@trpc/server 11.25.2-canary.4.g411501f77 → 11.25.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/fastify/index.cjs +1 -1
- package/dist/adapters/fastify/index.mjs +1 -1
- package/dist/adapters/ws.cjs +1 -1
- package/dist/adapters/ws.mjs +1 -1
- package/dist/{ws-ChTYDYLo.cjs → ws-BRFs3IJR.cjs} +13 -2
- package/dist/{ws-CTB2-0_W.mjs → ws-Bl1WQEXo.mjs} +14 -3
- package/dist/ws-Bl1WQEXo.mjs.map +1 -0
- package/dist/ws-D-DF_k_T.d.cts.map +1 -1
- package/dist/ws-lJRDMspc.d.mts.map +1 -1
- package/package.json +1 -1
- package/skills/adapter-aws-lambda/SKILL.md +1 -1
- package/skills/adapter-express/SKILL.md +1 -1
- package/skills/adapter-fastify/SKILL.md +1 -1
- package/skills/adapter-fetch/SKILL.md +1 -1
- package/skills/adapter-standalone/SKILL.md +1 -1
- package/skills/auth/SKILL.md +1 -1
- package/skills/caching/SKILL.md +1 -1
- package/skills/error-handling/SKILL.md +1 -1
- package/skills/middlewares/SKILL.md +1 -1
- package/skills/non-json-content-types/SKILL.md +1 -1
- package/skills/server-setup/SKILL.md +1 -1
- package/skills/server-side-calls/SKILL.md +1 -1
- package/skills/service-oriented-architecture/SKILL.md +1 -1
- package/skills/subscriptions/SKILL.md +1 -1
- package/skills/trpc-router/SKILL.md +1 -1
- package/skills/validators/SKILL.md +1 -1
- package/src/adapters/ws.ts +28 -2
- package/dist/ws-CTB2-0_W.mjs.map +0 -1
|
@@ -2,7 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
2
2
|
const require_getErrorShape = require("../../getErrorShape-BAuHhNuh.cjs");
|
|
3
3
|
const require_resolveResponse = require("../../resolveResponse-CiTYuZCi.cjs");
|
|
4
4
|
const require_node_http = require("../../node-http-BnGON5Za.cjs");
|
|
5
|
-
const require_ws = require("../../ws-
|
|
5
|
+
const require_ws = require("../../ws-BRFs3IJR.cjs");
|
|
6
6
|
//#region src/adapters/fastify/fastifyRequestHandler.ts
|
|
7
7
|
/**
|
|
8
8
|
* Handles one Fastify request for a router. `fastifyTRPCPlugin` uses it;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { n as _objectSpread2 } from "../../getErrorShape-B5jPKHJ3.mjs";
|
|
2
2
|
import { t as resolveResponse } from "../../resolveResponse-2MBY36PP.mjs";
|
|
3
3
|
import { i as incomingMessageToRequest } from "../../node-http-CyL_jN-0.mjs";
|
|
4
|
-
import { n as getWSConnectionHandler } from "../../ws-
|
|
4
|
+
import { n as getWSConnectionHandler } from "../../ws-Bl1WQEXo.mjs";
|
|
5
5
|
//#region src/adapters/fastify/fastifyRequestHandler.ts
|
|
6
6
|
/**
|
|
7
7
|
* Handles one Fastify request for a router. `fastifyTRPCPlugin` uses it;
|
package/dist/adapters/ws.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_ws = require("../ws-
|
|
2
|
+
const require_ws = require("../ws-BRFs3IJR.cjs");
|
|
3
3
|
exports.applyWSSHandler = require_ws.applyWSSHandler;
|
|
4
4
|
exports.getWSConnectionHandler = require_ws.getWSConnectionHandler;
|
|
5
5
|
exports.handleKeepAlive = require_ws.handleKeepAlive;
|
package/dist/adapters/ws.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { i as jsonEncoder, n as getWSConnectionHandler, r as handleKeepAlive, t as applyWSSHandler } from "../ws-
|
|
1
|
+
import { i as jsonEncoder, n as getWSConnectionHandler, r as handleKeepAlive, t as applyWSSHandler } from "../ws-Bl1WQEXo.mjs";
|
|
2
2
|
export { applyWSSHandler, getWSConnectionHandler, handleKeepAlive, jsonEncoder };
|
|
3
3
|
|
|
@@ -88,9 +88,11 @@ function getWSConnectionHandler(opts) {
|
|
|
88
88
|
var _opts$keepAlive;
|
|
89
89
|
const clientSubscriptions = /* @__PURE__ */ new Map();
|
|
90
90
|
const abortController = new AbortController();
|
|
91
|
+
/** Releases the id after cleanup, cancelling closed-socket work on every exit. */
|
|
91
92
|
function registerSubscription(id, subscription) {
|
|
92
93
|
clientSubscriptions.set(id, subscription);
|
|
93
94
|
return require_resolveResponse.makeResource({}, () => {
|
|
95
|
+
if (client.readyState !== WEBSOCKET_OPEN && !subscription.signal.aborted) subscription.abort();
|
|
94
96
|
clientSubscriptions.delete(id);
|
|
95
97
|
});
|
|
96
98
|
}
|
|
@@ -98,7 +100,9 @@ function getWSConnectionHandler(opts) {
|
|
|
98
100
|
const { pingMs, pongWaitMs } = opts.keepAlive;
|
|
99
101
|
handleKeepAlive(client, pingMs, pongWaitMs);
|
|
100
102
|
}
|
|
103
|
+
/** Drops replies once closing starts, before the close event cancels work. */
|
|
101
104
|
function respond(untransformedJSON) {
|
|
105
|
+
if (client.readyState !== WEBSOCKET_OPEN) return;
|
|
102
106
|
client.send(encoder.encode(require_asyncGeneratorDelegate.transformTRPCResponse(router._def._config, untransformedJSON)));
|
|
103
107
|
}
|
|
104
108
|
/**
|
|
@@ -243,6 +247,7 @@ function getWSConnectionHandler(opts) {
|
|
|
243
247
|
* - if connection params are expected, they will be created once received
|
|
244
248
|
*/
|
|
245
249
|
let ctxPromise = require_node_http.createURL(req).searchParams.get("connectionParams") === "1" ? null : createCtxPromise(() => null);
|
|
250
|
+
/** Runs a decoded call; deferred subscription admission must respect disconnects. */
|
|
246
251
|
async function handleRequest(msg, batchIndex, ctxResult) {
|
|
247
252
|
const { id, jsonrpc } = msg;
|
|
248
253
|
if (id === null) {
|
|
@@ -321,13 +326,14 @@ function getWSConnectionHandler(opts) {
|
|
|
321
326
|
}));
|
|
322
327
|
return;
|
|
323
328
|
}
|
|
329
|
+
/** Keeps a subscription owned until admission, iteration and disposal settle. */
|
|
324
330
|
const execute = async () => {
|
|
325
331
|
try {
|
|
326
332
|
var _usingCtx$1 = require_resolveResponse._usingCtx();
|
|
327
333
|
_usingCtx$1.u(type === "subscription" ? registerSubscription(id, abortController) : null);
|
|
328
334
|
const res = await ctxResult;
|
|
329
335
|
if (!res.ok) throw res.error;
|
|
330
|
-
if (abortController.signal.aborted) return;
|
|
336
|
+
if (abortController.signal.aborted || type === "subscription" && client.readyState !== WEBSOCKET_OPEN) return;
|
|
331
337
|
const result = await require_asyncGeneratorDelegate.callProcedure({
|
|
332
338
|
router,
|
|
333
339
|
path,
|
|
@@ -357,8 +363,13 @@ function getWSConnectionHandler(opts) {
|
|
|
357
363
|
message: `Subscription ${path} did not return an observable or a AsyncGenerator`,
|
|
358
364
|
code: "INTERNAL_SERVER_ERROR"
|
|
359
365
|
});
|
|
366
|
+
if (client.readyState !== WEBSOCKET_OPEN) {
|
|
367
|
+
abort();
|
|
368
|
+
if (require_observable.isObservable(result)) return;
|
|
369
|
+
}
|
|
360
370
|
const iterable = require_observable.isObservable(result) ? require_observable.observableToAsyncIterable(result, abortController.signal) : result;
|
|
361
|
-
if (abortController.signal.aborted) {
|
|
371
|
+
if (abortController.signal.aborted || client.readyState !== WEBSOCKET_OPEN) {
|
|
372
|
+
abort();
|
|
362
373
|
try {
|
|
363
374
|
try {
|
|
364
375
|
var _usingCtx3 = require_resolveResponse._usingCtx();
|
|
@@ -88,9 +88,11 @@ function getWSConnectionHandler(opts) {
|
|
|
88
88
|
var _opts$keepAlive;
|
|
89
89
|
const clientSubscriptions = /* @__PURE__ */ new Map();
|
|
90
90
|
const abortController = new AbortController();
|
|
91
|
+
/** Releases the id after cleanup, cancelling closed-socket work on every exit. */
|
|
91
92
|
function registerSubscription(id, subscription) {
|
|
92
93
|
clientSubscriptions.set(id, subscription);
|
|
93
94
|
return makeResource({}, () => {
|
|
95
|
+
if (client.readyState !== WEBSOCKET_OPEN && !subscription.signal.aborted) subscription.abort();
|
|
94
96
|
clientSubscriptions.delete(id);
|
|
95
97
|
});
|
|
96
98
|
}
|
|
@@ -98,7 +100,9 @@ function getWSConnectionHandler(opts) {
|
|
|
98
100
|
const { pingMs, pongWaitMs } = opts.keepAlive;
|
|
99
101
|
handleKeepAlive(client, pingMs, pongWaitMs);
|
|
100
102
|
}
|
|
103
|
+
/** Drops replies once closing starts, before the close event cancels work. */
|
|
101
104
|
function respond(untransformedJSON) {
|
|
105
|
+
if (client.readyState !== WEBSOCKET_OPEN) return;
|
|
102
106
|
client.send(encoder.encode(transformTRPCResponse(router._def._config, untransformedJSON)));
|
|
103
107
|
}
|
|
104
108
|
/**
|
|
@@ -243,6 +247,7 @@ function getWSConnectionHandler(opts) {
|
|
|
243
247
|
* - if connection params are expected, they will be created once received
|
|
244
248
|
*/
|
|
245
249
|
let ctxPromise = createURL(req).searchParams.get("connectionParams") === "1" ? null : createCtxPromise(() => null);
|
|
250
|
+
/** Runs a decoded call; deferred subscription admission must respect disconnects. */
|
|
246
251
|
async function handleRequest(msg, batchIndex, ctxResult) {
|
|
247
252
|
const { id, jsonrpc } = msg;
|
|
248
253
|
if (id === null) {
|
|
@@ -321,13 +326,14 @@ function getWSConnectionHandler(opts) {
|
|
|
321
326
|
}));
|
|
322
327
|
return;
|
|
323
328
|
}
|
|
329
|
+
/** Keeps a subscription owned until admission, iteration and disposal settle. */
|
|
324
330
|
const execute = async () => {
|
|
325
331
|
try {
|
|
326
332
|
var _usingCtx$1 = _usingCtx();
|
|
327
333
|
_usingCtx$1.u(type === "subscription" ? registerSubscription(id, abortController) : null);
|
|
328
334
|
const res = await ctxResult;
|
|
329
335
|
if (!res.ok) throw res.error;
|
|
330
|
-
if (abortController.signal.aborted) return;
|
|
336
|
+
if (abortController.signal.aborted || type === "subscription" && client.readyState !== WEBSOCKET_OPEN) return;
|
|
331
337
|
const result = await callProcedure({
|
|
332
338
|
router,
|
|
333
339
|
path,
|
|
@@ -357,8 +363,13 @@ function getWSConnectionHandler(opts) {
|
|
|
357
363
|
message: `Subscription ${path} did not return an observable or a AsyncGenerator`,
|
|
358
364
|
code: "INTERNAL_SERVER_ERROR"
|
|
359
365
|
});
|
|
366
|
+
if (client.readyState !== WEBSOCKET_OPEN) {
|
|
367
|
+
abort();
|
|
368
|
+
if (isObservable(result)) return;
|
|
369
|
+
}
|
|
360
370
|
const iterable = isObservable(result) ? observableToAsyncIterable(result, abortController.signal) : result;
|
|
361
|
-
if (abortController.signal.aborted) {
|
|
371
|
+
if (abortController.signal.aborted || client.readyState !== WEBSOCKET_OPEN) {
|
|
372
|
+
abort();
|
|
362
373
|
try {
|
|
363
374
|
try {
|
|
364
375
|
var _usingCtx3 = _usingCtx();
|
|
@@ -663,4 +674,4 @@ function applyWSSHandler(opts) {
|
|
|
663
674
|
export { jsonEncoder as i, getWSConnectionHandler as n, handleKeepAlive as r, applyWSSHandler as t };
|
|
664
675
|
|
|
665
676
|
|
|
666
|
-
//# sourceMappingURL=ws-
|
|
677
|
+
//# sourceMappingURL=ws-Bl1WQEXo.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ws-Bl1WQEXo.mjs","names":["callTRPCProcedure"],"sources":["../src/adapters/wsEncoder.ts","../src/adapters/ws.ts"],"sourcesContent":["/**\n * Encodes the messages a WebSocket server sends and decodes the ones it\n * gets. The client's `experimental_encoder` must match.\n *\n * @example\n * ```ts\n * const customEncoder: Encoder = {\n * encode: (data) => myFormat.stringify(data),\n * decode: (data) => myFormat.parse(data),\n * };\n * ```\n */\nexport interface Encoder {\n /** Encodes a message to send. */\n encode(data: unknown): string | Uint8Array<ArrayBuffer>;\n /** Decodes a received message. */\n decode(data: string | ArrayBuffer | Uint8Array): unknown;\n}\n\n/**\n * The default encoder: JSON in text frames.\n */\nexport const jsonEncoder: Encoder = {\n encode: (data) => JSON.stringify(data),\n decode: (data) => {\n if (typeof data !== 'string') {\n throw new Error(\n 'jsonEncoder received binary data. JSON uses text frames. ' +\n 'Use a binary encoder for binary data.',\n );\n }\n return JSON.parse(data);\n },\n};\n","import type { IncomingMessage } from 'http';\nimport type { WebSocketServer, WebSocket as WsWebSocket } from 'ws';\nimport type {\n AnyRouter,\n CreateContextCallback,\n inferRouterContext,\n} from '../@trpc/server';\nimport {\n callTRPCProcedure,\n getErrorShape,\n getTRPCErrorFromUnknown,\n transformTRPCResponse,\n TRPCError,\n} from '../@trpc/server';\nimport type { TRPCRequestInfo } from '../@trpc/server/http';\nimport { type BaseHandlerOptions } from '../@trpc/server/http';\nimport { parseTRPCMessage, TRPC_ERROR_CODES_BY_KEY } from '../@trpc/server/rpc';\n// @trpc/server/rpc\nimport type {\n TRPCClientOutgoingMessage,\n TRPCConnectionParamsMessage,\n TRPCErrorShape,\n TRPCReconnectNotification,\n TRPCResponseMessage,\n TRPCResultMessage,\n} from '../@trpc/server/rpc';\nimport { parseConnectionParamsFromUnknown } from '../http';\nimport { isObservable, observableToAsyncIterable } from '../observable';\n// oxlint-disable-next-line no-restricted-imports\nimport {\n isAbortError,\n isAsyncIterable,\n isObject,\n isPromise,\n isTrackedEnvelope,\n makeResource,\n run,\n type MaybePromise,\n} from '../unstable-core-do-not-import';\n// oxlint-disable-next-line no-restricted-imports\nimport type { Result } from '../unstable-core-do-not-import';\n// oxlint-disable-next-line no-restricted-imports\nimport { iteratorResource } from '../unstable-core-do-not-import/stream/utils/asyncIterable';\nimport { Unpromise } from '../vendor/unpromise';\nimport { createURL, type NodeHTTPCreateContextFnOptions } from './node-http';\nimport type { Encoder } from './wsEncoder';\nimport { jsonEncoder } from './wsEncoder';\n\n/**\n * Importing ws causes a build error\n * @see https://github.com/trpc/trpc/pull/5279\n */\nconst WEBSOCKET_OPEN = 1; /* ws.WebSocket.OPEN */\n\nfunction settle<TValue>(promise: Promise<TValue>): Promise<Result<TValue>> {\n return promise.then(\n (value): Result<TValue> => ({ ok: true, value }),\n (error: unknown): Result<TValue> => ({ ok: false, error }),\n );\n}\n\n/**\n * What `await using` rejects with when disposal fails after the scope threw:\n * `error` is the disposal failure and `suppressed` the original error.\n */\nfunction isSuppressedError(\n cause: unknown,\n): cause is { error: unknown; suppressed: unknown } {\n return (\n isObject(cause) &&\n cause['name'] === 'SuppressedError' &&\n 'error' in cause &&\n 'suppressed' in cause\n );\n}\n\n/**\n * What the client gets when its error can't be formatted or encoded. It says\n * nothing about the error, which is what `errorFormatter` would have hidden.\n */\nconst fallbackErrorShape: TRPCErrorShape = {\n code: TRPC_ERROR_CODES_BY_KEY.INTERNAL_SERVER_ERROR,\n message: 'Internal server error',\n data: { code: 'INTERNAL_SERVER_ERROR', httpStatus: 500 },\n};\n\n/**\n * A procedure that gives up because its subscription was cancelled rejects\n * with an `AbortError`, which is wrapped as an INTERNAL_SERVER_ERROR.\n */\nfunction isCancelledSetup(error: TRPCError, signal: AbortSignal) {\n return (\n signal.aborted &&\n error.code === 'INTERNAL_SERVER_ERROR' &&\n isAbortError(error.cause)\n );\n}\n\n/**\n * What `createContext` gets in the WebSocket adapter: the upgrade request\n * as `req`, the socket as `res`, and `info`. It's called once per\n * connection.\n * @see https://trpc.io/docs/server/websockets#creating-a-websocket-server\n * @public\n */\nexport type CreateWSSContextFnOptions = NodeHTTPCreateContextFnOptions<\n IncomingMessage,\n WsWebSocket\n>;\n\n/**\n * The `createContext` function the WebSocket adapter takes.\n * @public\n */\nexport type CreateWSSContextFn<TRouter extends AnyRouter> = (\n opts: CreateWSSContextFnOptions,\n) => MaybePromise<inferRouterContext<TRouter>>;\n\n/** The options of `getWSConnectionHandler`. */\nexport type WSConnectionHandlerOptions<TRouter extends AnyRouter> =\n BaseHandlerOptions<TRouter, IncomingMessage> &\n CreateContextCallback<\n inferRouterContext<TRouter>,\n CreateWSSContextFn<TRouter>\n >;\n\n/**\n * The options of `applyWSSHandler`.\n * @see https://trpc.io/docs/server/websockets#creating-a-websocket-server\n */\nexport type WSSHandlerOptions<TRouter extends AnyRouter> =\n WSConnectionHandlerOptions<TRouter> & {\n /** The `ws` server to serve the router on. */\n wss: WebSocketServer;\n /** Only connections whose URL starts with this are served. */\n prefix?: string;\n /**\n * Sends pings to each client and closes connections that stop\n * answering.\n */\n keepAlive?: {\n /**\n * Whether to send pings.\n * @default false\n */\n enabled: boolean;\n /**\n * How long a connection can be quiet before a ping, in milliseconds.\n * @default 30_000\n */\n pingMs?: number;\n /**\n * How long to wait for a pong before closing the connection, in\n * milliseconds.\n * @default 5_000\n */\n pongWaitMs?: number;\n };\n /**\n * Stops answering clients' pings. Meant for tests.\n * @default false\n */\n dangerouslyDisablePong?: boolean;\n /**\n * Encodes and decodes messages, for formats other than JSON.\n * Experimental: it may change in any release.\n * @default jsonEncoder\n */\n experimental_encoder?: Encoder;\n };\n\n/**\n * `iterator.next()` for a subscription loop that races it against the\n * subscription's `signal`, with a rejection turned into a `TRPCError`.\n *\n * Once the subscription is stopped, the loop doesn't wait for this call, so a\n * rejection after the stop, such as a teardown that throws, goes to\n * `onErrorAfterStop` and resolves `'abort'`. An `AbortError` is how a stopped\n * subscription is expected to end, and isn't reported.\n */\nfunction nextUnlessStopped<TValue, TReturn>(\n iterator: AsyncIterator<TValue, TReturn>,\n signal: AbortSignal,\n onErrorAfterStop: (error: TRPCError) => void,\n): Promise<IteratorResult<TValue, TReturn> | TRPCError | 'abort'> {\n return iterator.next().catch((cause: unknown) => {\n const error = getTRPCErrorFromUnknown(cause);\n if (!signal.aborted) {\n return error;\n }\n if (!isAbortError(error.cause)) {\n onErrorAfterStop(error);\n }\n return 'abort';\n });\n}\n\n/**\n * Returns a `ws` connection listener that serves a router. `applyWSSHandler`\n * uses it; call it to attach tRPC to your own WebSocket server.\n */\nexport function getWSConnectionHandler<TRouter extends AnyRouter>(\n opts: WSSHandlerOptions<TRouter>,\n) {\n const { createContext, router } = opts;\n const { transformer } = router._def._config;\n const encoder = opts.experimental_encoder ?? jsonEncoder;\n\n return (client: WsWebSocket, req: IncomingMessage) => {\n type Context = inferRouterContext<TRouter>;\n type ContextResult = Result<Context>;\n\n const clientSubscriptions = new Map<number | string, AbortController>();\n const abortController = new AbortController();\n\n /** Releases the id after cleanup, cancelling closed-socket work on every exit. */\n function registerSubscription(\n id: number | string,\n subscription: AbortController,\n ) {\n clientSubscriptions.set(id, subscription);\n return makeResource({}, () => {\n if (\n client.readyState !== WEBSOCKET_OPEN &&\n !subscription.signal.aborted\n ) {\n subscription.abort();\n }\n clientSubscriptions.delete(id);\n });\n }\n\n if (opts.keepAlive?.enabled) {\n const { pingMs, pongWaitMs } = opts.keepAlive;\n handleKeepAlive(client, pingMs, pongWaitMs);\n }\n\n /** Drops replies once closing starts, before the close event cancels work. */\n function respond(untransformedJSON: TRPCResponseMessage) {\n if (client.readyState !== WEBSOCKET_OPEN) return;\n client.send(\n encoder.encode(\n transformTRPCResponse(router._def._config, untransformedJSON),\n ),\n );\n }\n\n type ErrorInfo = Parameters<NonNullable<typeof opts.onError>>[0];\n\n /**\n * `onError` runs in listeners and in promises nothing awaits, where a\n * throw or a rejection would crash the process, so either goes to\n * `onFailure` instead.\n */\n function guardOnError(\n info: ErrorInfo,\n onFailure: (cause: unknown) => void,\n ) {\n try {\n const result: unknown = opts.onError?.(info);\n if (isPromise(result)) {\n result.catch(onFailure);\n }\n } catch (cause) {\n onFailure(cause);\n }\n }\n\n /** Reports an error to `onError`, ignoring an `onError` that fails. */\n function callOnError(info: ErrorInfo) {\n guardOnError(info, () => {\n // ignored, see guardOnError\n });\n }\n\n /**\n * Reports a failure of the adapter's own error handling, such as an\n * `errorFormatter` that throws or a reply that can't be sent. It's logged\n * when `onError` is missing or fails, so it's never dropped silently.\n */\n function reportInternalError(info: ErrorInfo) {\n const log = () => {\n // oxlint-disable-next-line no-console\n console.error('[@trpc/server/adapters/ws]', info.error);\n };\n if (!opts.onError) {\n log();\n return;\n }\n guardOnError(info, log);\n }\n\n /**\n * The error shape the client gets, or a minimal one when `errorFormatter`\n * throws, so that the request is still answered.\n */\n function errorShape(call: Omit<ErrorInfo, 'ctx' | 'req'>): TRPCErrorShape {\n try {\n return getErrorShape({ config: router._def._config, ctx, ...call });\n } catch (cause) {\n reportInternalError({\n ...call,\n error: getTRPCErrorFromUnknown(cause),\n ctx,\n req,\n });\n return fallbackErrorShape;\n }\n }\n\n function reportConnectionError(cause: unknown) {\n reportInternalError({\n error: getTRPCErrorFromUnknown(cause),\n path: undefined,\n type: 'unknown',\n ctx,\n req,\n input: undefined,\n });\n }\n\n /**\n * Sends a response that isn't tied to a request, reporting it if it\n * can't be built or sent. One that can't be sent is replaced by the\n * fallback error, so that a client still learns it was rejected.\n */\n function respondOrReport(response: () => TRPCResponseMessage) {\n let message: TRPCResponseMessage | null = null;\n try {\n message = response();\n respond(message);\n } catch (cause) {\n reportConnectionError(cause);\n if (message === null) {\n return;\n }\n try {\n respond({\n id: message.id,\n jsonrpc: message.jsonrpc,\n error: fallbackErrorShape,\n });\n } catch {\n // the same failure, and it was reported above\n }\n }\n }\n\n async function createCtxPromise(\n getConnectionParams: () => TRPCRequestInfo['connectionParams'],\n ): Promise<ContextResult> {\n try {\n return await run(async (): Promise<ContextResult> => {\n ctx = await createContext?.({\n req,\n res: client,\n info: {\n connectionParams: getConnectionParams(),\n calls: [],\n isBatchCall: false,\n accept: null,\n type: 'unknown',\n signal: abortController.signal,\n url: null,\n },\n });\n\n return {\n ok: true,\n value: ctx,\n };\n });\n } catch (cause) {\n const error = getTRPCErrorFromUnknown(cause);\n callOnError({\n error,\n path: undefined,\n type: 'unknown',\n ctx,\n req,\n input: undefined,\n });\n respondOrReport(() => ({\n id: null,\n error: errorShape({\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n }),\n }));\n\n // close in next tick\n (globalThis.setImmediate ?? globalThis.setTimeout)(() => {\n client.close();\n });\n return {\n ok: false,\n error,\n };\n }\n }\n\n let ctx: Context | undefined = undefined;\n\n /**\n * promise for initializing the context\n *\n * - the context promise will be created immediately on connection if no connectionParams are expected\n * - if connection params are expected, they will be created once received\n */\n let ctxPromise =\n createURL(req).searchParams.get('connectionParams') === '1'\n ? null\n : createCtxPromise(() => null);\n\n /** Runs a decoded call; deferred subscription admission must respect disconnects. */\n async function handleRequest(\n msg: TRPCClientOutgoingMessage,\n batchIndex: number,\n ctxResult: Promise<ContextResult>,\n ) {\n const { id, jsonrpc } = msg;\n\n if (id === null) {\n const error = getTRPCErrorFromUnknown(\n new TRPCError({\n code: 'PARSE_ERROR',\n message: '`id` is required',\n }),\n );\n callOnError({\n error,\n path: undefined,\n type: 'unknown',\n ctx,\n req,\n input: undefined,\n });\n respond({\n id,\n jsonrpc,\n error: errorShape({\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n }),\n });\n return;\n }\n if (msg.method === 'subscription.stop') {\n clientSubscriptions.get(id)?.abort();\n return;\n }\n const { path, lastEventId } = msg.params;\n let { input } = msg.params;\n const type = msg.method;\n\n if (lastEventId !== undefined) {\n if (isObject(input)) {\n input = {\n ...input,\n lastEventId: lastEventId,\n };\n } else {\n input ??= {\n lastEventId: lastEventId,\n };\n }\n }\n const abortController = new AbortController();\n // `abort()` builds an AbortError with a stack trace even when the\n // signal is already aborted, which is the common case on a stop.\n const abort = () => {\n if (!abortController.signal.aborted) {\n abortController.abort();\n }\n };\n const reportError = (cause: unknown) => {\n const error = getTRPCErrorFromUnknown(cause);\n callOnError({ error, path, type, ctx, req, input });\n return error;\n };\n const respondWithError = (cause: unknown) => {\n const error = reportError(cause);\n respond({\n id,\n jsonrpc,\n error: errorShape({ error, type, path, input }),\n });\n };\n\n if (type === 'subscription' && clientSubscriptions.has(id)) {\n // duplicate request ids for client\n respondWithError(\n new TRPCError({\n message: `Duplicate id ${id}`,\n code: 'BAD_REQUEST',\n }),\n );\n return;\n }\n\n /** Keeps a subscription owned until admission, iteration and disposal settle. */\n const execute = async () => {\n // Registered before any await so that a stop or a disconnect during\n // context creation or the procedure call cancels the subscription.\n // The id is freed once this has settled, after the iterator's\n // disposal and right before the client is told it may reuse it.\n using _subscription =\n type === 'subscription'\n ? registerSubscription(id, abortController)\n : null;\n\n const res = await ctxResult;\n if (!res.ok) {\n throw res.error;\n }\n\n if (\n abortController.signal.aborted ||\n (type === 'subscription' && client.readyState !== WEBSOCKET_OPEN)\n ) {\n return;\n }\n\n const result = await callTRPCProcedure({\n router,\n path,\n getRawInput: async () => input,\n ctx,\n type,\n signal: abortController.signal,\n batchIndex,\n });\n\n const isIterableResult =\n isAsyncIterable(result) || isObservable(result);\n\n if (type !== 'subscription') {\n if (isIterableResult) {\n throw new TRPCError({\n code: 'UNSUPPORTED_MEDIA_TYPE',\n message: `Cannot return an async iterable or observable from a ${type} procedure with WebSockets`,\n });\n }\n // send the value as data if the method is not a subscription\n respond({\n id,\n jsonrpc,\n result: {\n type: 'data',\n data: result,\n },\n });\n return;\n }\n\n if (!isIterableResult) {\n throw new TRPCError({\n message: `Subscription ${path} did not return an observable or a AsyncGenerator`,\n code: 'INTERNAL_SERVER_ERROR',\n });\n }\n\n // Closing precedes the close event: cancel signal-owned work before\n // releasing the id or waiting for cleanup. Conversion would subscribe\n // immediately, so leave a late observable untouched.\n if (client.readyState !== WEBSOCKET_OPEN) {\n abort();\n if (isObservable(result)) return;\n }\n\n const iterable = isObservable(result)\n ? observableToAsyncIterable(result, abortController.signal)\n : result;\n\n // A failed iterator cleanup is reported to the server only: the\n // client still gets `stopped`, so a subscription that completed or\n // was stopped doesn't turn into a failed one.\n if (\n abortController.signal.aborted ||\n client.readyState !== WEBSOCKET_OPEN\n ) {\n abort();\n try {\n // dispose the iterator without consuming it\n await using _iterator = iteratorResource(iterable);\n } catch (cause) {\n reportError(cause);\n }\n return;\n }\n\n respond({\n id,\n jsonrpc,\n result: {\n type: 'started',\n },\n });\n\n let ended = false;\n try {\n await using iterator = iteratorResource(iterable);\n let completed = false;\n // Disposed before the iterator, so cleanup that waits for\n // cancellation is woken when iteration ends other than by `done`.\n using _abortUnlessCompleted = makeResource({}, () => {\n if (!completed) {\n abort();\n }\n });\n\n const abortPromise = new Promise<'abort'>((resolve) => {\n abortController.signal.onabort = () => resolve('abort');\n });\n // We need those declarations outside the loop for garbage collection reasons. If they\n // were declared inside, they would not be freed until the next value is present.\n let next:\n | null\n | TRPCError\n | Awaited<\n typeof abortPromise | ReturnType<(typeof iterator)['next']>\n >;\n let result: null | TRPCResultMessage<unknown>['result'];\n\n while (true) {\n next = await Unpromise.race([\n nextUnlessStopped(iterator, abortController.signal, (error) =>\n callOnError({ error, path, type, ctx, req, input }),\n ),\n abortPromise,\n ]);\n\n if (next === 'abort') {\n break;\n }\n if (next instanceof Error) {\n // Report the error only after the iterator's disposal settles.\n throw next;\n }\n if (next.done) {\n completed = true;\n break;\n }\n\n result = {\n type: 'data',\n data: next.value,\n };\n\n if (isTrackedEnvelope(next.value)) {\n const [id, data] = next.value;\n result.id = id;\n result.data = {\n id,\n data,\n };\n }\n\n respond({\n id,\n jsonrpc,\n result,\n });\n\n // free up references for garbage collection\n next = null;\n result = null;\n }\n ended = true;\n } catch (cause) {\n abort();\n if (ended) {\n reportError(cause);\n } else if (isSuppressedError(cause)) {\n // the client gets the iteration error, the server both\n respondWithError(cause.suppressed);\n reportError(cause.error);\n } else {\n respondWithError(cause);\n }\n }\n };\n\n const outcome = await settle(execute());\n if (!outcome.ok) {\n const error = getTRPCErrorFromUnknown(outcome.error);\n if (!isCancelledSetup(error, abortController.signal)) {\n try {\n respondWithError(error);\n } catch (cause) {\n // the error reply couldn't be encoded or sent\n reportInternalError({\n error: getTRPCErrorFromUnknown(cause),\n path,\n type,\n ctx,\n req,\n input,\n });\n respondOrReport(() => ({ id, jsonrpc, error: fallbackErrorShape }));\n }\n return;\n }\n }\n if (type === 'subscription') {\n respond({ id, jsonrpc, result: { type: 'stopped' } });\n }\n }\n client.on('message', (rawData, isBinary) => {\n // Handle PING/PONG as text regardless of encoder\n if (!isBinary) {\n // oxlint-disable-next-line typescript/no-base-to-string\n const msgStr = rawData.toString();\n if (msgStr === 'PONG') {\n return;\n }\n if (msgStr === 'PING') {\n if (!opts.dangerouslyDisablePong) {\n client.send('PONG');\n }\n return;\n }\n }\n\n // Convert rawData to a format our encoder accepts\n // ws gives us Buffer for both text and binary frames\n if (!Buffer.isBuffer(rawData)) {\n const error = new TRPCError({\n code: 'UNPROCESSABLE_CONTENT',\n message: 'Unexpected WebSocket message format',\n });\n respondOrReport(() => ({\n id: null,\n error: errorShape({\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n }),\n }));\n return;\n }\n const data: string | Uint8Array = isBinary\n ? rawData\n : rawData.toString('utf8');\n\n if (!ctxPromise) {\n // If the ctxPromise wasn't created immediately, we're expecting the first message to be a TRPCConnectionParamsMessage\n ctxPromise = createCtxPromise(() => {\n let msg;\n try {\n msg = encoder.decode(data) as TRPCConnectionParamsMessage;\n\n if (!isObject(msg)) {\n throw new Error('Message was not an object');\n }\n } catch (cause) {\n throw new TRPCError({\n code: 'PARSE_ERROR',\n message: `Malformed TRPCConnectionParamsMessage`,\n cause,\n });\n }\n\n const connectionParams = parseConnectionParamsFromUnknown(msg.data);\n\n return connectionParams;\n });\n return;\n }\n\n const parsedMsgs = run(() => {\n try {\n const msgJSON: unknown = encoder.decode(data);\n const msgs: unknown[] = Array.isArray(msgJSON) ? msgJSON : [msgJSON];\n\n if (\n Array.isArray(msgJSON) &&\n typeof opts.maxBatchSize === 'number' &&\n msgs.length > opts.maxBatchSize\n ) {\n const error = new TRPCError({\n code: 'BAD_REQUEST',\n message: `Batch call exceeds maximum size`,\n });\n callOnError({\n error,\n path: undefined,\n type: 'unknown',\n ctx,\n req,\n input: undefined,\n });\n const shape = errorShape({\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n });\n\n // Checked before parsing so that no input is deserialized.\n // Every request in the batch gets the error, as a batched HTTP\n // call does, so that clients do not wait for a response forever.\n let responded = false;\n for (const raw of msgs) {\n if (\n isObject(raw) &&\n raw['method'] !== 'subscription.stop' &&\n (typeof raw['id'] === 'number' || typeof raw['id'] === 'string')\n ) {\n const id = raw['id'];\n const jsonrpc = raw['jsonrpc'] === '2.0' ? '2.0' : undefined;\n respondOrReport(() => ({ id, jsonrpc, error: shape }));\n responded = true;\n }\n }\n if (!responded) {\n respondOrReport(() => ({ id: null, error: shape }));\n }\n return [];\n }\n\n return msgs.map((raw) => parseTRPCMessage(raw, transformer));\n } catch (cause) {\n const error = new TRPCError({\n code: 'PARSE_ERROR',\n cause,\n });\n\n respondOrReport(() => ({\n id: null,\n error: errorShape({\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n }),\n }));\n\n return [];\n }\n });\n\n for (const [index, msg] of parsedMsgs.entries()) {\n handleRequest(msg, index, ctxPromise).catch(reportConnectionError);\n }\n });\n\n // WebSocket errors should be handled, as otherwise unhandled exceptions will crash Node.js.\n // This line was introduced after the following error brought down production systems:\n // \"RangeError: Invalid WebSocket frame: RSV2 and RSV3 must be clear\"\n // Here is the relevant discussion: https://github.com/websockets/ws/issues/1354#issuecomment-774616962\n client.on('error', (cause) => {\n callOnError({\n ctx,\n error: getTRPCErrorFromUnknown(cause),\n input: undefined,\n path: undefined,\n type: 'unknown',\n req,\n });\n });\n\n client.once('close', () => {\n for (const sub of clientSubscriptions.values()) {\n sub.abort();\n }\n clientSubscriptions.clear();\n abortController.abort();\n });\n };\n}\n\n/**\n * Pings a client after `pingMs` of quiet, and closes the connection if no\n * message comes within `pongWaitMs`.\n */\nexport function handleKeepAlive(\n client: WsWebSocket,\n pingMs = 30_000,\n pongWaitMs = 5_000,\n) {\n let timeout: NodeJS.Timeout | undefined = undefined;\n let ping: NodeJS.Timeout | undefined = undefined;\n\n const schedulePing = () => {\n const scheduleTimeout = () => {\n timeout = setTimeout(() => {\n client.terminate();\n }, pongWaitMs);\n };\n ping = setTimeout(() => {\n client.send('PING');\n\n scheduleTimeout();\n }, pingMs);\n };\n\n const onMessage = () => {\n clearTimeout(ping);\n clearTimeout(timeout);\n\n schedulePing();\n };\n\n client.on('message', onMessage);\n\n client.on('close', () => {\n clearTimeout(ping);\n clearTimeout(timeout);\n });\n\n schedulePing();\n}\n\n/**\n * Serves a router on a `ws` WebSocket server. Returns\n * `broadcastReconnectNotification()`, which tells every client to\n * reconnect, for example before a deploy.\n * @example\n * ```ts\n * const wss = new WebSocketServer({ port: 3001 });\n * const handler = applyWSSHandler({ wss, router: appRouter, createContext });\n * process.on('SIGTERM', () => {\n * handler.broadcastReconnectNotification();\n * wss.close();\n * });\n * ```\n * @see https://trpc.io/docs/server/websockets#creating-a-websocket-server\n */\nexport function applyWSSHandler<TRouter extends AnyRouter>(\n opts: WSSHandlerOptions<TRouter>,\n) {\n const encoder = opts.experimental_encoder ?? jsonEncoder;\n const onConnection = getWSConnectionHandler(opts);\n opts.wss.on('connection', (client, req) => {\n if (opts.prefix && !req.url?.startsWith(opts.prefix)) {\n return;\n }\n\n onConnection(client, req);\n });\n\n return {\n broadcastReconnectNotification: () => {\n const response: TRPCReconnectNotification = {\n id: null,\n method: 'reconnect',\n };\n const data = encoder.encode(response);\n for (const client of opts.wss.clients) {\n if (client.readyState === WEBSOCKET_OPEN) {\n client.send(data);\n }\n }\n },\n };\n}\n\nexport type { Encoder } from './wsEncoder';\nexport { jsonEncoder } from './wsEncoder';\n"],"mappings":";;;;;;;;;;;AAsBA,MAAa,cAAuB;CAClC,SAAS,SAAS,KAAK,UAAU,IAAI;CACrC,SAAS,SAAS;EAChB,IAAI,OAAO,SAAS,UAClB,MAAM,IAAI,MACR,gGAEF;EAEF,OAAO,KAAK,MAAM,IAAI;CACxB;AACF;;;;;;;ACmBA,MAAM,iBAAiB;AAEvB,SAAS,OAAe,SAAmD;CACzE,OAAO,QAAQ,MACZ,WAA2B;EAAE,IAAI;EAAM;CAAM,KAC7C,WAAoC;EAAE,IAAI;EAAO;CAAM,EAC1D;AACF;;;;;AAMA,SAAS,kBACP,OACkD;CAClD,OACE,SAAS,KAAK,KACd,MAAM,YAAY,qBAClB,WAAW,SACX,gBAAgB;AAEpB;;;;;AAMA,MAAM,qBAAqC;CACzC,MAAM,wBAAwB;CAC9B,SAAS;CACT,MAAM;EAAE,MAAM;EAAyB,YAAY;CAAI;AACzD;;;;;AAMA,SAAS,iBAAiB,OAAkB,QAAqB;CAC/D,OACE,OAAO,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,QAAA,2BAAA,KAAA,IAAA,yBAAwB;CAC7C,MAAM,eAAe,uBAAuB,IAAI;CAChD,KAAK,IAAI,GAAG,eAAe,QAAQ,QAAQ;;EACzC,IAAI,KAAK,UAAU,GAAA,WAAC,IAAI,SAAA,QAAA,aAAA,KAAA,IAAA,KAAA,IAAA,SAAK,WAAW,KAAK,MAAM,IACjD;EAGF,aAAa,QAAQ,GAAG;CAC1B,CAAC;CAED,OAAO,EACL,sCAAsC;EAKpC,MAAM,OAAO,QAAQ,OAAO;GAH1B,IAAI;GACJ,QAAQ;EAEyB,CAAC;EACpC,KAAK,MAAM,UAAU,KAAK,IAAI,SAC5B,IAAI,OAAO,eAAe,gBACxB,OAAO,KAAK,IAAI;CAGtB,EACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ws-D-DF_k_T.d.cts","names":[],"sources":["../src/adapters/ws.ts"],"mappings":";;;;;;;;;;;;KAyGY,4BAA4B,+BACtC,iBACA;;;;;KAOU,mBAAmB,gBAAgB,cAC7C,MAAM,8BACH,aAAa,mBAAmB;;KAGzB,2BAA2B,gBAAgB,aACrD,mBAAmB,SAAS,mBAC1B,sBACE,mBAAmB,UACnB,mBAAmB;;;;;KAOb,kBAAkB,gBAAgB,aAC5C,2BAA2B;;EAEzB,KAAK;;EAEL;;;;;EAKA;;;;;IAKE;;;;;IAKA;;;;;;IAMA;;;;;;EAMF;;;;;;EAMA,uBAAuB;;;;;;iBAiCX,uBAAuB,gBAAgB,WACrD,MAAM,kBAAkB,YAAQ,QAMhB,WAAW,KAAO;;;;;
|
|
1
|
+
{"version":3,"file":"ws-D-DF_k_T.d.cts","names":[],"sources":["../src/adapters/ws.ts"],"mappings":";;;;;;;;;;;;KAyGY,4BAA4B,+BACtC,iBACA;;;;;KAOU,mBAAmB,gBAAgB,cAC7C,MAAM,8BACH,aAAa,mBAAmB;;KAGzB,2BAA2B,gBAAgB,aACrD,mBAAmB,SAAS,mBAC1B,sBACE,mBAAmB,UACnB,mBAAmB;;;;;KAOb,kBAAkB,gBAAgB,aAC5C,2BAA2B;;EAEzB,KAAK;;EAEL;;;;;EAKA;;;;;IAKE;;;;;IAKA;;;;;;IAMA;;;;;;EAMF;;;;;;EAMA,uBAAuB;;;;;;iBAiCX,uBAAuB,gBAAgB,WACrD,MAAM,kBAAkB,YAAQ,QAMhB,WAAW,KAAO;;;;;iBAiqBpB,gBACd,QAAQ,WACR,iBACA;;;;;;;;;;;;;;;;iBAkDc,gBAAgB,gBAAgB,WAC9C,MAAM,kBAAkB;EAatB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ws-lJRDMspc.d.mts","names":[],"sources":["../src/adapters/ws.ts"],"mappings":";;;;;;;;;;;;KAyGY,4BAA4B,+BACtC,iBACA;;;;;KAOU,mBAAmB,gBAAgB,cAC7C,MAAM,8BACH,aAAa,mBAAmB;;KAGzB,2BAA2B,gBAAgB,aACrD,mBAAmB,SAAS,mBAC1B,sBACE,mBAAmB,UACnB,mBAAmB;;;;;KAOb,kBAAkB,gBAAgB,aAC5C,2BAA2B;;EAEzB,KAAK;;EAEL;;;;;EAKA;;;;;IAKE;;;;;IAKA;;;;;;IAMA;;;;;;EAMF;;;;;;EAMA,uBAAuB;;;;;;iBAiCX,uBAAuB,gBAAgB,WACrD,MAAM,kBAAkB,YAAQ,QAMhB,WAAW,KAAO;;;;;
|
|
1
|
+
{"version":3,"file":"ws-lJRDMspc.d.mts","names":[],"sources":["../src/adapters/ws.ts"],"mappings":";;;;;;;;;;;;KAyGY,4BAA4B,+BACtC,iBACA;;;;;KAOU,mBAAmB,gBAAgB,cAC7C,MAAM,8BACH,aAAa,mBAAmB;;KAGzB,2BAA2B,gBAAgB,aACrD,mBAAmB,SAAS,mBAC1B,sBACE,mBAAmB,UACnB,mBAAmB;;;;;KAOb,kBAAkB,gBAAgB,aAC5C,2BAA2B;;EAEzB,KAAK;;EAEL;;;;;EAKA;;;;;IAKE;;;;;IAKA;;;;;;IAMA;;;;;;EAMF;;;;;;EAMA,uBAAuB;;;;;;iBAiCX,uBAAuB,gBAAgB,WACrD,MAAM,kBAAkB,YAAQ,QAMhB,WAAW,KAAO;;;;;iBAiqBpB,gBACd,QAAQ,WACR,iBACA;;;;;;;;;;;;;;;;iBAkDc,gBAAgB,gBAAgB,WAC9C,MAAM,kBAAkB;EAatB"}
|
package/package.json
CHANGED
package/skills/auth/SKILL.md
CHANGED
package/skills/caching/SKILL.md
CHANGED
|
@@ -10,7 +10,7 @@ sources:
|
|
|
10
10
|
metadata:
|
|
11
11
|
type: composition
|
|
12
12
|
library: trpc
|
|
13
|
-
library_version: 11.25.2
|
|
13
|
+
library_version: 11.25.2
|
|
14
14
|
---
|
|
15
15
|
|
|
16
16
|
<!-- Generated from www/v11/docs/server/service-oriented-architecture.md by www/build/skills.ts. Edit the docs instead. -->
|
package/src/adapters/ws.ts
CHANGED
|
@@ -213,12 +213,19 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
213
213
|
const clientSubscriptions = new Map<number | string, AbortController>();
|
|
214
214
|
const abortController = new AbortController();
|
|
215
215
|
|
|
216
|
+
/** Releases the id after cleanup, cancelling closed-socket work on every exit. */
|
|
216
217
|
function registerSubscription(
|
|
217
218
|
id: number | string,
|
|
218
219
|
subscription: AbortController,
|
|
219
220
|
) {
|
|
220
221
|
clientSubscriptions.set(id, subscription);
|
|
221
222
|
return makeResource({}, () => {
|
|
223
|
+
if (
|
|
224
|
+
client.readyState !== WEBSOCKET_OPEN &&
|
|
225
|
+
!subscription.signal.aborted
|
|
226
|
+
) {
|
|
227
|
+
subscription.abort();
|
|
228
|
+
}
|
|
222
229
|
clientSubscriptions.delete(id);
|
|
223
230
|
});
|
|
224
231
|
}
|
|
@@ -228,7 +235,9 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
228
235
|
handleKeepAlive(client, pingMs, pongWaitMs);
|
|
229
236
|
}
|
|
230
237
|
|
|
238
|
+
/** Drops replies once closing starts, before the close event cancels work. */
|
|
231
239
|
function respond(untransformedJSON: TRPCResponseMessage) {
|
|
240
|
+
if (client.readyState !== WEBSOCKET_OPEN) return;
|
|
232
241
|
client.send(
|
|
233
242
|
encoder.encode(
|
|
234
243
|
transformTRPCResponse(router._def._config, untransformedJSON),
|
|
@@ -405,6 +414,7 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
405
414
|
? null
|
|
406
415
|
: createCtxPromise(() => null);
|
|
407
416
|
|
|
417
|
+
/** Runs a decoded call; deferred subscription admission must respect disconnects. */
|
|
408
418
|
async function handleRequest(
|
|
409
419
|
msg: TRPCClientOutgoingMessage,
|
|
410
420
|
batchIndex: number,
|
|
@@ -492,6 +502,7 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
492
502
|
return;
|
|
493
503
|
}
|
|
494
504
|
|
|
505
|
+
/** Keeps a subscription owned until admission, iteration and disposal settle. */
|
|
495
506
|
const execute = async () => {
|
|
496
507
|
// Registered before any await so that a stop or a disconnect during
|
|
497
508
|
// context creation or the procedure call cancels the subscription.
|
|
@@ -507,7 +518,10 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
507
518
|
throw res.error;
|
|
508
519
|
}
|
|
509
520
|
|
|
510
|
-
if (
|
|
521
|
+
if (
|
|
522
|
+
abortController.signal.aborted ||
|
|
523
|
+
(type === 'subscription' && client.readyState !== WEBSOCKET_OPEN)
|
|
524
|
+
) {
|
|
511
525
|
return;
|
|
512
526
|
}
|
|
513
527
|
|
|
@@ -550,6 +564,14 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
550
564
|
});
|
|
551
565
|
}
|
|
552
566
|
|
|
567
|
+
// Closing precedes the close event: cancel signal-owned work before
|
|
568
|
+
// releasing the id or waiting for cleanup. Conversion would subscribe
|
|
569
|
+
// immediately, so leave a late observable untouched.
|
|
570
|
+
if (client.readyState !== WEBSOCKET_OPEN) {
|
|
571
|
+
abort();
|
|
572
|
+
if (isObservable(result)) return;
|
|
573
|
+
}
|
|
574
|
+
|
|
553
575
|
const iterable = isObservable(result)
|
|
554
576
|
? observableToAsyncIterable(result, abortController.signal)
|
|
555
577
|
: result;
|
|
@@ -557,7 +579,11 @@ export function getWSConnectionHandler<TRouter extends AnyRouter>(
|
|
|
557
579
|
// A failed iterator cleanup is reported to the server only: the
|
|
558
580
|
// client still gets `stopped`, so a subscription that completed or
|
|
559
581
|
// was stopped doesn't turn into a failed one.
|
|
560
|
-
if (
|
|
582
|
+
if (
|
|
583
|
+
abortController.signal.aborted ||
|
|
584
|
+
client.readyState !== WEBSOCKET_OPEN
|
|
585
|
+
) {
|
|
586
|
+
abort();
|
|
561
587
|
try {
|
|
562
588
|
// dispose the iterator without consuming it
|
|
563
589
|
await using _iterator = iteratorResource(iterable);
|
package/dist/ws-CTB2-0_W.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ws-CTB2-0_W.mjs","names":["callTRPCProcedure"],"sources":["../src/adapters/wsEncoder.ts","../src/adapters/ws.ts"],"sourcesContent":["/**\n * Encodes the messages a WebSocket server sends and decodes the ones it\n * gets. The client's `experimental_encoder` must match.\n *\n * @example\n * ```ts\n * const customEncoder: Encoder = {\n * encode: (data) => myFormat.stringify(data),\n * decode: (data) => myFormat.parse(data),\n * };\n * ```\n */\nexport interface Encoder {\n /** Encodes a message to send. */\n encode(data: unknown): string | Uint8Array<ArrayBuffer>;\n /** Decodes a received message. */\n decode(data: string | ArrayBuffer | Uint8Array): unknown;\n}\n\n/**\n * The default encoder: JSON in text frames.\n */\nexport const jsonEncoder: Encoder = {\n encode: (data) => JSON.stringify(data),\n decode: (data) => {\n if (typeof data !== 'string') {\n throw new Error(\n 'jsonEncoder received binary data. JSON uses text frames. ' +\n 'Use a binary encoder for binary data.',\n );\n }\n return JSON.parse(data);\n },\n};\n","import type { IncomingMessage } from 'http';\nimport type { WebSocketServer, WebSocket as WsWebSocket } from 'ws';\nimport type {\n AnyRouter,\n CreateContextCallback,\n inferRouterContext,\n} from '../@trpc/server';\nimport {\n callTRPCProcedure,\n getErrorShape,\n getTRPCErrorFromUnknown,\n transformTRPCResponse,\n TRPCError,\n} from '../@trpc/server';\nimport type { TRPCRequestInfo } from '../@trpc/server/http';\nimport { type BaseHandlerOptions } from '../@trpc/server/http';\nimport { parseTRPCMessage, TRPC_ERROR_CODES_BY_KEY } from '../@trpc/server/rpc';\n// @trpc/server/rpc\nimport type {\n TRPCClientOutgoingMessage,\n TRPCConnectionParamsMessage,\n TRPCErrorShape,\n TRPCReconnectNotification,\n TRPCResponseMessage,\n TRPCResultMessage,\n} from '../@trpc/server/rpc';\nimport { parseConnectionParamsFromUnknown } from '../http';\nimport { isObservable, observableToAsyncIterable } from '../observable';\n// oxlint-disable-next-line no-restricted-imports\nimport {\n isAbortError,\n isAsyncIterable,\n isObject,\n isPromise,\n isTrackedEnvelope,\n makeResource,\n run,\n type MaybePromise,\n} from '../unstable-core-do-not-import';\n// oxlint-disable-next-line no-restricted-imports\nimport type { Result } from '../unstable-core-do-not-import';\n// oxlint-disable-next-line no-restricted-imports\nimport { iteratorResource } from '../unstable-core-do-not-import/stream/utils/asyncIterable';\nimport { Unpromise } from '../vendor/unpromise';\nimport { createURL, type NodeHTTPCreateContextFnOptions } from './node-http';\nimport type { Encoder } from './wsEncoder';\nimport { jsonEncoder } from './wsEncoder';\n\n/**\n * Importing ws causes a build error\n * @see https://github.com/trpc/trpc/pull/5279\n */\nconst WEBSOCKET_OPEN = 1; /* ws.WebSocket.OPEN */\n\nfunction settle<TValue>(promise: Promise<TValue>): Promise<Result<TValue>> {\n return promise.then(\n (value): Result<TValue> => ({ ok: true, value }),\n (error: unknown): Result<TValue> => ({ ok: false, error }),\n );\n}\n\n/**\n * What `await using` rejects with when disposal fails after the scope threw:\n * `error` is the disposal failure and `suppressed` the original error.\n */\nfunction isSuppressedError(\n cause: unknown,\n): cause is { error: unknown; suppressed: unknown } {\n return (\n isObject(cause) &&\n cause['name'] === 'SuppressedError' &&\n 'error' in cause &&\n 'suppressed' in cause\n );\n}\n\n/**\n * What the client gets when its error can't be formatted or encoded. It says\n * nothing about the error, which is what `errorFormatter` would have hidden.\n */\nconst fallbackErrorShape: TRPCErrorShape = {\n code: TRPC_ERROR_CODES_BY_KEY.INTERNAL_SERVER_ERROR,\n message: 'Internal server error',\n data: { code: 'INTERNAL_SERVER_ERROR', httpStatus: 500 },\n};\n\n/**\n * A procedure that gives up because its subscription was cancelled rejects\n * with an `AbortError`, which is wrapped as an INTERNAL_SERVER_ERROR.\n */\nfunction isCancelledSetup(error: TRPCError, signal: AbortSignal) {\n return (\n signal.aborted &&\n error.code === 'INTERNAL_SERVER_ERROR' &&\n isAbortError(error.cause)\n );\n}\n\n/**\n * What `createContext` gets in the WebSocket adapter: the upgrade request\n * as `req`, the socket as `res`, and `info`. It's called once per\n * connection.\n * @see https://trpc.io/docs/server/websockets#creating-a-websocket-server\n * @public\n */\nexport type CreateWSSContextFnOptions = NodeHTTPCreateContextFnOptions<\n IncomingMessage,\n WsWebSocket\n>;\n\n/**\n * The `createContext` function the WebSocket adapter takes.\n * @public\n */\nexport type CreateWSSContextFn<TRouter extends AnyRouter> = (\n opts: CreateWSSContextFnOptions,\n) => MaybePromise<inferRouterContext<TRouter>>;\n\n/** The options of `getWSConnectionHandler`. */\nexport type WSConnectionHandlerOptions<TRouter extends AnyRouter> =\n BaseHandlerOptions<TRouter, IncomingMessage> &\n CreateContextCallback<\n inferRouterContext<TRouter>,\n CreateWSSContextFn<TRouter>\n >;\n\n/**\n * The options of `applyWSSHandler`.\n * @see https://trpc.io/docs/server/websockets#creating-a-websocket-server\n */\nexport type WSSHandlerOptions<TRouter extends AnyRouter> =\n WSConnectionHandlerOptions<TRouter> & {\n /** The `ws` server to serve the router on. */\n wss: WebSocketServer;\n /** Only connections whose URL starts with this are served. */\n prefix?: string;\n /**\n * Sends pings to each client and closes connections that stop\n * answering.\n */\n keepAlive?: {\n /**\n * Whether to send pings.\n * @default false\n */\n enabled: boolean;\n /**\n * How long a connection can be quiet before a ping, in milliseconds.\n * @default 30_000\n */\n pingMs?: number;\n /**\n * How long to wait for a pong before closing the connection, in\n * milliseconds.\n * @default 5_000\n */\n pongWaitMs?: number;\n };\n /**\n * Stops answering clients' pings. Meant for tests.\n * @default false\n */\n dangerouslyDisablePong?: boolean;\n /**\n * Encodes and decodes messages, for formats other than JSON.\n * Experimental: it may change in any release.\n * @default jsonEncoder\n */\n experimental_encoder?: Encoder;\n };\n\n/**\n * `iterator.next()` for a subscription loop that races it against the\n * subscription's `signal`, with a rejection turned into a `TRPCError`.\n *\n * Once the subscription is stopped, the loop doesn't wait for this call, so a\n * rejection after the stop, such as a teardown that throws, goes to\n * `onErrorAfterStop` and resolves `'abort'`. An `AbortError` is how a stopped\n * subscription is expected to end, and isn't reported.\n */\nfunction nextUnlessStopped<TValue, TReturn>(\n iterator: AsyncIterator<TValue, TReturn>,\n signal: AbortSignal,\n onErrorAfterStop: (error: TRPCError) => void,\n): Promise<IteratorResult<TValue, TReturn> | TRPCError | 'abort'> {\n return iterator.next().catch((cause: unknown) => {\n const error = getTRPCErrorFromUnknown(cause);\n if (!signal.aborted) {\n return error;\n }\n if (!isAbortError(error.cause)) {\n onErrorAfterStop(error);\n }\n return 'abort';\n });\n}\n\n/**\n * Returns a `ws` connection listener that serves a router. `applyWSSHandler`\n * uses it; call it to attach tRPC to your own WebSocket server.\n */\nexport function getWSConnectionHandler<TRouter extends AnyRouter>(\n opts: WSSHandlerOptions<TRouter>,\n) {\n const { createContext, router } = opts;\n const { transformer } = router._def._config;\n const encoder = opts.experimental_encoder ?? jsonEncoder;\n\n return (client: WsWebSocket, req: IncomingMessage) => {\n type Context = inferRouterContext<TRouter>;\n type ContextResult = Result<Context>;\n\n const clientSubscriptions = new Map<number | string, AbortController>();\n const abortController = new AbortController();\n\n function registerSubscription(\n id: number | string,\n subscription: AbortController,\n ) {\n clientSubscriptions.set(id, subscription);\n return makeResource({}, () => {\n clientSubscriptions.delete(id);\n });\n }\n\n if (opts.keepAlive?.enabled) {\n const { pingMs, pongWaitMs } = opts.keepAlive;\n handleKeepAlive(client, pingMs, pongWaitMs);\n }\n\n function respond(untransformedJSON: TRPCResponseMessage) {\n client.send(\n encoder.encode(\n transformTRPCResponse(router._def._config, untransformedJSON),\n ),\n );\n }\n\n type ErrorInfo = Parameters<NonNullable<typeof opts.onError>>[0];\n\n /**\n * `onError` runs in listeners and in promises nothing awaits, where a\n * throw or a rejection would crash the process, so either goes to\n * `onFailure` instead.\n */\n function guardOnError(\n info: ErrorInfo,\n onFailure: (cause: unknown) => void,\n ) {\n try {\n const result: unknown = opts.onError?.(info);\n if (isPromise(result)) {\n result.catch(onFailure);\n }\n } catch (cause) {\n onFailure(cause);\n }\n }\n\n /** Reports an error to `onError`, ignoring an `onError` that fails. */\n function callOnError(info: ErrorInfo) {\n guardOnError(info, () => {\n // ignored, see guardOnError\n });\n }\n\n /**\n * Reports a failure of the adapter's own error handling, such as an\n * `errorFormatter` that throws or a reply that can't be sent. It's logged\n * when `onError` is missing or fails, so it's never dropped silently.\n */\n function reportInternalError(info: ErrorInfo) {\n const log = () => {\n // oxlint-disable-next-line no-console\n console.error('[@trpc/server/adapters/ws]', info.error);\n };\n if (!opts.onError) {\n log();\n return;\n }\n guardOnError(info, log);\n }\n\n /**\n * The error shape the client gets, or a minimal one when `errorFormatter`\n * throws, so that the request is still answered.\n */\n function errorShape(call: Omit<ErrorInfo, 'ctx' | 'req'>): TRPCErrorShape {\n try {\n return getErrorShape({ config: router._def._config, ctx, ...call });\n } catch (cause) {\n reportInternalError({\n ...call,\n error: getTRPCErrorFromUnknown(cause),\n ctx,\n req,\n });\n return fallbackErrorShape;\n }\n }\n\n function reportConnectionError(cause: unknown) {\n reportInternalError({\n error: getTRPCErrorFromUnknown(cause),\n path: undefined,\n type: 'unknown',\n ctx,\n req,\n input: undefined,\n });\n }\n\n /**\n * Sends a response that isn't tied to a request, reporting it if it\n * can't be built or sent. One that can't be sent is replaced by the\n * fallback error, so that a client still learns it was rejected.\n */\n function respondOrReport(response: () => TRPCResponseMessage) {\n let message: TRPCResponseMessage | null = null;\n try {\n message = response();\n respond(message);\n } catch (cause) {\n reportConnectionError(cause);\n if (message === null) {\n return;\n }\n try {\n respond({\n id: message.id,\n jsonrpc: message.jsonrpc,\n error: fallbackErrorShape,\n });\n } catch {\n // the same failure, and it was reported above\n }\n }\n }\n\n async function createCtxPromise(\n getConnectionParams: () => TRPCRequestInfo['connectionParams'],\n ): Promise<ContextResult> {\n try {\n return await run(async (): Promise<ContextResult> => {\n ctx = await createContext?.({\n req,\n res: client,\n info: {\n connectionParams: getConnectionParams(),\n calls: [],\n isBatchCall: false,\n accept: null,\n type: 'unknown',\n signal: abortController.signal,\n url: null,\n },\n });\n\n return {\n ok: true,\n value: ctx,\n };\n });\n } catch (cause) {\n const error = getTRPCErrorFromUnknown(cause);\n callOnError({\n error,\n path: undefined,\n type: 'unknown',\n ctx,\n req,\n input: undefined,\n });\n respondOrReport(() => ({\n id: null,\n error: errorShape({\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n }),\n }));\n\n // close in next tick\n (globalThis.setImmediate ?? globalThis.setTimeout)(() => {\n client.close();\n });\n return {\n ok: false,\n error,\n };\n }\n }\n\n let ctx: Context | undefined = undefined;\n\n /**\n * promise for initializing the context\n *\n * - the context promise will be created immediately on connection if no connectionParams are expected\n * - if connection params are expected, they will be created once received\n */\n let ctxPromise =\n createURL(req).searchParams.get('connectionParams') === '1'\n ? null\n : createCtxPromise(() => null);\n\n async function handleRequest(\n msg: TRPCClientOutgoingMessage,\n batchIndex: number,\n ctxResult: Promise<ContextResult>,\n ) {\n const { id, jsonrpc } = msg;\n\n if (id === null) {\n const error = getTRPCErrorFromUnknown(\n new TRPCError({\n code: 'PARSE_ERROR',\n message: '`id` is required',\n }),\n );\n callOnError({\n error,\n path: undefined,\n type: 'unknown',\n ctx,\n req,\n input: undefined,\n });\n respond({\n id,\n jsonrpc,\n error: errorShape({\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n }),\n });\n return;\n }\n if (msg.method === 'subscription.stop') {\n clientSubscriptions.get(id)?.abort();\n return;\n }\n const { path, lastEventId } = msg.params;\n let { input } = msg.params;\n const type = msg.method;\n\n if (lastEventId !== undefined) {\n if (isObject(input)) {\n input = {\n ...input,\n lastEventId: lastEventId,\n };\n } else {\n input ??= {\n lastEventId: lastEventId,\n };\n }\n }\n const abortController = new AbortController();\n // `abort()` builds an AbortError with a stack trace even when the\n // signal is already aborted, which is the common case on a stop.\n const abort = () => {\n if (!abortController.signal.aborted) {\n abortController.abort();\n }\n };\n const reportError = (cause: unknown) => {\n const error = getTRPCErrorFromUnknown(cause);\n callOnError({ error, path, type, ctx, req, input });\n return error;\n };\n const respondWithError = (cause: unknown) => {\n const error = reportError(cause);\n respond({\n id,\n jsonrpc,\n error: errorShape({ error, type, path, input }),\n });\n };\n\n if (type === 'subscription' && clientSubscriptions.has(id)) {\n // duplicate request ids for client\n respondWithError(\n new TRPCError({\n message: `Duplicate id ${id}`,\n code: 'BAD_REQUEST',\n }),\n );\n return;\n }\n\n const execute = async () => {\n // Registered before any await so that a stop or a disconnect during\n // context creation or the procedure call cancels the subscription.\n // The id is freed once this has settled, after the iterator's\n // disposal and right before the client is told it may reuse it.\n using _subscription =\n type === 'subscription'\n ? registerSubscription(id, abortController)\n : null;\n\n const res = await ctxResult;\n if (!res.ok) {\n throw res.error;\n }\n\n if (abortController.signal.aborted) {\n return;\n }\n\n const result = await callTRPCProcedure({\n router,\n path,\n getRawInput: async () => input,\n ctx,\n type,\n signal: abortController.signal,\n batchIndex,\n });\n\n const isIterableResult =\n isAsyncIterable(result) || isObservable(result);\n\n if (type !== 'subscription') {\n if (isIterableResult) {\n throw new TRPCError({\n code: 'UNSUPPORTED_MEDIA_TYPE',\n message: `Cannot return an async iterable or observable from a ${type} procedure with WebSockets`,\n });\n }\n // send the value as data if the method is not a subscription\n respond({\n id,\n jsonrpc,\n result: {\n type: 'data',\n data: result,\n },\n });\n return;\n }\n\n if (!isIterableResult) {\n throw new TRPCError({\n message: `Subscription ${path} did not return an observable or a AsyncGenerator`,\n code: 'INTERNAL_SERVER_ERROR',\n });\n }\n\n const iterable = isObservable(result)\n ? observableToAsyncIterable(result, abortController.signal)\n : result;\n\n // A failed iterator cleanup is reported to the server only: the\n // client still gets `stopped`, so a subscription that completed or\n // was stopped doesn't turn into a failed one.\n if (abortController.signal.aborted) {\n try {\n // dispose the iterator without consuming it\n await using _iterator = iteratorResource(iterable);\n } catch (cause) {\n reportError(cause);\n }\n return;\n }\n\n respond({\n id,\n jsonrpc,\n result: {\n type: 'started',\n },\n });\n\n let ended = false;\n try {\n await using iterator = iteratorResource(iterable);\n let completed = false;\n // Disposed before the iterator, so cleanup that waits for\n // cancellation is woken when iteration ends other than by `done`.\n using _abortUnlessCompleted = makeResource({}, () => {\n if (!completed) {\n abort();\n }\n });\n\n const abortPromise = new Promise<'abort'>((resolve) => {\n abortController.signal.onabort = () => resolve('abort');\n });\n // We need those declarations outside the loop for garbage collection reasons. If they\n // were declared inside, they would not be freed until the next value is present.\n let next:\n | null\n | TRPCError\n | Awaited<\n typeof abortPromise | ReturnType<(typeof iterator)['next']>\n >;\n let result: null | TRPCResultMessage<unknown>['result'];\n\n while (true) {\n next = await Unpromise.race([\n nextUnlessStopped(iterator, abortController.signal, (error) =>\n callOnError({ error, path, type, ctx, req, input }),\n ),\n abortPromise,\n ]);\n\n if (next === 'abort') {\n break;\n }\n if (next instanceof Error) {\n // Report the error only after the iterator's disposal settles.\n throw next;\n }\n if (next.done) {\n completed = true;\n break;\n }\n\n result = {\n type: 'data',\n data: next.value,\n };\n\n if (isTrackedEnvelope(next.value)) {\n const [id, data] = next.value;\n result.id = id;\n result.data = {\n id,\n data,\n };\n }\n\n respond({\n id,\n jsonrpc,\n result,\n });\n\n // free up references for garbage collection\n next = null;\n result = null;\n }\n ended = true;\n } catch (cause) {\n abort();\n if (ended) {\n reportError(cause);\n } else if (isSuppressedError(cause)) {\n // the client gets the iteration error, the server both\n respondWithError(cause.suppressed);\n reportError(cause.error);\n } else {\n respondWithError(cause);\n }\n }\n };\n\n const outcome = await settle(execute());\n if (!outcome.ok) {\n const error = getTRPCErrorFromUnknown(outcome.error);\n if (!isCancelledSetup(error, abortController.signal)) {\n try {\n respondWithError(error);\n } catch (cause) {\n // the error reply couldn't be encoded or sent\n reportInternalError({\n error: getTRPCErrorFromUnknown(cause),\n path,\n type,\n ctx,\n req,\n input,\n });\n respondOrReport(() => ({ id, jsonrpc, error: fallbackErrorShape }));\n }\n return;\n }\n }\n if (type === 'subscription') {\n respond({ id, jsonrpc, result: { type: 'stopped' } });\n }\n }\n client.on('message', (rawData, isBinary) => {\n // Handle PING/PONG as text regardless of encoder\n if (!isBinary) {\n // oxlint-disable-next-line typescript/no-base-to-string\n const msgStr = rawData.toString();\n if (msgStr === 'PONG') {\n return;\n }\n if (msgStr === 'PING') {\n if (!opts.dangerouslyDisablePong) {\n client.send('PONG');\n }\n return;\n }\n }\n\n // Convert rawData to a format our encoder accepts\n // ws gives us Buffer for both text and binary frames\n if (!Buffer.isBuffer(rawData)) {\n const error = new TRPCError({\n code: 'UNPROCESSABLE_CONTENT',\n message: 'Unexpected WebSocket message format',\n });\n respondOrReport(() => ({\n id: null,\n error: errorShape({\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n }),\n }));\n return;\n }\n const data: string | Uint8Array = isBinary\n ? rawData\n : rawData.toString('utf8');\n\n if (!ctxPromise) {\n // If the ctxPromise wasn't created immediately, we're expecting the first message to be a TRPCConnectionParamsMessage\n ctxPromise = createCtxPromise(() => {\n let msg;\n try {\n msg = encoder.decode(data) as TRPCConnectionParamsMessage;\n\n if (!isObject(msg)) {\n throw new Error('Message was not an object');\n }\n } catch (cause) {\n throw new TRPCError({\n code: 'PARSE_ERROR',\n message: `Malformed TRPCConnectionParamsMessage`,\n cause,\n });\n }\n\n const connectionParams = parseConnectionParamsFromUnknown(msg.data);\n\n return connectionParams;\n });\n return;\n }\n\n const parsedMsgs = run(() => {\n try {\n const msgJSON: unknown = encoder.decode(data);\n const msgs: unknown[] = Array.isArray(msgJSON) ? msgJSON : [msgJSON];\n\n if (\n Array.isArray(msgJSON) &&\n typeof opts.maxBatchSize === 'number' &&\n msgs.length > opts.maxBatchSize\n ) {\n const error = new TRPCError({\n code: 'BAD_REQUEST',\n message: `Batch call exceeds maximum size`,\n });\n callOnError({\n error,\n path: undefined,\n type: 'unknown',\n ctx,\n req,\n input: undefined,\n });\n const shape = errorShape({\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n });\n\n // Checked before parsing so that no input is deserialized.\n // Every request in the batch gets the error, as a batched HTTP\n // call does, so that clients do not wait for a response forever.\n let responded = false;\n for (const raw of msgs) {\n if (\n isObject(raw) &&\n raw['method'] !== 'subscription.stop' &&\n (typeof raw['id'] === 'number' || typeof raw['id'] === 'string')\n ) {\n const id = raw['id'];\n const jsonrpc = raw['jsonrpc'] === '2.0' ? '2.0' : undefined;\n respondOrReport(() => ({ id, jsonrpc, error: shape }));\n responded = true;\n }\n }\n if (!responded) {\n respondOrReport(() => ({ id: null, error: shape }));\n }\n return [];\n }\n\n return msgs.map((raw) => parseTRPCMessage(raw, transformer));\n } catch (cause) {\n const error = new TRPCError({\n code: 'PARSE_ERROR',\n cause,\n });\n\n respondOrReport(() => ({\n id: null,\n error: errorShape({\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n }),\n }));\n\n return [];\n }\n });\n\n for (const [index, msg] of parsedMsgs.entries()) {\n handleRequest(msg, index, ctxPromise).catch(reportConnectionError);\n }\n });\n\n // WebSocket errors should be handled, as otherwise unhandled exceptions will crash Node.js.\n // This line was introduced after the following error brought down production systems:\n // \"RangeError: Invalid WebSocket frame: RSV2 and RSV3 must be clear\"\n // Here is the relevant discussion: https://github.com/websockets/ws/issues/1354#issuecomment-774616962\n client.on('error', (cause) => {\n callOnError({\n ctx,\n error: getTRPCErrorFromUnknown(cause),\n input: undefined,\n path: undefined,\n type: 'unknown',\n req,\n });\n });\n\n client.once('close', () => {\n for (const sub of clientSubscriptions.values()) {\n sub.abort();\n }\n clientSubscriptions.clear();\n abortController.abort();\n });\n };\n}\n\n/**\n * Pings a client after `pingMs` of quiet, and closes the connection if no\n * message comes within `pongWaitMs`.\n */\nexport function handleKeepAlive(\n client: WsWebSocket,\n pingMs = 30_000,\n pongWaitMs = 5_000,\n) {\n let timeout: NodeJS.Timeout | undefined = undefined;\n let ping: NodeJS.Timeout | undefined = undefined;\n\n const schedulePing = () => {\n const scheduleTimeout = () => {\n timeout = setTimeout(() => {\n client.terminate();\n }, pongWaitMs);\n };\n ping = setTimeout(() => {\n client.send('PING');\n\n scheduleTimeout();\n }, pingMs);\n };\n\n const onMessage = () => {\n clearTimeout(ping);\n clearTimeout(timeout);\n\n schedulePing();\n };\n\n client.on('message', onMessage);\n\n client.on('close', () => {\n clearTimeout(ping);\n clearTimeout(timeout);\n });\n\n schedulePing();\n}\n\n/**\n * Serves a router on a `ws` WebSocket server. Returns\n * `broadcastReconnectNotification()`, which tells every client to\n * reconnect, for example before a deploy.\n * @example\n * ```ts\n * const wss = new WebSocketServer({ port: 3001 });\n * const handler = applyWSSHandler({ wss, router: appRouter, createContext });\n * process.on('SIGTERM', () => {\n * handler.broadcastReconnectNotification();\n * wss.close();\n * });\n * ```\n * @see https://trpc.io/docs/server/websockets#creating-a-websocket-server\n */\nexport function applyWSSHandler<TRouter extends AnyRouter>(\n opts: WSSHandlerOptions<TRouter>,\n) {\n const encoder = opts.experimental_encoder ?? jsonEncoder;\n const onConnection = getWSConnectionHandler(opts);\n opts.wss.on('connection', (client, req) => {\n if (opts.prefix && !req.url?.startsWith(opts.prefix)) {\n return;\n }\n\n onConnection(client, req);\n });\n\n return {\n broadcastReconnectNotification: () => {\n const response: TRPCReconnectNotification = {\n id: null,\n method: 'reconnect',\n };\n const data = encoder.encode(response);\n for (const client of opts.wss.clients) {\n if (client.readyState === WEBSOCKET_OPEN) {\n client.send(data);\n }\n }\n },\n };\n}\n\nexport type { Encoder } from './wsEncoder';\nexport { jsonEncoder } from './wsEncoder';\n"],"mappings":";;;;;;;;;;;AAsBA,MAAa,cAAuB;CAClC,SAAS,SAAS,KAAK,UAAU,IAAI;CACrC,SAAS,SAAS;EAChB,IAAI,OAAO,SAAS,UAClB,MAAM,IAAI,MACR,gGAEF;EAEF,OAAO,KAAK,MAAM,IAAI;CACxB;AACF;;;;;;;ACmBA,MAAM,iBAAiB;AAEvB,SAAS,OAAe,SAAmD;CACzE,OAAO,QAAQ,MACZ,WAA2B;EAAE,IAAI;EAAM;CAAM,KAC7C,WAAoC;EAAE,IAAI;EAAO;CAAM,EAC1D;AACF;;;;;AAMA,SAAS,kBACP,OACkD;CAClD,OACE,SAAS,KAAK,KACd,MAAM,YAAY,qBAClB,WAAW,SACX,gBAAgB;AAEpB;;;;;AAMA,MAAM,qBAAqC;CACzC,MAAM,wBAAwB;CAC9B,SAAS;CACT,MAAM;EAAE,MAAM;EAAyB,YAAY;CAAI;AACzD;;;;;AAMA,SAAS,iBAAiB,OAAkB,QAAqB;CAC/D,OACE,OAAO,WACP,MAAM,SAAS,2BACf,aAAa,MAAM,KAAK;AAE5B;;;;;;;;;;AAoFA,SAAS,kBACP,UACA,QACA,kBACgE;CAChE,OAAO,SAAS,KAAK,CAAC,CAAC,OAAO,UAAmB;EAC/C,MAAM,QAAQ,wBAAwB,KAAK;EAC3C,IAAI,CAAC,OAAO,SACV,OAAO;EAET,IAAI,CAAC,aAAa,MAAM,KAAK,GAC3B,iBAAiB,KAAK;EAExB,OAAO;CACT,CAAC;AACH;;;;;AAMA,SAAgB,uBACd,MACA;;CACA,MAAM,EAAE,eAAe,WAAW;CAClC,MAAM,EAAE,gBAAgB,OAAO,KAAK;CACpC,MAAM,WAAA,wBAAU,KAAK,0BAAA,QAAA,0BAAA,KAAA,IAAA,wBAAwB;CAE7C,QAAQ,QAAqB,QAAyB;;EAIpD,MAAM,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