@hyper-fetch/orpc 9.8.1 → 10.0.0
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 +35 -1
- package/__tests__/e2e/e2e.orpc-realtime-server.ts +181 -0
- package/__tests__/e2e/e2e.react-realtime.spec.tsx +181 -0
- package/__tests__/e2e/e2e.realtime.spec.ts +310 -0
- package/__tests__/features/socket/socket.schema.spec.ts +179 -0
- package/__tests__/features/stream-adapter/stream-adapter.environment.spec.ts +163 -0
- package/__tests__/features/stream-adapter/stream-adapter.lifecycle.spec.ts +509 -0
- package/__tests__/features/stream-adapter/stream-adapter.listener-lifecycle.spec.ts +291 -0
- package/__tests__/features/stream-adapter/stream-adapter.protocol.spec.ts +609 -0
- package/__tests__/features/stream-adapter/stream-adapter.subscriptions.spec.ts +270 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.environment.spec.ts +147 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.handshake-error.spec.ts +77 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.lifecycle.spec.ts +326 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.listener-lifecycle.spec.ts +222 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.protocol.spec.ts +415 -0
- package/__tests__/features/websocket-adapter/websocket-adapter.subscriptions.spec.ts +172 -0
- package/__tests__/utils/controlled-fetch.ts +160 -0
- package/__tests__/utils/controlled-websocket.ts +140 -0
- package/__tests__/utils/socket-error.ts +7 -0
- package/__tests__/utils/stream-socket.ts +54 -0
- package/__tests__/utils/websocket-socket.ts +45 -0
- package/__tests__/vitest.setup.ts +20 -0
- package/dist/adapter/adapter.schema.d.ts +32 -0
- package/dist/adapter/adapter.schema.d.ts.map +1 -1
- package/dist/adapter/adapter.utils.d.ts +22 -4
- package/dist/adapter/adapter.utils.d.ts.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +932 -11
- package/dist/index.mjs.map +1 -1
- package/dist/socket/index.d.ts +3 -0
- package/dist/socket/index.d.ts.map +1 -0
- package/dist/socket/socket.subscriptions.d.ts +31 -0
- package/dist/socket/socket.subscriptions.d.ts.map +1 -0
- package/dist/socket/socket.types.d.ts +62 -0
- package/dist/socket/socket.types.d.ts.map +1 -0
- package/dist/socket/socket.utils.d.ts +56 -0
- package/dist/socket/socket.utils.d.ts.map +1 -0
- package/dist/stream-adapter/index.d.ts +3 -0
- package/dist/stream-adapter/index.d.ts.map +1 -0
- package/dist/stream-adapter/stream-adapter.d.ts +21 -0
- package/dist/stream-adapter/stream-adapter.d.ts.map +1 -0
- package/dist/stream-adapter/stream-adapter.types.d.ts +22 -0
- package/dist/stream-adapter/stream-adapter.types.d.ts.map +1 -0
- package/dist/stream-adapter/stream-adapter.utils.d.ts +22 -0
- package/dist/stream-adapter/stream-adapter.utils.d.ts.map +1 -0
- package/dist/websocket-adapter/index.d.ts +3 -0
- package/dist/websocket-adapter/index.d.ts.map +1 -0
- package/dist/websocket-adapter/websocket-adapter.d.ts +21 -0
- package/dist/websocket-adapter/websocket-adapter.d.ts.map +1 -0
- package/dist/websocket-adapter/websocket-adapter.types.d.ts +22 -0
- package/dist/websocket-adapter/websocket-adapter.types.d.ts.map +1 -0
- package/dist/websocket-adapter/websocket-adapter.utils.d.ts +35 -0
- package/dist/websocket-adapter/websocket-adapter.utils.d.ts.map +1 -0
- package/package.json +3 -1
- package/src/adapter/adapter.schema.ts +57 -0
- package/src/adapter/adapter.utils.ts +40 -10
- package/src/index.ts +3 -0
- package/src/socket/index.ts +2 -0
- package/src/socket/socket.subscriptions.ts +178 -0
- package/src/socket/socket.types.ts +64 -0
- package/src/socket/socket.utils.ts +110 -0
- package/src/stream-adapter/index.ts +2 -0
- package/src/stream-adapter/stream-adapter.ts +381 -0
- package/src/stream-adapter/stream-adapter.types.ts +31 -0
- package/src/stream-adapter/stream-adapter.utils.ts +98 -0
- package/src/websocket-adapter/index.ts +2 -0
- package/src/websocket-adapter/websocket-adapter.ts +417 -0
- package/src/websocket-adapter/websocket-adapter.types.ts +31 -0
- package/src/websocket-adapter/websocket-adapter.utils.ts +119 -0
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/adapter/adapter.constants.ts","../src/adapter/adapter.utils.ts","../src/adapter/adapter.fetch.ts","../src/adapter/adapter.ts"],"sourcesContent":["import { Time } from \"@hyper-fetch/core\";\n\nimport type { OrpcExtraType } from \"./adapter.types\";\n\nexport const defaultTimeout = Time.SEC * 5;\n\nexport const orpcExtra: OrpcExtraType = {\n headers: {},\n};\n\nexport const OrpcMethods = {\n QUERY: \"QUERY\",\n MUTATION: \"MUTATION\",\n} as const;\n\n/** Query string key owned by the oRPC RPC protocol - it wins over the user query params */\nexport const reservedQueryParams = [\"data\"];\n\n/** Longer GET urls are sent with POST, the same limit as the `RPCLink` of oRPC */\nexport const maxGetUrlLength = 2083;\n","import type { EmptyTypes, QueryParamsType, RequestInstance } from \"@hyper-fetch/core\";\nimport { getErrorMessage, parseResponse, stringifyKey, stringifyQueryParams } from \"@hyper-fetch/core\";\nimport type { StandardRPCCustomJsonSerializer } from \"@orpc/client/standard\";\nimport { StandardRPCJsonSerializer, StandardRPCSerializer } from \"@orpc/client/standard\";\n\nimport { maxGetUrlLength, OrpcMethods, reservedQueryParams } from \"./adapter.constants\";\nimport type { OrpcErrorType, OrpcQueryMethod } from \"./adapter.types\";\n\n/** Serializer of the oRPC RPC protocol, it handles types like `Date`, `BigInt`, `Map`, `Set` and files */\nexport const createOrpcSerializer = (customJsonSerializers?: StandardRPCCustomJsonSerializer[]) => {\n return new StandardRPCSerializer(new StandardRPCJsonSerializer({ customJsonSerializers }));\n};\n\nexport type OrpcSerializerType = ReturnType<typeof createOrpcSerializer>;\n\n/** Turns the procedure path `user/byId` or `/user/byId` into the url path `/user/byId` */\nexport const orpcEndpointMapper = (endpoint: string): string => {\n const segments = endpoint.split(\"/\").filter(Boolean);\n\n return `/${segments.map(encodeURIComponent).join(\"/\")}`;\n};\n\n/**\n * Keys are built from the wire format, so values like `Date` or `Map` stay distinct.\n * Mappers run while the request is created, so an input that can't be serialized can't throw here.\n * It is reported when the request is sent.\n */\nconst getOrpcInputKey = (input: unknown, serializer: OrpcSerializerType): string => {\n try {\n const serialized = serializer.serialize(input);\n\n if (!(serialized instanceof FormData)) {\n return JSON.stringify(serialized);\n }\n\n // Files are compared by their metadata, reading their content would be too expensive\n const parts: string[] = [];\n serialized.forEach((value, key) => {\n parts.push(typeof value === \"string\" ? value : `${key}:${value.name}:${value.type}:${value.size}`);\n });\n return parts.join(\"|\");\n } catch {\n return \"\";\n }\n};\n\n/** Key of the request response - the same procedure called with a different input is a different resource */\nexport const getOrpcRequestKey = (request: RequestInstance, serializer: OrpcSerializerType): string => {\n const procedure = orpcEndpointMapper(request.endpoint);\n const input = getOrpcInputKey(request.payload, serializer);\n\n return `${request.method}_${procedure}-${input}-${stringifyKey(request.queryParams)}`;\n};\n\n/** The input is not a part of this key, so `request.abort()` stops every running call of the procedure */\nexport const getOrpcAbortKey = (request: RequestInstance): string => {\n return `${request.method}_${orpcEndpointMapper(request.endpoint)}-${request.cancelable}`;\n};\n\n/** Only the user headers, the content type depends on the encoded body and is set while sending */\nexport const getOrpcHeaders = (request: RequestInstance): HeadersInit => {\n return { ...(request.headers as Record<string, string> | undefined) };\n};\n\ntype OrpcHttpRequestType = {\n url: string;\n method: \"GET\" | \"POST\";\n headers: Record<string, string>;\n body?: string | FormData;\n};\n\n/**\n * Encodes the call as described by the oRPC RPC protocol.\n * GET sends the input in the `data` query param. Files and urls over the length limit fall back to POST,\n * the same as the `RPCLink` of oRPC.\n */\nexport const getOrpcHttpRequest = ({\n request,\n endpoint,\n queryParams,\n headers,\n payload,\n queryMethod,\n serializer,\n}: {\n request: RequestInstance;\n endpoint: string;\n queryParams: unknown;\n headers: HeadersInit;\n payload: unknown;\n queryMethod: OrpcQueryMethod;\n serializer: OrpcSerializerType;\n}): OrpcHttpRequestType => {\n const [baseUrl, baseQuery] = request.client.url.split(\"?\");\n const searchParams = new URLSearchParams(baseQuery);\n\n // Mappers can return anything, so we normalize their result to the query string\n new URLSearchParams(stringifyQueryParams(queryParams as QueryParamsType | string | EmptyTypes)).forEach(\n (value, key) => {\n if (!reservedQueryParams.includes(key)) {\n searchParams.append(key, value);\n }\n },\n );\n\n const url = `${baseUrl.replace(/\\/+$/, \"\")}${endpoint}`;\n const serialized = serializer.serialize(payload);\n const userHeaders = { ...(headers as Record<string, string>) };\n\n if (request.method === OrpcMethods.QUERY && queryMethod === \"GET\" && !(serialized instanceof FormData)) {\n const getParams = new URLSearchParams(searchParams);\n getParams.append(\"data\", JSON.stringify(serialized));\n const getUrl = `${url}?${getParams.toString()}`;\n\n if (getUrl.length <= maxGetUrlLength) {\n return { url: getUrl, method: \"GET\", headers: userHeaders };\n }\n }\n\n const queryString = searchParams.toString();\n const postUrl = queryString ? `${url}?${queryString}` : url;\n\n if (serialized instanceof FormData) {\n // The browser sets the multipart content type together with its boundary\n return { url: postUrl, method: \"POST\", headers: userHeaders, body: serialized };\n }\n\n return {\n url: postUrl,\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", ...userHeaders },\n body: JSON.stringify(serialized),\n };\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => {\n return typeof value === \"object\" && value !== null;\n};\n\n/** The same check as `isORPCErrorJson` of oRPC */\nconst isOrpcError = (value: unknown): value is OrpcErrorType => {\n return (\n isRecord(value) &&\n typeof value.defined === \"boolean\" &&\n typeof value.code === \"string\" &&\n typeof value.status === \"number\" &&\n typeof value.message === \"string\"\n );\n};\n\ntype OrpcResultType = { isSuccess: true; data: unknown } | { isSuccess: false; error: unknown };\n\n/**\n * Reads the serialized `{ json, meta }` body, or the multipart body when the output contains files.\n * Statuses from 400 up are errors, the same as in oRPC.\n */\nexport const getOrpcResult = ({\n body,\n status,\n serializer,\n}: {\n body: string | FormData;\n status: number;\n serializer: OrpcSerializerType;\n}): OrpcResultType => {\n // An empty body is an undefined output\n let parsed: unknown = body || undefined;\n if (typeof parsed === \"string\") {\n parsed = parseResponse(parsed);\n }\n const isSerialized = parsed === undefined || parsed instanceof FormData || isRecord(parsed);\n\n if (!isSerialized) {\n return { isSuccess: false, error: getErrorMessage() };\n }\n\n const value = serializer.deserialize(parsed);\n if (status < 400) {\n return { isSuccess: true, data: value ?? null };\n }\n\n if (!isOrpcError(value)) {\n return { isSuccess: false, error: getErrorMessage() };\n }\n\n // The same fields as `ORPCError.toJSON()`, the data key is there even when the error has no data\n const { defined, code, status: errorStatus, message, data } = value;\n return { isSuccess: false, error: { defined, code, status: errorStatus, message, data } };\n};\n","import type { DefaultMapperType, QueryParamsType } from \"@hyper-fetch/core\";\nimport { Adapter, defaultMapper, stringifyQueryParams } from \"@hyper-fetch/core\";\n\nimport { defaultTimeout, OrpcMethods, orpcExtra } from \"./adapter.constants\";\nimport type {\n FetchOrpcAdapterOptionsType,\n OrpcAdapterOptionsType,\n OrpcAdapterType,\n OrpcExtraType,\n OrpcMethod,\n} from \"./adapter.types\";\nimport {\n createOrpcSerializer,\n getOrpcAbortKey,\n getOrpcHeaders,\n getOrpcHttpRequest,\n getOrpcRequestKey,\n getOrpcResult,\n orpcEndpointMapper,\n} from \"./adapter.utils\";\n\nconst readBody = async (response: Response, onProgress: (progress: ProgressEvent) => void) => {\n // Outputs with files are sent as multipart form data\n if (response.headers.get(\"content-type\")?.startsWith(\"multipart/form-data\")) {\n return response.formData();\n }\n\n if (!response.body || typeof response.body.getReader !== \"function\") {\n return response.text();\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n const contentLength = parseInt(response.headers.get(\"content-length\") || \"0\", 10);\n let loaded = 0;\n let body = \"\";\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n // eslint-disable-next-line no-await-in-loop\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n loaded += value.length;\n body += decoder.decode(value, { stream: true });\n onProgress({ total: contentLength || loaded, loaded } as ProgressEvent);\n }\n\n return body + decoder.decode();\n};\n\nconst getBodySize = (body: string | FormData | undefined) => {\n if (body === undefined) {\n return 0;\n }\n if (typeof body === \"string\") {\n return new Blob([body]).size;\n }\n\n let size = 0;\n body.forEach((value) => {\n size += typeof value === \"string\" ? new Blob([value]).size : value.size;\n });\n return size;\n};\n\nexport const getOrpcAdapter = ({\n queryMethod: defaultQueryMethod = \"POST\",\n customJsonSerializers,\n}: OrpcAdapterOptionsType = {}): OrpcAdapterType => {\n const serializer = createOrpcSerializer(customJsonSerializers);\n\n return (\n new Adapter<\n FetchOrpcAdapterOptionsType,\n OrpcMethod,\n number,\n OrpcExtraType,\n QueryParamsType | string,\n QueryParamsType | string | undefined,\n string,\n DefaultMapperType,\n DefaultMapperType,\n DefaultMapperType,\n DefaultMapperType\n >({\n name: \"orpc\",\n defaultMethod: OrpcMethods.QUERY,\n defaultExtra: orpcExtra,\n systemErrorStatus: 0,\n systemErrorExtra: orpcExtra,\n })\n .onInitialize(({ client }) => {\n client.setCacheKeyMapper((request) => getOrpcRequestKey(request, serializer));\n client.setQueryKeyMapper((request) => getOrpcRequestKey(request, serializer));\n client.setAbortKeyMapper((request) => getOrpcAbortKey(request));\n })\n // Queries are safe reads, the same as GET in the HttpAdapter\n .setRequestDefaults((options) => {\n const method = options.method ?? OrpcMethods.QUERY;\n return method === OrpcMethods.QUERY ? { deduplicate: true } : {};\n })\n .setDevtoolsEndpointGetter(orpcEndpointMapper)\n .setEndpointMapper(orpcEndpointMapper)\n .setQueryParamsMapper(stringifyQueryParams)\n .setHeaderMapper(getOrpcHeaders)\n // The input is encoded by the fetcher, because the method decides where it is sent\n .setPayloadMapper(defaultMapper)\n .setFetcher(\n async ({\n request,\n endpoint,\n queryParams,\n payload,\n adapterOptions,\n headers,\n onError,\n onResponseEnd,\n onTimeoutError,\n onRequestEnd,\n createAbortListener,\n getAbortController,\n onResponseProgress,\n onResponseStart,\n onBeforeRequest,\n onRequestStart,\n onRequestProgress,\n onSuccess,\n }) => {\n const {\n timeout: timeoutMs = defaultTimeout,\n queryMethod = defaultQueryMethod,\n ...restOptions\n } = adapterOptions ?? {};\n\n let timedOut = false;\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let status = 0;\n let extra = orpcExtra;\n\n const unmountListener = createAbortListener({\n status: 0,\n extra: orpcExtra,\n });\n\n // The listener above throws when the controller is missing\n const controller = getAbortController() as AbortController;\n\n if (timeoutMs > 0) {\n timeoutId = setTimeout(() => {\n timedOut = true;\n unmountListener();\n controller.abort();\n }, timeoutMs);\n }\n\n onBeforeRequest();\n onRequestStart();\n\n try {\n const httpRequest = getOrpcHttpRequest({\n request,\n endpoint,\n queryParams,\n headers,\n payload,\n queryMethod,\n serializer,\n });\n\n const total = getBodySize(httpRequest.body);\n if (total) {\n onRequestProgress({ total, loaded: total } as ProgressEvent);\n }\n\n onRequestEnd();\n\n const response = await fetch(httpRequest.url, {\n ...restOptions,\n method: httpRequest.method,\n headers: httpRequest.headers,\n body: httpRequest.body,\n signal: controller.signal,\n });\n\n onResponseStart();\n\n const responseHeaders: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n\n status = response.status;\n extra = { headers: responseHeaders };\n\n const body = await readBody(response, onResponseProgress);\n\n clearTimeout(timeoutId);\n\n onResponseEnd();\n unmountListener();\n\n const result = getOrpcResult({ body, status, serializer });\n\n if (result.isSuccess) {\n onSuccess({ data: result.data, status, extra });\n } else {\n onError({ error: result.error, status, extra });\n }\n } catch (error) {\n clearTimeout(timeoutId);\n unmountListener();\n\n if (controller.signal.aborted) {\n if (timedOut) {\n onTimeoutError({ status: 0, extra: orpcExtra });\n }\n return;\n }\n\n onError({ error, status, extra });\n }\n },\n )\n );\n};\n","import { getOrpcAdapter } from \"./adapter.fetch\";\nimport type { OrpcAdapterOptionsType, OrpcAdapterType } from \"./adapter.types\";\n\n/**\n * Adapter calling oRPC procedures with the RPC protocol.\n * The endpoint is the procedure path and the payload is the procedure input.\n *\n * @example\n * const client = createClient({ url: \"http://localhost:3000/rpc\" }).setAdapter(OrpcAdapter());\n */\nexport const OrpcAdapter = (options?: OrpcAdapterOptionsType): OrpcAdapterType => {\n return getOrpcAdapter(options);\n};\n"],"mappings":";;;AAIA,IAAa,iBAAiB,KAAK,MAAM;AAEzC,IAAa,YAA2B,EACtC,SAAS,EAAE,EACZ;AAED,IAAa,cAAc;CACzB,OAAO;CACP,UAAU;CACX;;AAGD,IAAa,sBAAsB,CAAC,OAAO;;AAG3C,IAAa,kBAAkB;;;;ACV/B,IAAa,wBAAwB,0BAA8D;AACjG,QAAO,IAAI,sBAAsB,IAAI,0BAA0B,EAAE,uBAAuB,CAAC,CAAC;;;AAM5F,IAAa,sBAAsB,aAA6B;AAG9D,QAAO,IAFU,SAAS,MAAM,IAAI,CAAC,OAAO,QAAQ,CAEhC,IAAI,mBAAmB,CAAC,KAAK,IAAI;;;;;;;AAQvD,IAAM,mBAAmB,OAAgB,eAA2C;AAClF,KAAI;EACF,MAAM,aAAa,WAAW,UAAU,MAAM;AAE9C,MAAI,EAAE,sBAAsB,UAC1B,QAAO,KAAK,UAAU,WAAW;EAInC,MAAM,QAAkB,EAAE;AAC1B,aAAW,SAAS,OAAO,QAAQ;AACjC,SAAM,KAAK,OAAO,UAAU,WAAW,QAAQ,GAAG,IAAI,GAAG,MAAM,KAAK,GAAG,MAAM,KAAK,GAAG,MAAM,OAAO;IAClG;AACF,SAAO,MAAM,KAAK,IAAI;SAChB;AACN,SAAO;;;;AAKX,IAAa,qBAAqB,SAA0B,eAA2C;CACrG,MAAM,YAAY,mBAAmB,QAAQ,SAAS;CACtD,MAAM,QAAQ,gBAAgB,QAAQ,SAAS,WAAW;AAE1D,QAAO,GAAG,QAAQ,OAAO,GAAG,UAAU,GAAG,MAAM,GAAG,aAAa,QAAQ,YAAY;;;AAIrF,IAAa,mBAAmB,YAAqC;AACnE,QAAO,GAAG,QAAQ,OAAO,GAAG,mBAAm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a,eAAe,YAAsD;AAChF,QAAO,eAAe,QAAQ"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/adapter/adapter.constants.ts","../src/adapter/adapter.utils.ts","../src/adapter/adapter.fetch.ts","../src/adapter/adapter.ts","../src/socket/socket.utils.ts","../src/socket/socket.subscriptions.ts","../src/stream-adapter/stream-adapter.utils.ts","../src/stream-adapter/stream-adapter.ts","../src/websocket-adapter/websocket-adapter.utils.ts","../src/websocket-adapter/websocket-adapter.ts"],"sourcesContent":["import { Time } from \"@hyper-fetch/core\";\n\nimport type { OrpcExtraType } from \"./adapter.types\";\n\nexport const defaultTimeout = Time.SEC * 5;\n\nexport const orpcExtra: OrpcExtraType = {\n headers: {},\n};\n\nexport const OrpcMethods = {\n QUERY: \"QUERY\",\n MUTATION: \"MUTATION\",\n} as const;\n\n/** Query string key owned by the oRPC RPC protocol - it wins over the user query params */\nexport const reservedQueryParams = [\"data\"];\n\n/** Longer GET urls are sent with POST, the same limit as the `RPCLink` of oRPC */\nexport const maxGetUrlLength = 2083;\n","import type { EmptyTypes, QueryParamsType, RequestInstance } from \"@hyper-fetch/core\";\nimport { getErrorMessage, parseResponse, stringifyKey, stringifyQueryParams } from \"@hyper-fetch/core\";\nimport type { StandardRPCCustomJsonSerializer } from \"@orpc/client/standard\";\nimport { StandardRPCJsonSerializer, StandardRPCSerializer } from \"@orpc/client/standard\";\n\nimport { maxGetUrlLength, OrpcMethods, reservedQueryParams } from \"./adapter.constants\";\nimport type { OrpcErrorType, OrpcQueryMethod } from \"./adapter.types\";\n\n/** Serializer of the oRPC RPC protocol, it handles types like `Date`, `BigInt`, `Map`, `Set` and files */\nexport const createOrpcSerializer = (customJsonSerializers?: StandardRPCCustomJsonSerializer[]) => {\n return new StandardRPCSerializer(new StandardRPCJsonSerializer({ customJsonSerializers }));\n};\n\nexport type OrpcSerializerType = ReturnType<typeof createOrpcSerializer>;\n\n/** Turns the procedure path `user/byId` or `/user/byId` into the url path `/user/byId` */\nexport const orpcEndpointMapper = (endpoint: string): string => {\n const segments = endpoint.split(\"/\").filter(Boolean);\n\n return `/${segments.map(encodeURIComponent).join(\"/\")}`;\n};\n\n/**\n * Keys are built from the wire format, so values like `Date` or `Map` stay distinct.\n * Mappers run while the request is created, so an input that can't be serialized can't throw here.\n * It is reported when the request is sent.\n */\nconst getOrpcInputKey = (input: unknown, serializer: OrpcSerializerType): string => {\n try {\n const serialized = serializer.serialize(input);\n\n if (!(serialized instanceof FormData)) {\n return JSON.stringify(serialized);\n }\n\n // Files are compared by their metadata, reading their content would be too expensive\n const parts: string[] = [];\n serialized.forEach((value, key) => {\n parts.push(typeof value === \"string\" ? value : `${key}:${value.name}:${value.type}:${value.size}`);\n });\n return parts.join(\"|\");\n } catch {\n return \"\";\n }\n};\n\n/** Key of the request response - the same procedure called with a different input is a different resource */\nexport const getOrpcRequestKey = (request: RequestInstance, serializer: OrpcSerializerType): string => {\n const procedure = orpcEndpointMapper(request.endpoint);\n const input = getOrpcInputKey(request.payload, serializer);\n\n return `${request.method}_${procedure}-${input}-${stringifyKey(request.queryParams)}`;\n};\n\n/** The input is not a part of this key, so `request.abort()` stops every running call of the procedure */\nexport const getOrpcAbortKey = (request: RequestInstance): string => {\n return `${request.method}_${orpcEndpointMapper(request.endpoint)}-${request.cancelable}`;\n};\n\n/**\n * Key of a subscription - listeners of the same topic with the same input share one server subscription.\n * The input is read in the wire format, so values like `Date` or `Map` stay distinct.\n */\nexport const getOrpcSubscriptionKey = (topic: string, payload: unknown, serializer: OrpcSerializerType): string => {\n return `${topic}-${getOrpcInputKey(payload, serializer)}`;\n};\n\n/** Only the user headers, the content type depends on the encoded body and is set while sending */\nexport const getOrpcHeaders = (request: RequestInstance): HeadersInit => {\n return { ...(request.headers as Record<string, string> | undefined) };\n};\n\ntype OrpcHttpRequestType = {\n url: string;\n method: \"GET\" | \"POST\";\n headers: Record<string, string>;\n body?: string | FormData;\n};\n\n/**\n * Encodes a call of the procedure as described by the oRPC RPC protocol, for any base `url` - the client url of a\n * request or the url of a socket. GET sends the input in the `data` query param. Files and urls over the length limit\n * fall back to POST, the same as the `RPCLink` of oRPC.\n */\nexport const getOrpcCallRequest = ({\n url: base,\n endpoint,\n queryParams,\n headers,\n payload,\n method,\n serializer,\n}: {\n url: string;\n endpoint: string;\n queryParams: unknown;\n headers: HeadersInit;\n payload: unknown;\n method: \"GET\" | \"POST\";\n serializer: OrpcSerializerType;\n}): OrpcHttpRequestType => {\n const [baseUrl, baseQuery] = base.split(\"?\");\n const searchParams = new URLSearchParams(baseQuery);\n\n // Mappers can return anything, so we normalize their result to the query string\n new URLSearchParams(stringifyQueryParams(queryParams as QueryParamsType | string | EmptyTypes)).forEach(\n (value, key) => {\n if (!reservedQueryParams.includes(key)) {\n searchParams.append(key, value);\n }\n },\n );\n\n const url = `${baseUrl.replace(/\\/+$/, \"\")}${endpoint}`;\n const serialized = serializer.serialize(payload);\n const userHeaders = { ...(headers as Record<string, string>) };\n\n if (method === \"GET\" && !(serialized instanceof FormData)) {\n const getParams = new URLSearchParams(searchParams);\n getParams.append(\"data\", JSON.stringify(serialized));\n const getUrl = `${url}?${getParams.toString()}`;\n\n if (getUrl.length <= maxGetUrlLength) {\n return { url: getUrl, method: \"GET\", headers: userHeaders };\n }\n }\n\n const queryString = searchParams.toString();\n const postUrl = queryString ? `${url}?${queryString}` : url;\n\n if (serialized instanceof FormData) {\n // The browser sets the multipart content type together with its boundary\n return { url: postUrl, method: \"POST\", headers: userHeaders, body: serialized };\n }\n\n return {\n url: postUrl,\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", ...userHeaders },\n body: JSON.stringify(serialized),\n };\n};\n\n/**\n * Encodes the request as described by the oRPC RPC protocol.\n * Queries use the `queryMethod`, mutations are always sent with POST.\n */\nexport const getOrpcHttpRequest = ({\n request,\n queryMethod,\n ...call\n}: {\n request: RequestInstance;\n endpoint: string;\n queryParams: unknown;\n headers: HeadersInit;\n payload: unknown;\n queryMethod: OrpcQueryMethod;\n serializer: OrpcSerializerType;\n}): OrpcHttpRequestType => {\n const method = request.method === OrpcMethods.QUERY && queryMethod === \"GET\" ? \"GET\" : \"POST\";\n\n return getOrpcCallRequest({ ...call, url: request.client.url, method });\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => {\n return typeof value === \"object\" && value !== null;\n};\n\n/** The same check as `isORPCErrorJson` of oRPC */\nconst isOrpcError = (value: unknown): value is OrpcErrorType => {\n return (\n isRecord(value) &&\n typeof value.defined === \"boolean\" &&\n typeof value.code === \"string\" &&\n typeof value.status === \"number\" &&\n typeof value.message === \"string\"\n );\n};\n\ntype OrpcResultType = { isSuccess: true; data: unknown } | { isSuccess: false; error: unknown };\n\n/**\n * Reads the serialized `{ json, meta }` body, or the multipart body when the output contains files.\n * Statuses from 400 up are errors, the same as in oRPC.\n */\nexport const getOrpcResult = ({\n body,\n status,\n serializer,\n}: {\n body: string | FormData;\n status: number;\n serializer: OrpcSerializerType;\n}): OrpcResultType => {\n // An empty body is an undefined output\n let parsed: unknown = body || undefined;\n if (typeof parsed === \"string\") {\n parsed = parseResponse(parsed);\n }\n const isSerialized = parsed === undefined || parsed instanceof FormData || isRecord(parsed);\n\n if (!isSerialized) {\n return { isSuccess: false, error: getErrorMessage() };\n }\n\n const value = serializer.deserialize(parsed);\n if (status < 400) {\n return { isSuccess: true, data: value ?? null };\n }\n\n if (!isOrpcError(value)) {\n return { isSuccess: false, error: getErrorMessage() };\n }\n\n // The same fields as `ORPCError.toJSON()`, the data key is there even when the error has no data\n const { defined, code, status: errorStatus, message, data } = value;\n return { isSuccess: false, error: { defined, code, status: errorStatus, message, data } };\n};\n","import type { DefaultMapperType, QueryParamsType } from \"@hyper-fetch/core\";\nimport { Adapter, defaultMapper, stringifyQueryParams } from \"@hyper-fetch/core\";\n\nimport { defaultTimeout, OrpcMethods, orpcExtra } from \"./adapter.constants\";\nimport type {\n FetchOrpcAdapterOptionsType,\n OrpcAdapterOptionsType,\n OrpcAdapterType,\n OrpcExtraType,\n OrpcMethod,\n} from \"./adapter.types\";\nimport {\n createOrpcSerializer,\n getOrpcAbortKey,\n getOrpcHeaders,\n getOrpcHttpRequest,\n getOrpcRequestKey,\n getOrpcResult,\n orpcEndpointMapper,\n} from \"./adapter.utils\";\n\nconst readBody = async (response: Response, onProgress: (progress: ProgressEvent) => void) => {\n // Outputs with files are sent as multipart form data\n if (response.headers.get(\"content-type\")?.startsWith(\"multipart/form-data\")) {\n return response.formData();\n }\n\n if (!response.body || typeof response.body.getReader !== \"function\") {\n return response.text();\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n const contentLength = parseInt(response.headers.get(\"content-length\") || \"0\", 10);\n let loaded = 0;\n let body = \"\";\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n // eslint-disable-next-line no-await-in-loop\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n loaded += value.length;\n body += decoder.decode(value, { stream: true });\n onProgress({ total: contentLength || loaded, loaded } as ProgressEvent);\n }\n\n return body + decoder.decode();\n};\n\nconst getBodySize = (body: string | FormData | undefined) => {\n if (body === undefined) {\n return 0;\n }\n if (typeof body === \"string\") {\n return new Blob([body]).size;\n }\n\n let size = 0;\n body.forEach((value) => {\n size += typeof value === \"string\" ? new Blob([value]).size : value.size;\n });\n return size;\n};\n\nexport const getOrpcAdapter = ({\n queryMethod: defaultQueryMethod = \"POST\",\n customJsonSerializers,\n}: OrpcAdapterOptionsType = {}): OrpcAdapterType => {\n const serializer = createOrpcSerializer(customJsonSerializers);\n\n return (\n new Adapter<\n FetchOrpcAdapterOptionsType,\n OrpcMethod,\n number,\n OrpcExtraType,\n QueryParamsType | string,\n QueryParamsType | string | undefined,\n string,\n DefaultMapperType,\n DefaultMapperType,\n DefaultMapperType,\n DefaultMapperType\n >({\n name: \"orpc\",\n defaultMethod: OrpcMethods.QUERY,\n defaultExtra: orpcExtra,\n systemErrorStatus: 0,\n systemErrorExtra: orpcExtra,\n })\n .onInitialize(({ client }) => {\n client.setCacheKeyMapper((request) => getOrpcRequestKey(request, serializer));\n client.setQueryKeyMapper((request) => getOrpcRequestKey(request, serializer));\n client.setAbortKeyMapper((request) => getOrpcAbortKey(request));\n })\n // Queries are safe reads, the same as GET in the HttpAdapter\n .setRequestDefaults((options) => {\n const method = options.method ?? OrpcMethods.QUERY;\n return method === OrpcMethods.QUERY ? { deduplicate: true } : {};\n })\n .setDevtoolsEndpointGetter(orpcEndpointMapper)\n .setEndpointMapper(orpcEndpointMapper)\n .setQueryParamsMapper(stringifyQueryParams)\n .setHeaderMapper(getOrpcHeaders)\n // The input is encoded by the fetcher, because the method decides where it is sent\n .setPayloadMapper(defaultMapper)\n .setFetcher(\n async ({\n request,\n endpoint,\n queryParams,\n payload,\n adapterOptions,\n headers,\n onError,\n onResponseEnd,\n onTimeoutError,\n onRequestEnd,\n createAbortListener,\n getAbortController,\n onResponseProgress,\n onResponseStart,\n onBeforeRequest,\n onRequestStart,\n onRequestProgress,\n onSuccess,\n }) => {\n const {\n timeout: timeoutMs = defaultTimeout,\n queryMethod = defaultQueryMethod,\n ...restOptions\n } = adapterOptions ?? {};\n\n let timedOut = false;\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let status = 0;\n let extra = orpcExtra;\n\n const unmountListener = createAbortListener({\n status: 0,\n extra: orpcExtra,\n });\n\n // The listener above throws when the controller is missing\n const controller = getAbortController() as AbortController;\n\n if (timeoutMs > 0) {\n timeoutId = setTimeout(() => {\n timedOut = true;\n unmountListener();\n controller.abort();\n }, timeoutMs);\n }\n\n onBeforeRequest();\n onRequestStart();\n\n try {\n const httpRequest = getOrpcHttpRequest({\n request,\n endpoint,\n queryParams,\n headers,\n payload,\n queryMethod,\n serializer,\n });\n\n const total = getBodySize(httpRequest.body);\n if (total) {\n onRequestProgress({ total, loaded: total } as ProgressEvent);\n }\n\n onRequestEnd();\n\n const response = await fetch(httpRequest.url, {\n ...restOptions,\n method: httpRequest.method,\n headers: httpRequest.headers,\n body: httpRequest.body,\n signal: controller.signal,\n });\n\n onResponseStart();\n\n const responseHeaders: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n\n status = response.status;\n extra = { headers: responseHeaders };\n\n const body = await readBody(response, onResponseProgress);\n\n clearTimeout(timeoutId);\n\n onResponseEnd();\n unmountListener();\n\n const result = getOrpcResult({ body, status, serializer });\n\n if (result.isSuccess) {\n onSuccess({ data: result.data, status, extra });\n } else {\n onError({ error: result.error, status, extra });\n }\n } catch (error) {\n clearTimeout(timeoutId);\n unmountListener();\n\n if (controller.signal.aborted) {\n if (timedOut) {\n onTimeoutError({ status: 0, extra: orpcExtra });\n }\n return;\n }\n\n onError({ error, status, extra });\n }\n },\n )\n );\n};\n","import { getOrpcAdapter } from \"./adapter.fetch\";\nimport type { OrpcAdapterOptionsType, OrpcAdapterType } from \"./adapter.types\";\n\n/**\n * Adapter calling oRPC procedures with the RPC protocol.\n * The endpoint is the procedure path and the payload is the procedure input.\n *\n * @example\n * const client = createClient({ url: \"http://localhost:3000/rpc\" }).setAdapter(OrpcAdapter());\n */\nexport const OrpcAdapter = (options?: OrpcAdapterOptionsType): OrpcAdapterType => {\n return getOrpcAdapter(options);\n};\n","import { createORPCErrorFromJson, isORPCErrorJson, ORPCError } from \"@orpc/client\";\nimport { getMalformedResponseErrorCode } from \"@orpc/client/standard\";\n\nimport type { OrpcErrorType } from \"../adapter/adapter.types\";\nimport type { OrpcSerializerType } from \"../adapter/adapter.utils\";\nimport type { OrpcSocketErrorOptionsType } from \"./socket.types\";\n\nexport const toError = (error: unknown): Error => {\n return error instanceof Error ? error : new Error(String(error));\n};\n\nexport const isRecord = (value: unknown): value is Record<string, unknown> => {\n return typeof value === \"object\" && value !== null;\n};\n\n/**\n * Turns the serialized `{ json, meta }` data into the value. Anything else is not a part of the RPC protocol.\n * It throws for malformed data, the same as the serializer of oRPC.\n */\nexport const deserializeOrpcData = (data: unknown, serializer: OrpcSerializerType): unknown => {\n if (data !== undefined && !isRecord(data)) {\n throw new TypeError(\"Invalid RPC serialized data: expected the { json, meta } object\");\n }\n return serializer.deserialize(data);\n};\n\n/**\n * The error of a call the server rejected before the event iterator started, e.g. a failed input validation or\n * middleware. The same as in the `RPCLink` of oRPC: an `ORPCError` from the body, or one named after the status\n * when the body is not an oRPC error.\n */\nexport const getOrpcResponseError = ({\n status,\n body,\n serializer,\n}: {\n status: number;\n body: unknown;\n serializer: OrpcSerializerType;\n}): ORPCError<string, unknown> => {\n let value = body;\n try {\n value = deserializeOrpcData(body, serializer);\n } catch {\n // The raw body stays in the data of the error below\n }\n\n if (isORPCErrorJson(value)) {\n return createORPCErrorFromJson(value);\n }\n return new ORPCError(getMalformedResponseErrorCode(status), { status, data: value });\n};\n\n/** Reported when the procedure of a listener returns a regular output instead of an event iterator */\nexport const getNotIteratorError = (topic: string): Error => {\n return new Error(`The procedure \"${topic}\" did not return an event iterator`);\n};\n\n/**\n * Error of an oRPC subscription, reported to the `socket.onError` callbacks. `topic` and `payload` tell which\n * subscription failed. `shape` is the error the server sent, in the shape of `ORPCError.toJSON()` - it is `null` when\n * the failure did not come from a procedure, e.g. a dropped stream or a malformed message. The original error is the\n * `cause`.\n *\n * @example\n * socket.onError(({ error }) => {\n * if (error instanceof OrpcSocketError && error.defined && error.code === \"UNAUTHORIZED\") {\n * logout();\n * }\n * });\n */\nexport class OrpcSocketError<Code extends string = string, Data = unknown> extends Error {\n /** Error sent by the server, `null` when the failure did not come from a procedure */\n readonly shape: OrpcErrorType<Code, Data> | null;\n /** Topic of the failed subscription, `null` when the message can't be matched to a subscription */\n readonly topic: string | null;\n /** Input of the failed subscription */\n readonly payload: unknown;\n /** The `ORPCError` sent by the server, or the error of the transport or the decoding */\n declare readonly cause: unknown;\n\n constructor({ cause, topic, payload }: OrpcSocketErrorOptionsType) {\n const shape = cause instanceof ORPCError ? (cause.toJSON() as OrpcErrorType<Code, Data>) : null;\n super(shape?.message ?? toError(cause).message, { cause });\n this.name = \"OrpcSocketError\";\n this.shape = shape;\n this.topic = topic;\n this.payload = payload;\n }\n\n /** `true` for the errors from the `.errors()` map of the procedure */\n get defined(): boolean {\n return this.shape?.defined ?? false;\n }\n\n /** Code of the server error, e.g. `\"NOT_FOUND\"` */\n get code(): Code | undefined {\n return this.shape?.code;\n }\n\n /** Status of the server error */\n get status(): number | undefined {\n return this.shape?.status;\n }\n\n /** Data of the server error */\n get data(): Data | undefined {\n return this.shape?.data;\n }\n}\n","import type {\n ExtractAdapterExtraType,\n getAdapterBindings,\n ListenerCallbackType,\n ListenerOfAdapter,\n} from \"@hyper-fetch/sockets\";\nimport { createORPCErrorFromJson, ErrorEvent, isORPCErrorJson } from \"@orpc/client\";\n\nimport type { OrpcSerializerType } from \"../adapter/adapter.utils\";\nimport { getOrpcSubscriptionKey } from \"../adapter/adapter.utils\";\nimport type {\n OrpcIteratorEventType,\n OrpcSocketAdapterInstance,\n OrpcSocketExtraType,\n OrpcSubscriptionType,\n} from \"./socket.types\";\nimport { deserializeOrpcData, OrpcSocketError, toError } from \"./socket.utils\";\n\ntype BindingsType<Adapter extends OrpcSocketAdapterInstance> = ReturnType<typeof getAdapterBindings<Adapter>>;\n\n/**\n * Keeps one server subscription per procedure and input, shared by every listener with the same topic and payload.\n * The adapter starts and stops the server side, this module counts the listeners, turns the events of the server\n * iterator into listener messages and errors, and reports the lifecycle of the subscription to the listeners.\n *\n * - `start` is called for a subscription that has no running server side. It does nothing until the adapter can\n * start it, the adapter starts the rest when it connects.\n * - `stop` is called when the last listener of a running subscription unsubscribes - it cancels the server side.\n * - `release` forgets the server side of a subscription the server ended, without telling the server.\n */\nexport const createOrpcSubscriptions = <Adapter extends OrpcSocketAdapterInstance, Transport>({\n bindings,\n serializer,\n start,\n stop,\n release,\n}: {\n bindings: Pick<BindingsType<Adapter>, \"onListen\" | \"onEvent\" | \"onError\" | \"onListenerStart\" | \"onListenerEnd\">;\n serializer: OrpcSerializerType;\n start: (subscription: OrpcSubscriptionType<Transport>) => void;\n stop: (subscription: OrpcSubscriptionType<Transport>) => void;\n release: (subscription: OrpcSubscriptionType<Transport>) => void;\n}) => {\n const { onListen, onEvent, onError, onListenerStart, onListenerEnd } = bindings;\n const subscriptions = new Map<string, OrpcSubscriptionType<Transport>>();\n\n /** The callbacks of a subscription as the bindings of the adapter type them */\n const callbacksOf = (subscription: OrpcSubscriptionType<Transport>) =>\n subscription.callbacks as ReadonlySet<ListenerCallbackType<Adapter, any>>;\n\n const createError = (subscription: OrpcSubscriptionType<Transport>, cause: unknown) => {\n return new OrpcSocketError({ cause, topic: subscription.topic, payload: subscription.payload });\n };\n\n /**\n * Reports a failure of the subscription that does not end it, e.g. a dropped stream that starts again, as an\n * `OrpcSocketError`, so the user can tell which subscription failed\n */\n const report = (subscription: OrpcSubscriptionType<Transport>, cause: unknown) => {\n onError({ error: createError(subscription, cause) });\n };\n\n /** The server confirmed the subscription - after the first start and after every restart */\n const confirm = (subscription: OrpcSubscriptionType<Transport>) => {\n subscription.started = true;\n onListenerStart({ topic: subscription.topic, callbacks: callbacksOf(subscription) });\n };\n\n /**\n * The server ended the subscription - finished it when `cause` is not set, failed it otherwise. The error is\n * reported to `onError` too. The listeners unsubscribe, and a later `listen()` starts a new subscription.\n */\n const end = (subscription: OrpcSubscriptionType<Transport>, cause?: unknown) => {\n release(subscription);\n subscription.started = false;\n subscriptions.delete(subscription.key);\n\n const error = cause === undefined ? null : createError(subscription, cause);\n if (error) {\n onError({ error });\n }\n onListenerEnd({ topic: subscription.topic, callbacks: new Set(callbacksOf(subscription)), error });\n };\n\n const listen = (listener: ListenerOfAdapter<Adapter>, callback: ListenerCallbackType<Adapter, any>) => {\n const key = getOrpcSubscriptionKey(listener.topic, listener.payload, serializer);\n const subscription: OrpcSubscriptionType<Transport> = subscriptions.get(key) ?? {\n key,\n topic: listener.topic,\n payload: listener.payload,\n callbacks: new Set(),\n lastEventId: undefined,\n lastEventRetry: undefined,\n transport: undefined,\n started: false,\n };\n subscriptions.set(key, subscription);\n subscription.callbacks.add(callback);\n\n const removeListener = onListen({\n listener,\n callback,\n onUnmount: () => {\n subscription.callbacks.delete(callback);\n // An ended subscription is gone already, there is nothing to cancel on the server\n if (subscription.callbacks.size === 0 && subscriptions.get(key) === subscription) {\n subscriptions.delete(key);\n stop(subscription);\n }\n },\n });\n\n if (subscription.started) {\n // Joined a subscription the server confirmed already\n onListenerStart({ topic: subscription.topic, callbacks: new Set([callback]) });\n } else if (!subscription.transport) {\n start(subscription);\n }\n\n return removeListener;\n };\n\n /**\n * Applies an event of the server iterator to the subscription. `done` and `error` end the subscription, then it\n * returns `true`. Nothing here throws into the transport: errors of the server\n * and malformed data are reported as an `OrpcSocketError`, errors thrown by listener callbacks as they are.\n */\n const receive = (subscription: OrpcSubscriptionType<Transport>, { event, data, meta }: OrpcIteratorEventType) => {\n const id = typeof meta?.id === \"string\" ? meta.id : undefined;\n const retry = typeof meta?.retry === \"number\" ? meta.retry : undefined;\n // Errors carry the meta too, so a failed subscription resumes from the right place\n subscription.lastEventId = id ?? subscription.lastEventId;\n subscription.lastEventRetry = retry ?? subscription.lastEventRetry;\n\n // The value returned by the iterator is not delivered, listeners receive the yielded values\n if (event === \"done\") {\n end(subscription);\n return true;\n }\n\n let value: unknown;\n try {\n value = deserializeOrpcData(data, serializer);\n } catch (error) {\n if (event === \"error\") {\n end(subscription, error);\n return true;\n }\n report(subscription, error);\n return false;\n }\n\n if (event === \"error\") {\n // The same as the `RPCLink` of oRPC - an `ORPCError` when the data is one, the raw data otherwise\n end(subscription, isORPCErrorJson(value) ? createORPCErrorFromJson(value) : new ErrorEvent({ data: value }));\n return true;\n }\n\n // Every adapter of this package has the event meta as its extra type\n const extra = { id, retry } satisfies OrpcSocketExtraType as ExtractAdapterExtraType<Adapter>;\n try {\n onEvent({ topic: subscription.topic, data: value, extra, callbacks: callbacksOf(subscription) });\n } catch (error) {\n onError({ error: toError(error) });\n }\n return false;\n };\n\n return {\n listen,\n receive,\n report,\n confirm,\n end,\n /** Every subscription with at least one listener */\n values: () => [...subscriptions.values()],\n };\n};\n","import type { OrpcIteratorEventType } from \"../socket/socket.types\";\n\n/** One message of a `text/event-stream`, the fields of the Server-Sent Events format */\nexport type OrpcEventStreamMessageType = {\n event: string | undefined;\n data: string | undefined;\n id: string | undefined;\n retry: number | undefined;\n};\n\nconst lineEnding = /\\r\\n|\\r(?!\\n)|\\n/;\nconst messageDelimiter = /(?:\\r\\n|\\r(?!\\n)|\\n){2}/g;\n\n/** Reads the fields of one message, the same as `decodeEventMessage` of oRPC */\nconst decodeEventStreamMessage = (encoded: string): OrpcEventStreamMessageType => {\n const message: OrpcEventStreamMessageType = { event: undefined, data: undefined, id: undefined, retry: undefined };\n\n encoded.split(lineEnding).forEach((line) => {\n const index = line.indexOf(\":\");\n // Lines starting with a colon are comments, the keep-alive pings of oRPC\n if (line === \"\" || index === 0) {\n return;\n }\n const field = index === -1 ? line : line.slice(0, index);\n const value = index === -1 ? \"\" : line.slice(line.charAt(index + 1) === \" \" ? index + 2 : index + 1);\n\n if (field === \"data\") {\n message.data = message.data === undefined ? value : `${message.data}\\n${value}`;\n } else if (field === \"event\") {\n message.event = value;\n } else if (field === \"id\") {\n message.id = value;\n } else if (field === \"retry\") {\n const retry = Number.parseInt(value, 10);\n if (retry >= 0 && retry.toString() === value) {\n message.retry = retry;\n }\n }\n });\n\n return message;\n};\n\n/**\n * Splits the text of a `text/event-stream` into messages, the same as the `EventDecoder` of oRPC. Chunks can end\n * anywhere, the text after the last complete message waits for the next chunk.\n */\nexport const createEventStreamDecoder = (onMessage: (message: OrpcEventStreamMessageType) => void) => {\n let pending = \"\";\n // A chunk that ended a message with `\\r` may be followed by the `\\n` of the same `\\r\\n`\n let discardLeadingLineFeed = false;\n\n const feed = (chunk: string) => {\n pending += discardLeadingLineFeed && chunk.startsWith(\"\\n\") ? chunk.slice(1) : chunk;\n discardLeadingLineFeed = false;\n\n let start = 0;\n const messages: string[] = [];\n [...pending.matchAll(messageDelimiter)].forEach((match) => {\n // `matchAll` always sets the index - older TypeScript versions type it as optional\n const { index = 0 } = match;\n messages.push(pending.slice(start, index));\n start = index + match[0].length;\n });\n if (messages.length > 0) {\n discardLeadingLineFeed = start === pending.length && pending.endsWith(\"\\r\");\n }\n pending = pending.slice(start);\n\n messages.forEach((message) => onMessage(decodeEventStreamMessage(message)));\n };\n\n /** The same as oRPC - a stream that stops in the middle of a message is broken */\n const end = () => {\n if (pending !== \"\") {\n throw new Error(\"The event stream ended before the last message was complete\");\n }\n };\n\n return { feed, end };\n};\n\n/**\n * Maps a message to the event of the server iterator, the same as `toEventIterator` of oRPC. Messages without an\n * event and data are keep-alive pings and return `null`. Throws when the data is not JSON.\n */\nexport const getEventStreamIteratorEvent = (message: OrpcEventStreamMessageType): OrpcIteratorEventType | null => {\n const event = message.event ?? (message.data !== undefined ? \"message\" : undefined);\n const meta = { id: message.id, retry: message.retry };\n\n if (event === \"message\" || event === \"error\") {\n return { event, data: message.data ? JSON.parse(message.data) : undefined, meta };\n }\n if (event === \"done\" || event === \"close\") {\n return { event: \"done\", data: undefined, meta };\n }\n return null;\n};\n","/* eslint-disable @typescript-eslint/no-use-before-define */\nimport type { QueryParamsType } from \"@hyper-fetch/core\";\nimport { parseResponse, stringifyQueryParams } from \"@hyper-fetch/core\";\nimport type { SocketConnectionType } from \"@hyper-fetch/sockets\";\nimport { SocketAdapter } from \"@hyper-fetch/sockets\";\nimport { isORPCErrorStatus } from \"@orpc/client\";\n\nimport { createOrpcSerializer, getOrpcCallRequest, orpcEndpointMapper } from \"../adapter/adapter.utils\";\nimport { createOrpcSubscriptions } from \"../socket/socket.subscriptions\";\nimport type { OrpcSocketAdapterConfigType, OrpcSocketExtraType, OrpcSubscriptionType } from \"../socket/socket.types\";\nimport { getNotIteratorError, getOrpcResponseError } from \"../socket/socket.utils\";\nimport type { OrpcStreamAdapterOptionsType, OrpcStreamAdapterType } from \"./stream-adapter.types\";\nimport type { OrpcEventStreamMessageType } from \"./stream-adapter.utils\";\nimport { createEventStreamDecoder, getEventStreamIteratorEvent } from \"./stream-adapter.utils\";\n\n/** Server side of one subscription - a running request, or the wait before it starts again */\ntype StreamTransportType = {\n /** Aborts the running request. It is missing while the stream waits to start again. */\n controller: AbortController | undefined;\n /** Open timeout of the running request, or the delay before the stream starts again */\n timer: ReturnType<typeof setTimeout> | undefined;\n /** Failed starts in a row */\n attempts: number;\n timedOut: boolean;\n};\n\ntype StreamSubscriptionType = OrpcSubscriptionType<StreamTransportType>;\n\n/**\n * Socket adapter for the event iterators of oRPC over HTTP. Every subscription is a call of the procedure with the\n * RPC protocol - a `POST {url}/planet/onUpdate` with the serialized input - answered with a `text/event-stream`.\n * The same protocol as the `RPCLink` of oRPC, so it works with the `RPCHandler` of `@orpc/server/fetch` or `/node`.\n *\n * There is no shared connection: \"connected\" means the adapter opens streams. `connect()` starts every\n * subscription, `disconnect()` aborts them, `reconnect()` starts them again with the id of their last event.\n * Listeners of the same procedure and input share one stream, the last one to unsubscribe aborts it.\n * A subscription starts (`onStart`) when the server answers with the event stream, and ends (`onEnd`) when the\n * iterator finishes, fails or the server rejects the call.\n *\n * @example\n * const socket = new Socket({ url: \"http://localhost:3000/rpc\", adapter: OrpcStreamAdapter() });\n * const sdk = createSocketSdk<typeof socket, OrpcSocketSchema<typeof router>>(socket, { camelCaseToKebabCase: false });\n *\n * sdk.planet.onUpdate.$listener.setPayload({ id: 1 }).listen(({ data, extra }) => console.log(data, extra.id));\n */\nexport const OrpcStreamAdapter = ({\n customJsonSerializers,\n}: OrpcSocketAdapterConfigType = {}): OrpcStreamAdapterType => {\n const serializer = createOrpcSerializer(customJsonSerializers);\n\n return new SocketAdapter<\n OrpcSocketExtraType,\n OrpcStreamAdapterOptionsType,\n undefined,\n undefined,\n QueryParamsType | string,\n typeof stringifyQueryParams\n >({ name: \"orpc-stream\", confirmsSubscriptions: true })\n .setQueryParamsMapper(stringifyQueryParams)\n .setConnector((bindings) => {\n const {\n socket,\n adapter,\n getQueryParams,\n onConnect,\n onConnectFailed,\n onReconnect,\n onDisconnect,\n onConnected,\n onDisconnected,\n } = bindings;\n\n const autoConnect = adapter.adapterOptions?.autoConnect ?? true;\n\n // Details of the current connection (after onConnect interceptors), every stream is opened with them.\n // Set only while the adapter is connected.\n let connection: SocketConnectionType<OrpcStreamAdapterType> | undefined;\n // Connection attempt in progress - concurrent `connect()` calls join it\n let pendingConnection: Promise<boolean> | undefined;\n\n const subscriptions = createOrpcSubscriptions<OrpcStreamAdapterType, StreamTransportType>({\n bindings,\n serializer,\n start: (subscription) => startStream(subscription, 0),\n stop: (subscription) => stopStream(subscription),\n release: (subscription) => stopStream(subscription),\n });\n\n /**\n * Aborts the request or the wait of the subscription. Whatever the old request reports later is ignored.\n * For a stream the server ended it only releases the response.\n */\n const stopStream = (subscription: StreamSubscriptionType) => {\n const { transport } = subscription;\n subscription.transport = undefined;\n subscription.started = false;\n if (transport) {\n clearTimeout(transport.timer);\n transport.controller?.abort();\n }\n };\n\n /** After a failure the stream starts again, after the `retry` of the last event or the socket reconnect time */\n const scheduleRestart = (subscription: StreamSubscriptionType, attempts: number) => {\n if (attempts > socket.reconnectAttempts) {\n subscriptions.end(\n subscription,\n new Error(`Stopped restarting the stream of \"${subscription.topic}\" after ${attempts - 1} attempts`),\n );\n return;\n }\n\n const transport: StreamTransportType = { controller: undefined, timer: undefined, attempts, timedOut: false };\n transport.timer = setTimeout(() => {\n // Offline the stream waits for the network and starts again when the app is back online\n if (socket.appManager.isOnline) {\n startStream(subscription, attempts);\n }\n }, subscription.lastEventRetry ?? socket.reconnectTime);\n subscription.transport = transport;\n };\n\n /** Returns `true` when the server ended the iterator */\n const receiveMessage = (subscription: StreamSubscriptionType, message: OrpcEventStreamMessageType): boolean => {\n try {\n const event = getEventStreamIteratorEvent(message);\n return event ? subscriptions.receive(subscription, event) : false;\n } catch (error) {\n // Data that is not JSON - the message is skipped, the stream goes on\n subscriptions.report(subscription, error);\n return false;\n }\n };\n\n /**\n * Reads the stream until the server ends it. Resolves the error of a call the server rejected, rejects when\n * the transport failed - the network, the timeout or a stream cut in the middle of a message.\n */\n const readStream = async ({\n subscription,\n transport,\n controller,\n details: { url, queryParams, adapterOptions },\n }: {\n subscription: StreamSubscriptionType;\n transport: StreamTransportType;\n controller: AbortController;\n details: SocketConnectionType<OrpcStreamAdapterType>;\n }): Promise<Error | null> => {\n const { headers, fetchOptions, fetch: customFetch } = adapterOptions ?? {};\n const { lastEventId } = subscription;\n const request = getOrpcCallRequest({\n url,\n endpoint: orpcEndpointMapper(subscription.topic),\n queryParams: getQueryParams(queryParams),\n // The server reads it as `lastEventId` and can resume where the previous stream stopped\n headers: lastEventId === undefined ? { ...headers } : { ...headers, \"last-event-id\": lastEventId },\n payload: subscription.payload,\n method: \"POST\",\n serializer,\n });\n\n // Checked to be a function when connecting\n const fetchStream = customFetch ?? globalThis.fetch;\n const response = await fetchStream(request.url, {\n ...fetchOptions,\n method: request.method,\n headers: request.headers,\n body: request.body,\n signal: controller.signal,\n });\n clearTimeout(transport.timer);\n\n if (isORPCErrorStatus(response.status)) {\n const body = parseResponse(await response.text());\n return getOrpcResponseError({ status: response.status, body, serializer });\n }\n if (!response.headers.get(\"content-type\")?.startsWith(\"text/event-stream\")) {\n return getNotIteratorError(subscription.topic);\n }\n // The server accepted the call, the next failure counts from the beginning\n transport.attempts = 0;\n // Unless the listeners left while the response was on its way\n if (subscription.transport === transport) {\n subscriptions.confirm(subscription);\n }\n\n if (!response.body) {\n return null;\n }\n\n const reader = response.body.getReader();\n const textDecoder = new TextDecoder();\n let ended = false;\n const eventDecoder = createEventStreamDecoder((message) => {\n // Messages after the end, or after the subscription stopped, are not delivered\n if (!ended && subscription.transport === transport) {\n ended = receiveMessage(subscription, message);\n }\n });\n\n let chunk = await reader.read();\n while (!chunk.done) {\n eventDecoder.feed(textDecoder.decode(chunk.value, { stream: true }));\n if (ended) {\n return null;\n }\n // eslint-disable-next-line no-await-in-loop\n chunk = await reader.read();\n }\n // A stream closed without the `done` event is a finished iterator, the same as in oRPC\n eventDecoder.feed(textDecoder.decode());\n eventDecoder.end();\n return null;\n };\n\n const startStream = (subscription: StreamSubscriptionType, attempts: number) => {\n // Not connected - the stream starts on connect\n const details = connection;\n if (!details) {\n return;\n }\n\n const controller = new AbortController();\n const transport: StreamTransportType = { controller, timer: undefined, attempts, timedOut: false };\n subscription.transport = transport;\n const isCurrent = () => subscription.transport === transport;\n\n // Connection timeout - when the server does not answer in time, the stream starts again\n transport.timer = setTimeout(() => {\n transport.timedOut = true;\n controller.abort();\n }, socket.connectionTimeout);\n\n readStream({ subscription, transport, controller, details }).then(\n (rejection) => {\n if (!isCurrent()) {\n return;\n }\n // The server ended the iterator or rejected the call - the subscription is over\n subscriptions.end(subscription, rejection ?? undefined);\n },\n (error) => {\n if (!isCurrent()) {\n return;\n }\n stopStream(subscription);\n subscriptions.report(\n subscription,\n transport.timedOut\n ? new Error(`The stream of \"${subscription.topic}\" did not open in ${socket.connectionTimeout}ms`)\n : error,\n );\n scheduleRestart(subscription, transport.attempts + 1);\n },\n );\n };\n\n const openConnection = async (): Promise<boolean> => {\n const details = await onConnect();\n if (!details) {\n return adapter.connected;\n }\n\n if (typeof (details.adapterOptions?.fetch ?? globalThis.fetch) !== \"function\") {\n onConnectFailed({ error: new Error(\"fetch is not available in this environment\") });\n return false;\n }\n\n connection = details;\n onConnected();\n [...subscriptions.values()].forEach((subscription) => {\n // A listener added by an `onConnected` callback is running already\n if (!subscription.transport) {\n startStream(subscription, 0);\n }\n });\n return true;\n };\n\n const connect = (): Promise<boolean> => {\n // Another attempt is already on its way (e.g. the automatic one) - resolve together with it\n if (adapter.connecting && pendingConnection) {\n return pendingConnection;\n }\n\n const attempt = openConnection();\n pendingConnection = attempt;\n const release = () => {\n if (pendingConnection === attempt) {\n pendingConnection = undefined;\n }\n };\n attempt.then(release, release);\n\n return attempt;\n };\n\n /** Aborts every stream. Listeners stay registered and keep the id of their last event for the next connection. */\n const closeConnection = async ({ manual }: { manual: boolean }): Promise<boolean> => {\n const wasActive = adapter.connected || adapter.connecting;\n connection = undefined;\n [...subscriptions.values()].forEach(stopStream);\n\n onDisconnect();\n if (!manual) {\n // Closing the previous streams is a part of reconnecting - only `disconnect()` keeps the socket closed\n adapter.setForceClosed(false);\n }\n if (wasActive) {\n onDisconnected();\n }\n return true;\n };\n\n /** Manual disconnect - the socket stays closed until `connect()` or `reconnect()` is called */\n const disconnect = (): Promise<boolean> => {\n return closeConnection({ manual: true });\n };\n\n const reconnect = async () => {\n // Reconnecting is a request to be connected, also after a manual disconnect\n adapter.setForceClosed(false);\n\n await onReconnect({\n disconnect: () => closeConnection({ manual: false }),\n connect: async () => {\n // `disconnect()` called in the meantime wins over the reconnection\n if (adapter.forceClosed) {\n adapter.setReconnectionAttempts(0);\n return false;\n }\n return connect();\n },\n });\n };\n\n // Event iterators only send data from the server. Throwing synchronously makes `emitter.emit()` fail right at\n // the call site, the same as in the Server-Sent Events adapter.\n const emit = () => {\n throw new Error(\"Cannot emit events in the oRPC stream adapter, it only receives events of subscriptions\");\n };\n\n // Initialize\n if (autoConnect) {\n connect();\n }\n\n const unmountOnline = socket.appManager.events.onOnline(() => {\n if (connection) {\n // Streams that failed while offline start again right away\n [...subscriptions.values()].forEach((subscription) => {\n const { transport } = subscription;\n if (transport && !transport.controller) {\n clearTimeout(transport.timer);\n startStream(subscription, transport.attempts);\n }\n });\n return;\n }\n // A socket disconnected on purpose stays closed until `connect()` or `reconnect()` is called\n if (autoConnect && !adapter.forceClosed) {\n connect();\n }\n });\n\n return {\n connect,\n reconnect,\n disconnect,\n listen: subscriptions.listen,\n emit,\n // Nothing of this connector outlives the socket - no online subscription, no running or waiting streams\n dispose: () => {\n unmountOnline();\n connection = undefined;\n [...subscriptions.values()].forEach(stopStream);\n },\n };\n });\n};\n","import type { OrpcSerializerType } from \"../adapter/adapter.utils\";\nimport { orpcEndpointMapper } from \"../adapter/adapter.utils\";\nimport type { OrpcIteratorEventType } from \"../socket/socket.types\";\nimport { isRecord } from \"../socket/socket.utils\";\n\n/** Message types of the oRPC peer protocol, used by `@orpc/server/ws` and `@orpc/client/websocket` */\nconst peerMessageType = {\n REQUEST: 1,\n RESPONSE: 2,\n EVENT_ITERATOR: 3,\n ABORT_SIGNAL: 4,\n} as const;\n\n/** JSON and binary parts of a binary frame are split by this byte */\nconst binaryDelimiter = 255;\n\n/** A message the server sends for one request */\nexport type OrpcPeerResponseMessageType =\n | { id: string; type: \"response\"; status: number; headers: Record<string, unknown>; body: unknown }\n | { id: string; type: \"event\"; event: OrpcIteratorEventType }\n | { id: string; type: \"abort\" };\n\nconst getMalformedError = (detail: string) => new TypeError(`Invalid oRPC message: ${detail}`);\n\n/**\n * Starts the call of the procedure - the same request message as the `RPCLink` of `@orpc/client/websocket`.\n * The input is serialized with the RPC serializer, inputs with files are not supported.\n */\nexport const encodeOrpcRequestMessage = ({\n id,\n topic,\n payload,\n headers,\n serializer,\n}: {\n id: string;\n topic: string;\n payload: unknown;\n headers: Record<string, string>;\n serializer: OrpcSerializerType;\n}): string => {\n const body = serializer.serialize(payload);\n if (body instanceof FormData) {\n throw new TypeError(`Files in the input of \"${topic}\" are not supported by the oRPC WebSocket adapter`);\n }\n\n // The `POST` method is the default of the protocol, so it is not sent\n return JSON.stringify({\n i: id,\n p: { u: orpcEndpointMapper(topic), b: body, h: Object.keys(headers).length > 0 ? headers : undefined },\n });\n};\n\n/** Stops the call of the procedure, the server cancels its iterator */\nexport const encodeOrpcAbortMessage = (id: string): string => {\n return JSON.stringify({ i: id, t: peerMessageType.ABORT_SIGNAL });\n};\n\nconst readFrameText = (frame: unknown): string => {\n if (typeof frame === \"string\") {\n return frame;\n }\n if (frame instanceof ArrayBuffer || ArrayBuffer.isView(frame)) {\n const bytes =\n frame instanceof ArrayBuffer\n ? new Uint8Array(frame)\n : new Uint8Array(frame.buffer, frame.byteOffset, frame.byteLength);\n // Binary frames carry a file after the delimiter, event iterators never send files\n const end = bytes.indexOf(binaryDelimiter);\n return new TextDecoder().decode(end === -1 ? bytes : bytes.subarray(0, end));\n }\n throw getMalformedError(\"expected a text or a binary frame\");\n};\n\n/** Reads a message of the server, the same as `decodeResponseMessage` of oRPC. Throws for malformed frames. */\nexport const decodeOrpcResponseMessage = (frame: unknown): OrpcPeerResponseMessageType => {\n const message: unknown = JSON.parse(readFrameText(frame));\n if (!isRecord(message) || typeof message.i !== \"string\") {\n throw getMalformedError(\"expected an object with the request id\");\n }\n\n const { i: id, t: type, p: payload } = message;\n if (type === peerMessageType.ABORT_SIGNAL) {\n return { id, type: \"abort\" };\n }\n if (!isRecord(payload)) {\n throw getMalformedError(\"expected the payload object\");\n }\n\n if (type === peerMessageType.EVENT_ITERATOR) {\n const { e: event, d: data, m: meta } = payload;\n if (event !== \"message\" && event !== \"error\" && event !== \"done\") {\n throw getMalformedError(`unknown event \"${String(event)}\"`);\n }\n return { id, type: \"event\", event: { event, data, meta: isRecord(meta) ? meta : undefined } };\n }\n\n // Any other message is a response, the same as in oRPC\n const { s: status = 200, h: headers = {}, b: body } = payload;\n if (typeof status !== \"number\" || !isRecord(headers)) {\n throw getMalformedError(\"expected the status and the headers of the response\");\n }\n return { id, type: \"response\", status, headers, body };\n};\n\nconst flattenHeader = (header: unknown): string | undefined => {\n if (typeof header === \"string\") {\n return header;\n }\n return Array.isArray(header) && header.length > 0 ? header.join(\", \") : undefined;\n};\n\n/** The same check as `isEventIteratorHeaders` of oRPC - an event stream that is not a file */\nexport const isOrpcEventIteratorResponse = (headers: Record<string, unknown>): boolean => {\n return (\n !!flattenHeader(headers[\"content-type\"])?.startsWith(\"text/event-stream\") &&\n flattenHeader(headers[\"content-disposition\"]) === undefined\n );\n};\n","/* eslint-disable @typescript-eslint/no-use-before-define */\nimport type { QueryParamsType } from \"@hyper-fetch/core\";\nimport { stringifyQueryParams } from \"@hyper-fetch/core\";\nimport {\n getSocketError,\n getSocketUrl,\n getWebsocketConstructor,\n SocketAdapter,\n WebsocketReadyState,\n} from \"@hyper-fetch/sockets\";\nimport { isORPCErrorStatus } from \"@orpc/client\";\n\nimport { createOrpcSerializer } from \"../adapter/adapter.utils\";\nimport { createOrpcSubscriptions } from \"../socket/socket.subscriptions\";\nimport type { OrpcSocketAdapterConfigType, OrpcSocketExtraType, OrpcSubscriptionType } from \"../socket/socket.types\";\nimport { getNotIteratorError, getOrpcResponseError, OrpcSocketError, toError } from \"../socket/socket.utils\";\nimport type { OrpcWebsocketAdapterOptionsType, OrpcWebsocketAdapterType } from \"./websocket-adapter.types\";\nimport type { OrpcPeerResponseMessageType } from \"./websocket-adapter.utils\";\nimport {\n decodeOrpcResponseMessage,\n encodeOrpcAbortMessage,\n encodeOrpcRequestMessage,\n isOrpcEventIteratorResponse,\n} from \"./websocket-adapter.utils\";\n\n/** Server side of one subscription - its request on the connection */\ntype WebsocketTransportType = { id: string; websocket: WebSocket };\n\ntype WebsocketSubscriptionType = OrpcSubscriptionType<WebsocketTransportType>;\n\n/**\n * Socket adapter for the event iterators of oRPC over one WebSocket connection. It speaks the protocol of the\n * `RPCHandler` of `@orpc/server/ws` (the same as `@orpc/client/websocket`): every subscription is a request on the\n * shared connection, and its events arrive as messages of that request.\n *\n * The adapter only subscribes. Emitting, and calling regular procedures, is not supported - use `OrpcAdapter` for\n * them. Listeners of the same procedure and input share one request, the last one to unsubscribe aborts it.\n * After a reconnect every running subscription starts again with the id of its last event. A subscription starts\n * (`onStart`) when the server answers with the event iterator, and ends (`onEnd`) when the iterator finishes, fails\n * or the server rejects the call.\n *\n * @example\n * const socket = new Socket({ url: \"ws://localhost:3000\", adapter: OrpcWebsocketAdapter() });\n * const sdk = createSocketSdk<typeof socket, OrpcSocketSchema<typeof router>>(socket, { camelCaseToKebabCase: false });\n *\n * sdk.planet.onUpdate.$listener.setPayload({ id: 1 }).listen(({ data }) => console.log(data));\n */\nexport const OrpcWebsocketAdapter = ({\n customJsonSerializers,\n}: OrpcSocketAdapterConfigType = {}): OrpcWebsocketAdapterType => {\n const serializer = createOrpcSerializer(customJsonSerializers);\n\n return new SocketAdapter<\n OrpcSocketExtraType,\n OrpcWebsocketAdapterOptionsType,\n undefined,\n undefined,\n QueryParamsType | string,\n typeof stringifyQueryParams\n >({ name: \"orpc-websocket\", confirmsSubscriptions: true })\n .setQueryParamsMapper(stringifyQueryParams)\n .setConnector((bindings) => {\n const {\n socket,\n adapter,\n getQueryParams,\n onConnect,\n onConnectFailed,\n onReconnect,\n onDisconnect,\n onConnected,\n onDisconnected,\n onError,\n } = bindings;\n\n const autoConnect = adapter.adapterOptions?.autoConnect ?? true;\n\n // The transport in use. Events of any other instance (replaced or closed on purpose) are ignored.\n let websocket: WebSocket | undefined;\n // Options of the current connection (after onConnect interceptors)\n let options: OrpcWebsocketAdapterOptionsType | undefined;\n // Connection attempt in progress - concurrent `connect()` calls join it\n let pendingConnection: Promise<boolean> | undefined;\n // Connection timeout while connecting, reconnection delay after the connection was lost\n let timeout: ReturnType<typeof setTimeout> | undefined;\n // Request ids are never reused, so a late message of a stopped request can't reach a new one\n let lastRequestId = 0;\n // Running requests of the current connection\n const requests = new Map<string, WebsocketSubscriptionType>();\n\n const subscriptions = createOrpcSubscriptions<OrpcWebsocketAdapterType, WebsocketTransportType>({\n bindings,\n serializer,\n start: (subscription) => startSubscription(subscription),\n stop: (subscription) => stopSubscription(subscription),\n release: (subscription) => {\n releaseSubscription(subscription);\n },\n });\n\n /** Sends a frame of the subscription, reporting the failure instead of throwing */\n const sendFrame = (subscription: WebsocketSubscriptionType, target: WebSocket, frame: string): boolean => {\n try {\n target.send(frame);\n return true;\n } catch (error) {\n subscriptions.report(subscription, error);\n return false;\n }\n };\n\n const startSubscription = (subscription: WebsocketSubscriptionType) => {\n // Not connected - the subscription starts on connect\n const current = websocket;\n if (!current || !adapter.connected) {\n return;\n }\n\n lastRequestId += 1;\n const id = lastRequestId.toString(36);\n const { lastEventId } = subscription;\n // The server reads it as `lastEventId` and can resume where the previous connection stopped\n const headers =\n lastEventId === undefined ? { ...options?.headers } : { ...options?.headers, \"last-event-id\": lastEventId };\n\n let frame: string;\n try {\n frame = encodeOrpcRequestMessage({\n id,\n topic: subscription.topic,\n payload: subscription.payload,\n headers,\n serializer,\n });\n } catch (error) {\n // An input that can't be encoded never will be, so the subscription is over\n subscriptions.end(subscription, error);\n return;\n }\n\n if (sendFrame(subscription, current, frame)) {\n subscription.transport = { id, websocket: current };\n requests.set(id, subscription);\n }\n };\n\n /** Forgets the request of the subscription. Messages that still come for it are ignored. */\n const releaseSubscription = (subscription: WebsocketSubscriptionType) => {\n const { transport } = subscription;\n subscription.transport = undefined;\n subscription.started = false;\n if (transport) {\n requests.delete(transport.id);\n }\n return transport;\n };\n\n const stopSubscription = (subscription: WebsocketSubscriptionType) => {\n const transport = releaseSubscription(subscription);\n if (transport) {\n sendFrame(subscription, transport.websocket, encodeOrpcAbortMessage(transport.id));\n }\n };\n\n /** The connection is gone and the server dropped every request with it */\n const releaseAll = () => {\n requests.forEach((subscription) => {\n subscription.transport = undefined;\n subscription.started = false;\n });\n requests.clear();\n };\n\n const handleResponse = (\n subscription: WebsocketSubscriptionType,\n { status, headers, body }: Extract<OrpcPeerResponseMessageType, { type: \"response\" }>,\n ) => {\n // The server rejected the call before the iterator started, e.g. a failed input validation\n if (isORPCErrorStatus(status)) {\n subscriptions.end(subscription, getOrpcResponseError({ status, body, serializer }));\n return;\n }\n if (!isOrpcEventIteratorResponse(headers)) {\n subscriptions.end(subscription, getNotIteratorError(subscription.topic));\n return;\n }\n // The response of an event iterator - the subscription runs\n subscriptions.confirm(subscription);\n };\n\n const handleMessage = (frame: unknown) => {\n let message: OrpcPeerResponseMessageType;\n try {\n message = decodeOrpcResponseMessage(frame);\n } catch (error) {\n // A frame that can't be read can't be matched to its subscription either\n onError({ error: new OrpcSocketError({ cause: error, topic: null, payload: undefined }) });\n return;\n }\n\n // Late messages of stopped requests, and the abort the server sends for iterators in the input, are ignored\n const subscription = requests.get(message.id);\n if (!subscription || message.type === \"abort\") {\n return;\n }\n\n if (message.type === \"response\") {\n handleResponse(subscription, message);\n return;\n }\n // `done` and `error` end the subscription there\n subscriptions.receive(subscription, message.event);\n };\n\n /** Starts over after `delay` - the connection timeout while connecting, the reconnect delay after a loss */\n const scheduleReconnect = (delay = socket.reconnectTime) => {\n clearTimeout(timeout);\n timeout = setTimeout(() => {\n reconnect();\n }, delay);\n };\n\n const openConnection = async (): Promise<boolean> => {\n const connection = await onConnect();\n if (!connection) {\n return adapter.connected;\n }\n\n clearTimeout(timeout);\n options = connection.adapterOptions;\n const url = getSocketUrl(connection.url, getQueryParams(connection.queryParams));\n\n const WebSocketConstructor = getWebsocketConstructor(options);\n if (!WebSocketConstructor) {\n onConnectFailed({ error: new Error(\"WebSocket is not available in this environment\") });\n return false;\n }\n\n let instance: WebSocket;\n try {\n instance = new WebSocketConstructor(url, options?.protocols);\n } catch (error) {\n onConnectFailed({ error: toError(error) });\n return false;\n }\n // Binary frames are read synchronously, so messages keep their order\n instance.binaryType = \"arraybuffer\";\n websocket = instance;\n const isCurrent = () => websocket === instance;\n\n // Connection timeout - when the server does not answer in time, start over\n scheduleReconnect(socket.connectionTimeout);\n\n return new Promise<boolean>((resolve) => {\n // A closed instance never opens, so the open event always belongs to the current one\n instance.addEventListener(\"open\", () => {\n clearTimeout(timeout);\n onConnected();\n [...subscriptions.values()].forEach((subscription) => {\n // A listener added by an `onConnected` callback is running already\n if (!subscription.transport) {\n startSubscription(subscription);\n }\n });\n resolve(true);\n });\n\n /** The transport is gone - report it and get the connection back unless it was closed normally */\n const onTransportClosed = (event: Pick<CloseEvent, \"code\"> & Event) => {\n websocket = undefined;\n clearTimeout(timeout);\n releaseAll();\n onDisconnected();\n onError({ error: new Error(getSocketError(event)) });\n\n // The connection was lost or closed by the server with an error - try to get it back\n if (event.code !== 1000) {\n scheduleReconnect();\n }\n };\n\n instance.addEventListener(\"close\", (event) => {\n resolve(false);\n if (!isCurrent()) {\n return;\n }\n onTransportClosed(event);\n });\n\n // Node.js 22 reports a failed handshake with `error` only - no `close` follows and the transport stays\n // CONNECTING. Browsers set CLOSED before the error and send the close event, which handles it as usual.\n // Here the transport is detached and treated as an abnormally closed one (1006).\n instance.addEventListener(\"error\", () => {\n if (!isCurrent() || instance.readyState !== WebsocketReadyState.CONNECTING) {\n return;\n }\n resolve(false);\n try {\n instance.close();\n } catch {\n // Closing a transport that never connected may throw in some runtimes - it is detached already\n }\n onTransportClosed(Object.assign(new Event(\"close\"), { code: 1006 }));\n });\n\n instance.addEventListener(\"message\", (event) => {\n if (isCurrent()) {\n handleMessage(event.data);\n }\n });\n });\n };\n\n const connect = (): Promise<boolean> => {\n // Another attempt is already on its way (e.g. the automatic one) - resolve together with it\n if (adapter.connecting && pendingConnection) {\n return pendingConnection;\n }\n\n const attempt = openConnection();\n pendingConnection = attempt;\n const release = () => {\n if (pendingConnection === attempt) {\n pendingConnection = undefined;\n }\n };\n attempt.then(release, release);\n\n return attempt;\n };\n\n /**\n * Closes the transport and resets the connection state. The server cancels every subscription of the\n * connection, the listeners stay registered and keep the id of their last event for the next connection.\n */\n const closeConnection = async ({ manual }: { manual: boolean }): Promise<boolean> => {\n clearTimeout(timeout);\n\n const current = websocket;\n websocket = undefined;\n releaseAll();\n\n const wasActive = adapter.connected || adapter.connecting;\n onDisconnect();\n if (!manual) {\n // Closing the previous transport is a part of reconnecting - only `disconnect()` keeps the socket closed\n adapter.setForceClosed(false);\n }\n if (wasActive) {\n onDisconnected();\n }\n\n if (!current) {\n return true;\n }\n return new Promise<boolean>((resolve) => {\n current.addEventListener(\"close\", () => resolve(true), { once: true });\n // A transport that fails while closing may report only `error` (Node.js 22) - don't wait for a close\n current.addEventListener(\"error\", () => resolve(true), { once: true });\n current.close(1000);\n });\n };\n\n /** Manual disconnect - the socket stays closed until `connect()` or `reconnect()` is called */\n const disconnect = (): Promise<boolean> => {\n return closeConnection({ manual: true });\n };\n\n const reconnect = async () => {\n // Reconnecting is a request to be connected, also after a manual disconnect\n adapter.setForceClosed(false);\n\n await onReconnect({\n disconnect: () => closeConnection({ manual: false }),\n connect: async () => {\n // `disconnect()` called while the previous transport was closing wins over the reconnection\n if (adapter.forceClosed) {\n adapter.setReconnectionAttempts(0);\n return false;\n }\n return connect();\n },\n });\n };\n\n // Throwing synchronously makes `emitter.emit()` fail right at the call site, the same as in the\n // Server-Sent Events adapter\n const emit = () => {\n throw new Error(\"Cannot emit events in the oRPC WebSocket adapter, it only receives events of subscriptions\");\n };\n\n // Initialize\n if (autoConnect) {\n connect();\n }\n\n const unmountOnline = socket.appManager.events.onOnline(() => {\n // A socket disconnected on purpose stays closed until `connect()` or `reconnect()` is called\n if (autoConnect && !adapter.connected && !adapter.forceClosed) {\n connect();\n }\n });\n\n return {\n connect,\n reconnect,\n disconnect,\n listen: subscriptions.listen,\n emit,\n // Nothing of this connector outlives the socket - no online subscription, no pending reconnect\n dispose: () => {\n unmountOnline();\n clearTimeout(timeout);\n },\n };\n });\n};\n"],"mappings":";;;;;AAIA,IAAa,iBAAiB,KAAK,MAAM;AAEzC,IAAa,YAA2B,EACtC,SAAS,EAAE,EACZ;AAED,IAAa,cAAc;CACzB,OAAO;CACP,UAAU;CACX;;AAGD,IAAa,sBAAsB,CAAC,OAAO;;AAG3C,IAAa,kBAAkB;;;;ACV/B,IAAa,wBAAwB,0BAA8D;AACjG,QAAO,IAAI,sBAAsB,IAAI,0BAA0B,EAAE,uBAAuB,CAAC,CAAC;;;AAM5F,IAAa,sBAAsB,aAA6B;AAG9D,QAAO,IAFU,SAAS,MAAM,IAAI,CAAC,OAAO,QAAQ,CAEhC,IAAI,mBAAmB,CAAC,KAAK,IAAI;;;;;;;AAQvD,IAAM,mBAAmB,OAAgB,eAA2C;AAClF,KAAI;EACF,MAAM,aAAa,WAAW,UAAU,MAAM;AAE9C,MAAI,EAAE,sBAAsB,UAC1B,QAAO,KAAK,UAAU,WAAW;EAInC,MAAM,QAAkB,EAAE;AAC1B,aAAW,SAAS,OAAO,QAAQ;AACjC,SAAM,KAAK,OAAO,UAAU,WAAW,QAAQ,GAAG,IAAI,GAAG,MAAM,KAAK,GAAG,MAAM,KAAK,GAAG,MAA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mappings":"AAAA,YAAY,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACnH,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { getAdapterBindings, ListenerCallbackType, ListenerOfAdapter } from '@hyper-fetch/sockets';
|
|
2
|
+
import { OrpcSerializerType } from '../adapter/adapter.utils';
|
|
3
|
+
import { OrpcIteratorEventType, OrpcSocketAdapterInstance, OrpcSubscriptionType } from './socket.types';
|
|
4
|
+
type BindingsType<Adapter extends OrpcSocketAdapterInstance> = ReturnType<typeof getAdapterBindings<Adapter>>;
|
|
5
|
+
/**
|
|
6
|
+
* Keeps one server subscription per procedure and input, shared by every listener with the same topic and payload.
|
|
7
|
+
* The adapter starts and stops the server side, this module counts the listeners, turns the events of the server
|
|
8
|
+
* iterator into listener messages and errors, and reports the lifecycle of the subscription to the listeners.
|
|
9
|
+
*
|
|
10
|
+
* - `start` is called for a subscription that has no running server side. It does nothing until the adapter can
|
|
11
|
+
* start it, the adapter starts the rest when it connects.
|
|
12
|
+
* - `stop` is called when the last listener of a running subscription unsubscribes - it cancels the server side.
|
|
13
|
+
* - `release` forgets the server side of a subscription the server ended, without telling the server.
|
|
14
|
+
*/
|
|
15
|
+
export declare const createOrpcSubscriptions: <Adapter extends OrpcSocketAdapterInstance, Transport>({ bindings, serializer, start, stop, release, }: {
|
|
16
|
+
bindings: Pick<BindingsType<Adapter>, "onListen" | "onEvent" | "onError" | "onListenerStart" | "onListenerEnd">;
|
|
17
|
+
serializer: OrpcSerializerType;
|
|
18
|
+
start: (subscription: OrpcSubscriptionType<Transport>) => void;
|
|
19
|
+
stop: (subscription: OrpcSubscriptionType<Transport>) => void;
|
|
20
|
+
release: (subscription: OrpcSubscriptionType<Transport>) => void;
|
|
21
|
+
}) => {
|
|
22
|
+
listen: (listener: ListenerOfAdapter<Adapter>, callback: ListenerCallbackType<Adapter, any>) => () => void;
|
|
23
|
+
receive: (subscription: OrpcSubscriptionType<Transport>, { event, data, meta }: OrpcIteratorEventType) => boolean;
|
|
24
|
+
report: (subscription: OrpcSubscriptionType<Transport>, cause: unknown) => void;
|
|
25
|
+
confirm: (subscription: OrpcSubscriptionType<Transport>) => void;
|
|
26
|
+
end: (subscription: OrpcSubscriptionType<Transport>, cause?: unknown) => void;
|
|
27
|
+
/** Every subscription with at least one listener */
|
|
28
|
+
values: () => OrpcSubscriptionType<Transport>[];
|
|
29
|
+
};
|
|
30
|
+
export {};
|
|
31
|
+
//# sourceMappingURL=socket.subscriptions.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"socket.subscriptions.d.ts","sourceRoot":"","sources":["../../src/socket/socket.subscriptions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,kBAAkB,EAClB,oBAAoB,EACpB,iBAAiB,EAClB,MAAM,sBAAsB,CAAC;AAG9B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAEnE,OAAO,KAAK,EACV,qBAAqB,EACrB,yBAAyB,EAEzB,oBAAoB,EACrB,MAAM,gBAAgB,CAAC;AAGxB,KAAK,YAAY,CAAC,OAAO,SAAS,yBAAyB,IAAI,UAAU,CAAC,OAAO,kBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC;AAE9G;;;;;;;;;GASG;AACH,eAAO,MAAM,uBAAuB,GAAI,OAAO,SAAS,yBAAyB,EAAE,SAAS,EAAE,iDAM3F;IACD,QAAQ,EAAE,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,EAAE,UAAU,GAAG,SAAS,GAAG,SAAS,GAAG,iBAAiB,GAAG,eAAe,CAAC,CAAC;IAChH,UAAU,EAAE,kBAAkB,CAAC;IAC/B,KAAK,EAAE,CAAC,YAAY,EAAE,oBAAoB,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC;IAC/D,IAAI,EAAE,CAAC,YAAY,EAAE,oBAAoB,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC;IAC9D,OAAO,EAAE,CAAC,YAAY,EAAE,oBAAoB,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC;CAClE;uBA0C2B,iBAAiB,CAAC,OAAO,CAAC,YAAY,oBAAoB,CAAC,OAAO,EAAE,GAAG,CAAC;4BA2CnE,oBAAoB,CAAC,SAAS,CAAC,yBAAyB,qBAAqB;2BArE9E,oBAAoB,CAAC,SAAS,CAAC,SAAS,OAAO;4BAK9C,oBAAoB,CAAC,SAAS,CAAC;wBASnC,oBAAoB,CAAC,SAAS,CAAC,UAAU,OAAO;IAsGzE,oDAAoD;;CAGvD,CAAC"}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { ListenerCallbackType, SocketAdapter } from '@hyper-fetch/sockets';
|
|
2
|
+
import { StandardRPCCustomJsonSerializer } from '@orpc/client/standard';
|
|
3
|
+
/**
|
|
4
|
+
* Meta of the event, passed to the listeners as `extra`.
|
|
5
|
+
* The server sets it with `withEventMeta(value, { id, retry })`.
|
|
6
|
+
*/
|
|
7
|
+
export type OrpcSocketExtraType = {
|
|
8
|
+
/** Id of the event. It is sent back as `last-event-id` when the subscription starts again, so the server can resume */
|
|
9
|
+
id: string | undefined;
|
|
10
|
+
/** Delay in milliseconds the server asks for before the subscription starts again after a failure */
|
|
11
|
+
retry: number | undefined;
|
|
12
|
+
};
|
|
13
|
+
/** Options of the `OrpcStreamAdapter` and `OrpcWebsocketAdapter` factories */
|
|
14
|
+
export type OrpcSocketAdapterConfigType = {
|
|
15
|
+
/**
|
|
16
|
+
* Serializers of custom types, the same as the `customJsonSerializers` option of `RPCHandler` and `RPCLink`.
|
|
17
|
+
* Both sides need the same list.
|
|
18
|
+
*/
|
|
19
|
+
customJsonSerializers?: StandardRPCCustomJsonSerializer[];
|
|
20
|
+
};
|
|
21
|
+
/** Any socket adapter of this package, the listeners receive the event meta as `extra` */
|
|
22
|
+
export type OrpcSocketAdapterInstance = SocketAdapter<OrpcSocketExtraType, any, any, any, any, any>;
|
|
23
|
+
/** An event of the server event iterator, with the data still in the serialized `{ json, meta }` form */
|
|
24
|
+
export type OrpcIteratorEventType = {
|
|
25
|
+
event: "message" | "error" | "done";
|
|
26
|
+
data: unknown;
|
|
27
|
+
meta: {
|
|
28
|
+
id?: unknown;
|
|
29
|
+
retry?: unknown;
|
|
30
|
+
} | undefined;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* One server subscription - the procedure called with one input. Every listener with the same topic and payload
|
|
34
|
+
* shares it. `transport` holds the adapter state of the running server side, it is empty when nothing runs.
|
|
35
|
+
* Once the server ends it, the subscription is gone - a later `listen()` creates a new one.
|
|
36
|
+
*/
|
|
37
|
+
export type OrpcSubscriptionType<Transport> = {
|
|
38
|
+
key: string;
|
|
39
|
+
topic: string;
|
|
40
|
+
payload: unknown;
|
|
41
|
+
callbacks: Set<ListenerCallbackType<any, any>>;
|
|
42
|
+
/** Id of the last event, sent as `last-event-id` when the subscription starts again */
|
|
43
|
+
lastEventId: string | undefined;
|
|
44
|
+
/** Retry delay of the last event */
|
|
45
|
+
lastEventRetry: number | undefined;
|
|
46
|
+
transport: Transport | undefined;
|
|
47
|
+
/** `true` once the server confirmed the running server side, reset when it starts again */
|
|
48
|
+
started: boolean;
|
|
49
|
+
};
|
|
50
|
+
/** Details of the subscription an `OrpcSocketError` belongs to */
|
|
51
|
+
export type OrpcSocketErrorOptionsType = {
|
|
52
|
+
/**
|
|
53
|
+
* What went wrong - the `ORPCError` the server sent, the `ErrorEvent` of an error event without the oRPC shape,
|
|
54
|
+
* or the error of the transport or the decoding.
|
|
55
|
+
*/
|
|
56
|
+
cause: unknown;
|
|
57
|
+
/** Topic of the failed subscription, `null` when the message can't be matched to a subscription */
|
|
58
|
+
topic: string | null;
|
|
59
|
+
/** Input of the failed subscription */
|
|
60
|
+
payload: unknown;
|
|
61
|
+
};
|
|
62
|
+
//# sourceMappingURL=socket.types.d.ts.map
|
|
@@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cAAc,EAAE,MAAM,GAAG,SAAS,CAAC;IACnC,SAAS,EAAE,SAAS,GAAG,SAAS,CAAC;IACjC,2FAA2F;IAC3F,OAAO,EAAE,OAAO,CAAC;CAClB,CAAC;AAEF,kEAAkE;AAClE,MAAM,MAAM,0BAA0B,GAAG;IACvC;;;OAGG;IACH,KAAK,EAAE,OAAO,CAAC;IACf,mGAAmG;IACnG,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,uCAAuC;IACvC,OAAO,EAAE,OAAO,CAAC;CAClB,CAAC"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { ORPCError } from '@orpc/client';
|
|
2
|
+
import { OrpcErrorType } from '../adapter/adapter.types';
|
|
3
|
+
import { OrpcSerializerType } from '../adapter/adapter.utils';
|
|
4
|
+
import { OrpcSocketErrorOptionsType } from './socket.types';
|
|
5
|
+
export declare const toError: (error: unknown) => Error;
|
|
6
|
+
export declare const isRecord: (value: unknown) => value is Record<string, unknown>;
|
|
7
|
+
/**
|
|
8
|
+
* Turns the serialized `{ json, meta }` data into the value. Anything else is not a part of the RPC protocol.
|
|
9
|
+
* It throws for malformed data, the same as the serializer of oRPC.
|
|
10
|
+
*/
|
|
11
|
+
export declare const deserializeOrpcData: (data: unknown, serializer: OrpcSerializerType) => unknown;
|
|
12
|
+
/**
|
|
13
|
+
* The error of a call the server rejected before the event iterator started, e.g. a failed input validation or
|
|
14
|
+
* middleware. The same as in the `RPCLink` of oRPC: an `ORPCError` from the body, or one named after the status
|
|
15
|
+
* when the body is not an oRPC error.
|
|
16
|
+
*/
|
|
17
|
+
export declare const getOrpcResponseError: ({ status, body, serializer, }: {
|
|
18
|
+
status: number;
|
|
19
|
+
body: unknown;
|
|
20
|
+
serializer: OrpcSerializerType;
|
|
21
|
+
}) => ORPCError<string, unknown>;
|
|
22
|
+
/** Reported when the procedure of a listener returns a regular output instead of an event iterator */
|
|
23
|
+
export declare const getNotIteratorError: (topic: string) => Error;
|
|
24
|
+
/**
|
|
25
|
+
* Error of an oRPC subscription, reported to the `socket.onError` callbacks. `topic` and `payload` tell which
|
|
26
|
+
* subscription failed. `shape` is the error the server sent, in the shape of `ORPCError.toJSON()` - it is `null` when
|
|
27
|
+
* the failure did not come from a procedure, e.g. a dropped stream or a malformed message. The original error is the
|
|
28
|
+
* `cause`.
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* socket.onError(({ error }) => {
|
|
32
|
+
* if (error instanceof OrpcSocketError && error.defined && error.code === "UNAUTHORIZED") {
|
|
33
|
+
* logout();
|
|
34
|
+
* }
|
|
35
|
+
* });
|
|
36
|
+
*/
|
|
37
|
+
export declare class OrpcSocketError<Code extends string = string, Data = unknown> extends Error {
|
|
38
|
+
/** Error sent by the server, `null` when the failure did not come from a procedure */
|
|
39
|
+
readonly shape: OrpcErrorType<Code, Data> | null;
|
|
40
|
+
/** Topic of the failed subscription, `null` when the message can't be matched to a subscription */
|
|
41
|
+
readonly topic: string | null;
|
|
42
|
+
/** Input of the failed subscription */
|
|
43
|
+
readonly payload: unknown;
|
|
44
|
+
/** The `ORPCError` sent by the server, or the error of the transport or the decoding */
|
|
45
|
+
readonly cause: unknown;
|
|
46
|
+
constructor({ cause, topic, payload }: OrpcSocketErrorOptionsType);
|
|
47
|
+
/** `true` for the errors from the `.errors()` map of the procedure */
|
|
48
|
+
get defined(): boolean;
|
|
49
|
+
/** Code of the server error, e.g. `"NOT_FOUND"` */
|
|
50
|
+
get code(): Code | undefined;
|
|
51
|
+
/** Status of the server error */
|
|
52
|
+
get status(): number | undefined;
|
|
53
|
+
/** Data of the server error */
|
|
54
|
+
get data(): Data | undefined;
|
|
55
|
+
}
|
|
56
|
+
//# sourceMappingURL=socket.utils.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"socket.utils.d.ts","sourceRoot":"","sources":["../../src/socket/socket.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4C,SAAS,EAAE,MAAM,cAAc,CAA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,CAErB;IAED,mDAAmD;IACnD,IAAI,IAAI,IAAI,IAAI,GAAG,SAAS,CAE3B;IAED,iCAAiC;IACjC,IAAI,MAAM,IAAI,MAAM,GAAG,SAAS,CAE/B;IAED,+BAA+B;IAC/B,IAAI,IAAI,IAAI,IAAI,GAAG,SAAS,CAE3B;CACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/stream-adapter/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAC;AACjC,cAAc,wBAAwB,CAAC"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { OrpcSocketAdapterConfigType } from '../socket/socket.types';
|
|
2
|
+
import { OrpcStreamAdapterType } from './stream-adapter.types';
|
|
3
|
+
/**
|
|
4
|
+
* Socket adapter for the event iterators of oRPC over HTTP. Every subscription is a call of the procedure with the
|
|
5
|
+
* RPC protocol - a `POST {url}/planet/onUpdate` with the serialized input - answered with a `text/event-stream`.
|
|
6
|
+
* The same protocol as the `RPCLink` of oRPC, so it works with the `RPCHandler` of `@orpc/server/fetch` or `/node`.
|
|
7
|
+
*
|
|
8
|
+
* There is no shared connection: "connected" means the adapter opens streams. `connect()` starts every
|
|
9
|
+
* subscription, `disconnect()` aborts them, `reconnect()` starts them again with the id of their last event.
|
|
10
|
+
* Listeners of the same procedure and input share one stream, the last one to unsubscribe aborts it.
|
|
11
|
+
* A subscription starts (`onStart`) when the server answers with the event stream, and ends (`onEnd`) when the
|
|
12
|
+
* iterator finishes, fails or the server rejects the call.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* const socket = new Socket({ url: "http://localhost:3000/rpc", adapter: OrpcStreamAdapter() });
|
|
16
|
+
* const sdk = createSocketSdk<typeof socket, OrpcSocketSchema<typeof router>>(socket, { camelCaseToKebabCase: false });
|
|
17
|
+
*
|
|
18
|
+
* sdk.planet.onUpdate.$listener.setPayload({ id: 1 }).listen(({ data, extra }) => console.log(data, extra.id));
|
|
19
|
+
*/
|
|
20
|
+
export declare const OrpcStreamAdapter: ({ customJsonSerializers, }?: OrpcSocketAdapterConfigType) => OrpcStreamAdapterType;
|
|
21
|
+
//# sourceMappingURL=stream-adapter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stream-adapter.d.ts","sourceRoot":"","sources":["../../src/stream-adapter/stream-adapter.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,2BAA2B,EAA6C,MAAM,wBAAwB,CAAC;AAErH,OAAO,KAAK,EAAgC,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAiBlG;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,iBAAiB,GAAI,6BAE/B,2BAAgC,KAAG,qBA6UrC,CAAC"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { QueryParamsType, stringifyQueryParams } from '@hyper-fetch/core';
|
|
2
|
+
import { SocketAdapter } from '@hyper-fetch/sockets';
|
|
3
|
+
import { OrpcSocketExtraType } from '../socket/socket.types';
|
|
4
|
+
/** Options of the `OrpcStreamAdapter`, set with the `adapterOptions` of the socket or per connection in `onConnect` */
|
|
5
|
+
export type OrpcStreamAdapterOptionsType = {
|
|
6
|
+
/**
|
|
7
|
+
* Connects when the socket is created. Without it, call `socket.connect()`.
|
|
8
|
+
* @default true
|
|
9
|
+
*/
|
|
10
|
+
autoConnect?: boolean;
|
|
11
|
+
/** Headers of every stream request, e.g. the `authorization` header */
|
|
12
|
+
headers?: Record<string, string>;
|
|
13
|
+
/**
|
|
14
|
+
* The `fetch` used for the streams, e.g. one with a proxy agent or a mock in tests. Defaults to the global `fetch`
|
|
15
|
+
* of browsers, Node.js 18+, Bun and Deno.
|
|
16
|
+
*/
|
|
17
|
+
fetch?: typeof fetch;
|
|
18
|
+
/** Options passed to `fetch`, e.g. `credentials: "include"` for cookies on another origin */
|
|
19
|
+
fetchOptions?: Omit<RequestInit, "method" | "headers" | "body" | "signal">;
|
|
20
|
+
};
|
|
21
|
+
export type OrpcStreamAdapterType = SocketAdapter<OrpcSocketExtraType, OrpcStreamAdapterOptionsType, undefined, undefined, QueryParamsType | string, typeof stringifyQueryParams>;
|
|
22
|
+
//# sourceMappingURL=stream-adapter.types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stream-adapter.types.d.ts","sourceRoot":"","sources":["../../src/stream-adapter/stream-adapter.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAC/E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAE1D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAElE,uHAAuH;AACvH,MAAM,MAAM,4BAA4B,GAAG;IACzC;;;OAGG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,uEAAuE;IACvE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IACrB,6FAA6F;IAC7F,YAAY,CAAC,EAAE,IAAI,CAAC,WAAW,EAAE,QAAQ,GAAG,SAAS,GAAG,MAAM,GAAG,QAAQ,CAAC,CAAC;CAC5E,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG,aAAa,CAC/C,mBAAmB,EACnB,4BAA4B,EAC5B,SAAS,EACT,SAAS,EACT,eAAe,GAAG,MAAM,EACxB,OAAO,oBAAoB,CAC5B,CAAC"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { OrpcIteratorEventType } from '../socket/socket.types';
|
|
2
|
+
/** One message of a `text/event-stream`, the fields of the Server-Sent Events format */
|
|
3
|
+
export type OrpcEventStreamMessageType = {
|
|
4
|
+
event: string | undefined;
|
|
5
|
+
data: string | undefined;
|
|
6
|
+
id: string | undefined;
|
|
7
|
+
retry: number | undefined;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Splits the text of a `text/event-stream` into messages, the same as the `EventDecoder` of oRPC. Chunks can end
|
|
11
|
+
* anywhere, the text after the last complete message waits for the next chunk.
|
|
12
|
+
*/
|
|
13
|
+
export declare const createEventStreamDecoder: (onMessage: (message: OrpcEventStreamMessageType) => void) => {
|
|
14
|
+
feed: (chunk: string) => void;
|
|
15
|
+
end: () => void;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Maps a message to the event of the server iterator, the same as `toEventIterator` of oRPC. Messages without an
|
|
19
|
+
* event and data are keep-alive pings and return `null`. Throws when the data is not JSON.
|
|
20
|
+
*/
|
|
21
|
+
export declare const getEventStreamIteratorEvent: (message: OrpcEventStreamMessageType) => OrpcIteratorEventType | null;
|
|
22
|
+
//# sourceMappingURL=stream-adapter.utils.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stream-adapter.utils.d.ts","sourceRoot":"","sources":["../../src/stream-adapter/stream-adapter.utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAEpE,wFAAwF;AACxF,MAAM,MAAM,0BAA0B,GAAG;IACvC,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1B,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,EAAE,EAAE,MAAM,GAAG,SAAS,CAAC;IACvB,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;CAC3B,CAAC;AAmCF;;;GAGG;AACH,eAAO,MAAM,wBAAwB,GAAI,WAAW,CAAC,OAAO,EAAE,0BAA0B,KAAK,IAAI;kBAK1E,MAAM;;CA4B5B,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,2BAA2B,GAAI,SAAS,0BAA0B,KAAG,qBAAqB,GAAG,IAWzG,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/websocket-adapter/index.ts"],"names":[],"mappings":"AAAA,cAAc,qBAAqB,CAAC;AACpC,cAAc,2BAA2B,CAAC"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { OrpcSocketAdapterConfigType } from '../socket/socket.types';
|
|
2
|
+
import { OrpcWebsocketAdapterType } from './websocket-adapter.types';
|
|
3
|
+
/**
|
|
4
|
+
* Socket adapter for the event iterators of oRPC over one WebSocket connection. It speaks the protocol of the
|
|
5
|
+
* `RPCHandler` of `@orpc/server/ws` (the same as `@orpc/client/websocket`): every subscription is a request on the
|
|
6
|
+
* shared connection, and its events arrive as messages of that request.
|
|
7
|
+
*
|
|
8
|
+
* The adapter only subscribes. Emitting, and calling regular procedures, is not supported - use `OrpcAdapter` for
|
|
9
|
+
* them. Listeners of the same procedure and input share one request, the last one to unsubscribe aborts it.
|
|
10
|
+
* After a reconnect every running subscription starts again with the id of its last event. A subscription starts
|
|
11
|
+
* (`onStart`) when the server answers with the event iterator, and ends (`onEnd`) when the iterator finishes, fails
|
|
12
|
+
* or the server rejects the call.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* const socket = new Socket({ url: "ws://localhost:3000", adapter: OrpcWebsocketAdapter() });
|
|
16
|
+
* const sdk = createSocketSdk<typeof socket, OrpcSocketSchema<typeof router>>(socket, { camelCaseToKebabCase: false });
|
|
17
|
+
*
|
|
18
|
+
* sdk.planet.onUpdate.$listener.setPayload({ id: 1 }).listen(({ data }) => console.log(data));
|
|
19
|
+
*/
|
|
20
|
+
export declare const OrpcWebsocketAdapter: ({ customJsonSerializers, }?: OrpcSocketAdapterConfigType) => OrpcWebsocketAdapterType;
|
|
21
|
+
//# sourceMappingURL=websocket-adapter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"websocket-adapter.d.ts","sourceRoot":"","sources":["../../src/websocket-adapter/websocket-adapter.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,2BAA2B,EAA6C,MAAM,wBAAwB,CAAC;AAErH,OAAO,KAAK,EAAmC,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAc3G;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,oBAAoB,GAAI,6BAElC,2BAAgC,KAAG,wBA+WrC,CAAC"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { QueryParamsType, stringifyQueryParams } from '@hyper-fetch/core';
|
|
2
|
+
import { SocketAdapter } from '@hyper-fetch/sockets';
|
|
3
|
+
import { OrpcSocketExtraType } from '../socket/socket.types';
|
|
4
|
+
/** Options of the `OrpcWebsocketAdapter`, set with the `adapterOptions` of the socket or per connection in `onConnect` */
|
|
5
|
+
export type OrpcWebsocketAdapterOptionsType = {
|
|
6
|
+
/**
|
|
7
|
+
* Connects when the socket is created. Without it, call `socket.connect()`.
|
|
8
|
+
* @default true
|
|
9
|
+
*/
|
|
10
|
+
autoConnect?: boolean;
|
|
11
|
+
/**
|
|
12
|
+
* The WebSocket constructor, e.g. from the `ws` package. Defaults to the global `WebSocket` of browsers,
|
|
13
|
+
* Node.js 22+, Bun and Deno. Pass it in runtimes without the global.
|
|
14
|
+
*/
|
|
15
|
+
WebSocket?: typeof WebSocket;
|
|
16
|
+
/** Subprotocols passed to the `WebSocket` constructor (`Sec-WebSocket-Protocol` header) */
|
|
17
|
+
protocols?: string | string[];
|
|
18
|
+
/** Headers of every subscription request, the procedures read them the same as the headers of HTTP requests */
|
|
19
|
+
headers?: Record<string, string>;
|
|
20
|
+
};
|
|
21
|
+
export type OrpcWebsocketAdapterType = SocketAdapter<OrpcSocketExtraType, OrpcWebsocketAdapterOptionsType, undefined, undefined, QueryParamsType | string, typeof stringifyQueryParams>;
|
|
22
|
+
//# sourceMappingURL=websocket-adapter.types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"websocket-adapter.types.d.ts","sourceRoot":"","sources":["../../src/websocket-adapter/websocket-adapter.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAC/E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAE1D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAElE,0HAA0H;AAC1H,MAAM,MAAM,+BAA+B,GAAG;IAC5C;;;OAGG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,SAAS,CAAC;IAC7B,2FAA2F;IAC3F,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAC9B,+GAA+G;IAC/G,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC,CAAC;AAEF,MAAM,MAAM,wBAAwB,GAAG,aAAa,CAClD,mBAAmB,EACnB,+BAA+B,EAC/B,SAAS,EACT,SAAS,EACT,eAAe,GAAG,MAAM,EACxB,OAAO,oBAAoB,CAC5B,CAAC"}
|