@trpc/server 11.24.0 → 11.24.1-canary.2.c7a2144c5
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/README.md +56 -0
- package/dist/adapters/aws-lambda/index.cjs +1 -1
- package/dist/adapters/aws-lambda/index.d.cts +1 -1
- package/dist/adapters/aws-lambda/index.d.mts +1 -1
- package/dist/adapters/aws-lambda/index.mjs +1 -1
- package/dist/adapters/express.cjs +1 -1
- package/dist/adapters/express.d.cts +2 -2
- package/dist/adapters/express.d.mts +2 -2
- package/dist/adapters/express.mjs +1 -1
- package/dist/adapters/fastify/index.cjs +3 -3
- package/dist/adapters/fastify/index.d.cts +3 -3
- package/dist/adapters/fastify/index.d.mts +3 -3
- package/dist/adapters/fastify/index.mjs +3 -3
- package/dist/adapters/fetch/index.cjs +1 -1
- package/dist/adapters/fetch/index.d.cts +1 -1
- package/dist/adapters/fetch/index.d.mts +1 -1
- package/dist/adapters/fetch/index.mjs +1 -1
- package/dist/adapters/next-app-dir.d.cts +1 -1
- package/dist/adapters/next-app-dir.d.mts +1 -1
- package/dist/adapters/next.cjs +1 -1
- package/dist/adapters/next.d.cts +2 -2
- package/dist/adapters/next.d.mts +2 -2
- package/dist/adapters/next.mjs +1 -1
- package/dist/adapters/node-http/index.cjs +1 -1
- package/dist/adapters/node-http/index.d.cts +1 -1
- package/dist/adapters/node-http/index.d.mts +1 -1
- package/dist/adapters/node-http/index.mjs +1 -1
- package/dist/adapters/standalone.cjs +1 -1
- package/dist/adapters/standalone.d.cts +2 -2
- package/dist/adapters/standalone.d.mts +2 -2
- package/dist/adapters/standalone.mjs +1 -1
- package/dist/adapters/ws.cjs +1 -1
- package/dist/adapters/ws.d.cts +2 -2
- package/dist/adapters/ws.d.mts +2 -2
- package/dist/adapters/ws.mjs +1 -1
- package/dist/http.cjs +1 -1
- package/dist/http.d.cts +1 -1
- package/dist/http.d.mts +1 -1
- package/dist/http.mjs +1 -1
- package/dist/{index-BGYvuCEh.d.cts → index-DIc3RMYq.d.cts} +6 -3
- package/dist/{index-BGYvuCEh.d.cts.map → index-DIc3RMYq.d.cts.map} +1 -1
- package/dist/{index-BGYvuCEh.d.mts → index-DIc3RMYq.d.mts} +6 -3
- package/dist/{index-BGYvuCEh.d.mts.map → index-DIc3RMYq.d.mts.map} +1 -1
- package/dist/{index-BHT7qMyI.d.mts → index-DXOA7HZX.d.cts} +2 -2
- package/dist/{index-BHT7qMyI.d.mts.map → index-DXOA7HZX.d.cts.map} +1 -1
- package/dist/{index-CJbDjPDQ.d.cts → index-yEUjMWq0.d.mts} +2 -2
- package/dist/{index-CJbDjPDQ.d.cts.map → index-yEUjMWq0.d.mts.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{initTRPC-DZEOtiNy.cjs → initTRPC-Cra_OZpb.cjs} +1 -1
- package/dist/{initTRPC-D-7sLVWc.mjs → initTRPC-D2bGKLkU.mjs} +2 -2
- package/dist/{initTRPC-D-7sLVWc.mjs.map → initTRPC-D2bGKLkU.mjs.map} +1 -1
- package/dist/{node-http-fnRXnfX7.cjs → node-http-Bq8c5wbG.cjs} +1 -1
- package/dist/{node-http-BHs4hFcB.mjs → node-http-DX50OxnV.mjs} +2 -2
- package/dist/{node-http-BHs4hFcB.mjs.map → node-http-DX50OxnV.mjs.map} +1 -1
- package/dist/observable/index.cjs +2 -2
- package/dist/observable/index.d.cts +1 -1
- package/dist/observable/index.d.mts +1 -1
- package/dist/observable/index.mjs +2 -2
- package/dist/{observable-B8nn0anr.cjs → observable-C-kLxTDb.cjs} +62 -48
- package/dist/{observable-DMA7fHJ6.mjs → observable-C3JLK4qJ.mjs} +2 -2
- package/dist/{observable-DMA7fHJ6.mjs.map → observable-C3JLK4qJ.mjs.map} +1 -1
- package/dist/{observable-CdPmrXKY.mjs → observable-DvsUkNRH.mjs} +63 -49
- package/dist/observable-DvsUkNRH.mjs.map +1 -0
- package/dist/{observable-DJG_yLnF.cjs → observable-ljzQ36vj.cjs} +1 -1
- package/dist/{resolveResponse-BLSF4Ks0.cjs → resolveResponse-CPinar9Q.cjs} +1 -1
- package/dist/{resolveResponse-BDxeIDKz.mjs → resolveResponse-F8DsMtod.mjs} +2 -2
- package/dist/{resolveResponse-BDxeIDKz.mjs.map → resolveResponse-F8DsMtod.mjs.map} +1 -1
- package/dist/rpc.d.cts +1 -1
- package/dist/rpc.d.mts +1 -1
- package/dist/shared.d.cts +1 -1
- package/dist/shared.d.mts +1 -1
- package/dist/{unstable-core-do-not-import-BAX_ZNHT.d.cts → unstable-core-do-not-import-BcPWhI2Q.d.cts} +2 -2
- package/dist/{unstable-core-do-not-import-OfjMxw-0.d.mts.map → unstable-core-do-not-import-BcPWhI2Q.d.cts.map} +1 -1
- package/dist/{unstable-core-do-not-import-OfjMxw-0.d.mts → unstable-core-do-not-import-ia0QlnhQ.d.mts} +2 -2
- package/dist/{unstable-core-do-not-import-BAX_ZNHT.d.cts.map → unstable-core-do-not-import-ia0QlnhQ.d.mts.map} +1 -1
- package/dist/unstable-core-do-not-import.cjs +2 -2
- package/dist/unstable-core-do-not-import.d.cts +1 -1
- package/dist/unstable-core-do-not-import.d.mts +1 -1
- package/dist/unstable-core-do-not-import.mjs +2 -2
- package/dist/{ws-CA_yykwZ.d.mts → ws-BgubbdBw.d.cts} +3 -3
- package/dist/{ws-C6aokjeu.d.cts.map → ws-BgubbdBw.d.cts.map} +1 -1
- package/dist/{ws-D8h4AHV-.cjs → ws-CuH1cMuq.cjs} +3 -3
- package/dist/{ws-C6aokjeu.d.cts → ws-DHvOQ0WH.d.mts} +3 -3
- package/dist/{ws-CA_yykwZ.d.mts.map → ws-DHvOQ0WH.d.mts.map} +1 -1
- package/dist/{ws-BY66ccWn.mjs → ws-PNlb0-d5.mjs} +4 -4
- package/dist/{ws-BY66ccWn.mjs.map → ws-PNlb0-d5.mjs.map} +1 -1
- package/package.json +2 -2
- 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/observable/observable.ts +73 -60
- package/dist/observable-CdPmrXKY.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ws-BY66ccWn.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 } from '../@trpc/server/rpc';\n// @trpc/server/rpc\nimport type {\n TRPCClientOutgoingMessage,\n TRPCConnectionParamsMessage,\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 isAsyncIterable,\n isObject,\n isTrackedEnvelope,\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\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 * 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 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 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 opts.onError?.({\n error,\n path: undefined,\n type: 'unknown',\n ctx,\n req,\n input: undefined,\n });\n respond({\n id: null,\n error: getErrorShape({\n config: router._def._config,\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n ctx,\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 function handleRequest(msg: TRPCClientOutgoingMessage, batchIndex: number) {\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 opts.onError?.({\n error,\n path: undefined,\n type: 'unknown',\n ctx,\n req,\n input: undefined,\n });\n respond({\n id,\n jsonrpc,\n error: getErrorShape({\n config: router._def._config,\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n ctx,\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 run(async () => {\n // oxlint-disable-next-line typescript/no-non-null-assertion\n const res = await ctxPromise!; // asserts context has been set\n if (!res.ok) {\n throw res.error;\n }\n\n const abortController = new AbortController();\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 /* istanbul ignore next -- @preserve */\n if (client.readyState !== WEBSOCKET_OPEN) {\n // if the client got disconnected whilst initializing the subscription\n // no need to send stopped message if the client is disconnected\n\n return;\n }\n\n /* istanbul ignore next -- @preserve */\n if (clientSubscriptions.has(id)) {\n // duplicate request ids for client\n\n throw new TRPCError({\n message: `Duplicate id ${id}`,\n code: 'BAD_REQUEST',\n });\n }\n\n const iterable = isObservable(result)\n ? observableToAsyncIterable(result, abortController.signal)\n : result;\n\n run(async () => {\n await using iterator = iteratorResource(iterable);\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 iterator.next().catch(getTRPCErrorFromUnknown),\n abortPromise,\n ]);\n\n if (next === 'abort') {\n await iterator.return?.();\n break;\n }\n if (next instanceof Error) {\n const error = getTRPCErrorFromUnknown(next);\n opts.onError?.({ error, path, type, ctx, req, input });\n respond({\n id,\n jsonrpc,\n error: getErrorShape({\n config: router._def._config,\n error,\n type,\n path,\n input,\n ctx,\n }),\n });\n break;\n }\n if (next.done) {\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\n respond({\n id,\n jsonrpc,\n result: {\n type: 'stopped',\n },\n });\n clientSubscriptions.delete(id);\n }).catch((cause) => {\n clientSubscriptions.delete(id);\n const error = getTRPCErrorFromUnknown(cause);\n opts.onError?.({ error, path, type, ctx, req, input });\n respond({\n id,\n jsonrpc,\n error: getErrorShape({\n config: router._def._config,\n error,\n type,\n path,\n input,\n ctx,\n }),\n });\n abortController.abort();\n });\n clientSubscriptions.set(id, abortController);\n\n respond({\n id,\n jsonrpc,\n result: {\n type: 'started',\n },\n });\n }).catch((cause) => {\n // procedure threw an error\n const error = getTRPCErrorFromUnknown(cause);\n opts.onError?.({ error, path, type, ctx, req, input });\n respond({\n id,\n jsonrpc,\n error: getErrorShape({\n config: router._def._config,\n error,\n type,\n path,\n input,\n ctx,\n }),\n });\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 respond({\n id: null,\n error: getErrorShape({\n config: router._def._config,\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n ctx,\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 opts.onError?.({\n error,\n path: undefined,\n type: 'unknown',\n ctx,\n req,\n input: undefined,\n });\n const errorShape = getErrorShape({\n config: router._def._config,\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n ctx,\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 respond({\n id: raw['id'],\n jsonrpc: raw['jsonrpc'] === '2.0' ? '2.0' : undefined,\n error: errorShape,\n });\n responded = true;\n }\n }\n if (!responded) {\n respond({ id: null, error: errorShape });\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 respond({\n id: null,\n error: getErrorShape({\n config: router._def._config,\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n ctx,\n }),\n });\n\n return [];\n }\n });\n\n parsedMsgs.map((msg, index) => handleRequest(msg, index));\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 opts.onError?.({\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;;;;;;;ACeA,MAAM,iBAAiB;;;;;AA+EvB,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,sCAAsB,IAAI,IAAsC;EACtE,MAAM,kBAAkB,IAAI,gBAAgB;EAE5C,KAAA,kBAAI,KAAK,eAAA,QAAA,oBAAA,KAAA,IAAA,KAAA,IAAA,gBAAW,SAAS;GAC3B,MAAM,EAAE,QAAQ,eAAe,KAAK;GACpC,gBAAgB,QAAQ,QAAQ,UAAU;EAC5C;EAEA,SAAS,QAAQ,mBAAwC;GACvD,OAAO,K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E9B,OAAO,GAAG,eAAe;EACvB,aAAa,IAAI;EACjB,aAAa,OAAO;CACtB,CAAC;CAED,aAAa;AACf;;;;;;;;;;;;;;;;AAiBA,SAAgB,gBACd,MACA;;CACA,MAAM,WAAA,yBAAU,KAAK,0BAAA,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
|
+
{"version":3,"file":"ws-PNlb0-d5.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 } from '../@trpc/server/rpc';\n// @trpc/server/rpc\nimport type {\n TRPCClientOutgoingMessage,\n TRPCConnectionParamsMessage,\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 isAsyncIterable,\n isObject,\n isTrackedEnvelope,\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\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 * 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 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 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 opts.onError?.({\n error,\n path: undefined,\n type: 'unknown',\n ctx,\n req,\n input: undefined,\n });\n respond({\n id: null,\n error: getErrorShape({\n config: router._def._config,\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n ctx,\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 function handleRequest(msg: TRPCClientOutgoingMessage, batchIndex: number) {\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 opts.onError?.({\n error,\n path: undefined,\n type: 'unknown',\n ctx,\n req,\n input: undefined,\n });\n respond({\n id,\n jsonrpc,\n error: getErrorShape({\n config: router._def._config,\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n ctx,\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 run(async () => {\n // oxlint-disable-next-line typescript/no-non-null-assertion\n const res = await ctxPromise!; // asserts context has been set\n if (!res.ok) {\n throw res.error;\n }\n\n const abortController = new AbortController();\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 /* istanbul ignore next -- @preserve */\n if (client.readyState !== WEBSOCKET_OPEN) {\n // if the client got disconnected whilst initializing the subscription\n // no need to send stopped message if the client is disconnected\n\n return;\n }\n\n /* istanbul ignore next -- @preserve */\n if (clientSubscriptions.has(id)) {\n // duplicate request ids for client\n\n throw new TRPCError({\n message: `Duplicate id ${id}`,\n code: 'BAD_REQUEST',\n });\n }\n\n const iterable = isObservable(result)\n ? observableToAsyncIterable(result, abortController.signal)\n : result;\n\n run(async () => {\n await using iterator = iteratorResource(iterable);\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 iterator.next().catch(getTRPCErrorFromUnknown),\n abortPromise,\n ]);\n\n if (next === 'abort') {\n await iterator.return?.();\n break;\n }\n if (next instanceof Error) {\n const error = getTRPCErrorFromUnknown(next);\n opts.onError?.({ error, path, type, ctx, req, input });\n respond({\n id,\n jsonrpc,\n error: getErrorShape({\n config: router._def._config,\n error,\n type,\n path,\n input,\n ctx,\n }),\n });\n break;\n }\n if (next.done) {\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\n respond({\n id,\n jsonrpc,\n result: {\n type: 'stopped',\n },\n });\n clientSubscriptions.delete(id);\n }).catch((cause) => {\n clientSubscriptions.delete(id);\n const error = getTRPCErrorFromUnknown(cause);\n opts.onError?.({ error, path, type, ctx, req, input });\n respond({\n id,\n jsonrpc,\n error: getErrorShape({\n config: router._def._config,\n error,\n type,\n path,\n input,\n ctx,\n }),\n });\n abortController.abort();\n });\n clientSubscriptions.set(id, abortController);\n\n respond({\n id,\n jsonrpc,\n result: {\n type: 'started',\n },\n });\n }).catch((cause) => {\n // procedure threw an error\n const error = getTRPCErrorFromUnknown(cause);\n opts.onError?.({ error, path, type, ctx, req, input });\n respond({\n id,\n jsonrpc,\n error: getErrorShape({\n config: router._def._config,\n error,\n type,\n path,\n input,\n ctx,\n }),\n });\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 respond({\n id: null,\n error: getErrorShape({\n config: router._def._config,\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n ctx,\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 opts.onError?.({\n error,\n path: undefined,\n type: 'unknown',\n ctx,\n req,\n input: undefined,\n });\n const errorShape = getErrorShape({\n config: router._def._config,\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n ctx,\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 respond({\n id: raw['id'],\n jsonrpc: raw['jsonrpc'] === '2.0' ? '2.0' : undefined,\n error: errorShape,\n });\n responded = true;\n }\n }\n if (!responded) {\n respond({ id: null, error: errorShape });\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 respond({\n id: null,\n error: getErrorShape({\n config: router._def._config,\n error,\n type: 'unknown',\n path: undefined,\n input: undefined,\n ctx,\n }),\n });\n\n return [];\n }\n });\n\n parsedMsgs.map((msg, index) => handleRequest(msg, index));\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 opts.onError?.({\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;;;;;;;ACeA,MAAM,iBAAiB;;;;;AA+EvB,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,sCAAsB,IAAI,IAAsC;EACtE,MAAM,kBAAkB,IAAI,gBAAgB;EAE5C,KAAA,kBAAI,KAAK,eAAA,QAAA,oBAAA,KAAA,IAAA,KAAA,IAAA,gBAAW,SAAS;GAC3B,MAAM,EAAE,QAAQ,eAAe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kB;EACtB,aAAa,IAAI;EACjB,aAAa,OAAO;EAEpB,aAAa;CACf;CAEA,OAAO,GAAG,WAAW,SAAS;CAE9B,OAAO,GAAG,eAAe;EACvB,aAAa,IAAI;EACjB,aAAa,OAAO;CACtB,CAAC;CAED,aAAa;AACf;;;;;;;;;;;;;;;;AAiBA,SAAgB,gBACd,MACA;;CACA,MAAM,WAAA,yBAAU,KAAK,0BAAA,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"}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@trpc/server",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "11.24.
|
|
5
|
+
"version": "11.24.1-canary.2.c7a2144c5",
|
|
6
6
|
"description": "The tRPC server library",
|
|
7
7
|
"author": "KATT",
|
|
8
8
|
"license": "MIT",
|
|
@@ -257,5 +257,5 @@
|
|
|
257
257
|
"keywords": [
|
|
258
258
|
"tanstack-intent"
|
|
259
259
|
],
|
|
260
|
-
"gitHead": "
|
|
260
|
+
"gitHead": "c7a2144c5703c7ee50b3a437a9e43003615f88e5"
|
|
261
261
|
}
|
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.24.
|
|
13
|
+
library_version: 11.24.1-canary.2.c7a2144c5
|
|
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. -->
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { Result } from '../unstable-core-do-not-import';
|
|
2
1
|
import type {
|
|
3
2
|
Observable,
|
|
4
3
|
Observer,
|
|
@@ -145,83 +144,97 @@ export function observableToPromise<TValue>(
|
|
|
145
144
|
}
|
|
146
145
|
|
|
147
146
|
/**
|
|
147
|
+
* Turns an observable into an async iterable, like Node's `events.on()`.
|
|
148
|
+
* Values wait in a queue until `next()` reads them. An error rejects the
|
|
149
|
+
* `next()` after the queued values, once. Completion, `return()` and aborting
|
|
150
|
+
* `signal` unsubscribe and end every pending `next()` with `{ done: true }`;
|
|
151
|
+
* anything the observable sends after that is ignored.
|
|
148
152
|
* @internal
|
|
149
153
|
*/
|
|
150
|
-
function
|
|
154
|
+
export function observableToAsyncIterable<TValue>(
|
|
151
155
|
observable: Observable<TValue, unknown>,
|
|
152
156
|
signal: AbortSignal,
|
|
153
|
-
):
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
157
|
+
): AsyncIterable<TValue> {
|
|
158
|
+
const values: TValue[] = [];
|
|
159
|
+
const pending: {
|
|
160
|
+
resolve: (result: IteratorResult<TValue>) => void;
|
|
161
|
+
reject: (cause: unknown) => void;
|
|
162
|
+
}[] = [];
|
|
163
|
+
let error: { cause: unknown } | null = null;
|
|
164
|
+
let finished = false;
|
|
165
|
+
let subscription: Unsubscribable | null = null;
|
|
161
166
|
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
167
|
+
function finish() {
|
|
168
|
+
if (finished) {
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
finished = true;
|
|
172
|
+
signal.removeEventListener('abort', finish);
|
|
173
|
+
try {
|
|
174
|
+
subscription?.unsubscribe();
|
|
175
|
+
} finally {
|
|
176
|
+
for (const promise of pending.splice(0)) {
|
|
177
|
+
promise.resolve({ value: undefined, done: true });
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
176
181
|
|
|
177
|
-
|
|
178
|
-
|
|
182
|
+
subscription = observable.subscribe({
|
|
183
|
+
next(value) {
|
|
184
|
+
if (finished) {
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
const promise = pending.shift();
|
|
188
|
+
if (promise) {
|
|
189
|
+
promise.resolve({ value, done: false });
|
|
179
190
|
} else {
|
|
180
|
-
|
|
191
|
+
values.push(value);
|
|
181
192
|
}
|
|
182
193
|
},
|
|
183
|
-
|
|
184
|
-
|
|
194
|
+
error(cause) {
|
|
195
|
+
if (finished) {
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
const promise = pending.shift();
|
|
199
|
+
if (promise) {
|
|
200
|
+
promise.reject(cause);
|
|
201
|
+
} else {
|
|
202
|
+
error = { cause };
|
|
203
|
+
}
|
|
204
|
+
finish();
|
|
185
205
|
},
|
|
206
|
+
complete: finish,
|
|
186
207
|
});
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
export function observableToAsyncIterable<TValue>(
|
|
195
|
-
observable: Observable<TValue, unknown>,
|
|
196
|
-
signal: AbortSignal,
|
|
197
|
-
): AsyncIterable<TValue> {
|
|
198
|
-
const stream = observableToReadableStream(observable, signal);
|
|
208
|
+
if (finished) {
|
|
209
|
+
subscription.unsubscribe();
|
|
210
|
+
} else if (signal.aborted) {
|
|
211
|
+
finish();
|
|
212
|
+
} else {
|
|
213
|
+
signal.addEventListener('abort', finish, { once: true });
|
|
214
|
+
}
|
|
199
215
|
|
|
200
|
-
const reader = stream.getReader();
|
|
201
216
|
const iterator: AsyncIterator<TValue> = {
|
|
202
217
|
async next() {
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
return {
|
|
206
|
-
value: undefined,
|
|
207
|
-
done: true,
|
|
208
|
-
};
|
|
218
|
+
if (values.length > 0) {
|
|
219
|
+
return { value: values.shift() as TValue, done: false };
|
|
209
220
|
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
221
|
+
if (error) {
|
|
222
|
+
const { cause } = error;
|
|
223
|
+
error = null;
|
|
224
|
+
throw cause;
|
|
213
225
|
}
|
|
214
|
-
|
|
215
|
-
value:
|
|
216
|
-
|
|
217
|
-
|
|
226
|
+
if (finished) {
|
|
227
|
+
return { value: undefined, done: true };
|
|
228
|
+
}
|
|
229
|
+
return new Promise((resolve, reject) => {
|
|
230
|
+
pending.push({ resolve, reject });
|
|
231
|
+
});
|
|
218
232
|
},
|
|
219
233
|
async return() {
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
};
|
|
234
|
+
values.length = 0;
|
|
235
|
+
error = null;
|
|
236
|
+
finish();
|
|
237
|
+
return { value: undefined, done: true };
|
|
225
238
|
},
|
|
226
239
|
};
|
|
227
240
|
return {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"observable-CdPmrXKY.mjs","names":[],"sources":["../src/observable/observable.ts"],"sourcesContent":["import type { Result } from '../unstable-core-do-not-import';\nimport type {\n Observable,\n Observer,\n OperatorFunction,\n TeardownLogic,\n UnaryFunction,\n Unsubscribable,\n} from './types';\n\n/**\n * The type of the values an observable emits.\n * @public\n */\nexport type inferObservableValue<TObservable> =\n TObservable extends Observable<infer TValue, unknown> ? TValue : never;\n\n/**\n * Whether a value is an observable: an object with `subscribe`.\n * @public\n */\nexport function isObservable(x: unknown): x is Observable<unknown, unknown> {\n return typeof x === 'object' && x !== null && 'subscribe' in x;\n}\n\n/**\n * Creates an observable. `subscribe` runs for each subscriber, and can\n * return a function that cleans up when it unsubscribes.\n * @example\n * ```ts\n * const ticks = observable<number>((observer) => {\n * const timer = setInterval(() => observer.next(Date.now()), 1000);\n * return () => clearInterval(timer);\n * });\n * ```\n * @see https://trpc.io/docs/client/links#creating-a-custom-link\n * @public\n */\nexport function observable<TValue, TError = unknown>(\n subscribe: (observer: Observer<TValue, TError>) => TeardownLogic,\n): Observable<TValue, TError> {\n const self: Observable<TValue, TError> = {\n subscribe(observer) {\n let teardownRef: TeardownLogic | null = null;\n let isDone = false;\n let unsubscribed = false;\n let teardownImmediately = false;\n function unsubscribe() {\n if (teardownRef === null) {\n teardownImmediately = true;\n return;\n }\n if (unsubscribed) {\n return;\n }\n unsubscribed = true;\n\n if (typeof teardownRef === 'function') {\n teardownRef();\n } else if (teardownRef) {\n teardownRef.unsubscribe();\n }\n }\n teardownRef = subscribe({\n next(value) {\n if (isDone) {\n return;\n }\n observer.next?.(value);\n },\n error(err) {\n if (isDone) {\n return;\n }\n isDone = true;\n observer.error?.(err);\n unsubscribe();\n },\n complete() {\n if (isDone) {\n return;\n }\n isDone = true;\n observer.complete?.();\n unsubscribe();\n },\n });\n if (teardownImmediately) {\n unsubscribe();\n }\n return {\n unsubscribe,\n };\n },\n pipe(\n ...operations: OperatorFunction<any, any, any, any>[]\n ): Observable<any, any> {\n return operations.reduce(pipeReducer, self);\n },\n };\n return self;\n}\n\nfunction pipeReducer(prev: any, fn: UnaryFunction<any, any>) {\n return fn(prev);\n}\n\n/**\n * Resolves with an observable's first value. Rejects if it errors or\n * completes first. It doesn't unsubscribe after the first value.\n * @internal\n */\nexport function observableToPromise<TValue>(\n observable: Observable<TValue, unknown>,\n) {\n const ac = new AbortController();\n const promise = new Promise<TValue>((resolve, reject) => {\n let isDone = false;\n function onDone() {\n if (isDone) {\n return;\n }\n isDone = true;\n obs$.unsubscribe();\n }\n ac.signal.addEventListener('abort', () => {\n reject(ac.signal.reason);\n });\n const obs$ = observable.subscribe({\n next(data) {\n isDone = true;\n resolve(data);\n onDone();\n },\n error(data) {\n reject(data);\n },\n complete() {\n ac.abort();\n onDone();\n },\n });\n });\n return promise;\n}\n\n/**\n * @internal\n */\nfunction observableToReadableStream<TValue>(\n observable: Observable<TValue, unknown>,\n signal: AbortSignal,\n): ReadableStream<Result<TValue>> {\n let unsub: Unsubscribable | null = null;\n\n const onAbort = () => {\n unsub?.unsubscribe();\n unsub = null;\n signal.removeEventListener('abort', onAbort);\n };\n\n return new ReadableStream<Result<TValue>>({\n start(controller) {\n unsub = observable.subscribe({\n next(data) {\n controller.enqueue({ ok: true, value: data });\n },\n error(error) {\n controller.enqueue({ ok: false, error });\n controller.close();\n },\n complete() {\n controller.close();\n },\n });\n\n if (signal.aborted) {\n onAbort();\n } else {\n signal.addEventListener('abort', onAbort, { once: true });\n }\n },\n cancel() {\n onAbort();\n },\n });\n}\n\n/**\n * Turns an observable into an async iterable. Aborting `signal`\n * unsubscribes from the observable but doesn't end a pending `next()`.\n * @internal\n */\nexport function observableToAsyncIterable<TValue>(\n observable: Observable<TValue, unknown>,\n signal: AbortSignal,\n): AsyncIterable<TValue> {\n const stream = observableToReadableStream(observable, signal);\n\n const reader = stream.getReader();\n const iterator: AsyncIterator<TValue> = {\n async next() {\n const value = await reader.read();\n if (value.done) {\n return {\n value: undefined,\n done: true,\n };\n }\n const { value: result } = value;\n if (!result.ok) {\n throw result.error;\n }\n return {\n value: result.value,\n done: false,\n };\n },\n async return() {\n await reader.cancel();\n return {\n value: undefined,\n done: true,\n };\n },\n };\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n };\n}\n"],"mappings":";;;;;AAqBA,SAAgB,aAAa,GAA+C;CAC1E,OAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,eAAe;AAC/D;;;;;;;;;;;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