@hyper-fetch/orpc 9.9.0 → 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.
Files changed (70) hide show
  1. package/README.md +35 -1
  2. package/__tests__/e2e/e2e.orpc-realtime-server.ts +181 -0
  3. package/__tests__/e2e/e2e.react-realtime.spec.tsx +181 -0
  4. package/__tests__/e2e/e2e.realtime.spec.ts +310 -0
  5. package/__tests__/features/socket/socket.schema.spec.ts +179 -0
  6. package/__tests__/features/stream-adapter/stream-adapter.environment.spec.ts +163 -0
  7. package/__tests__/features/stream-adapter/stream-adapter.lifecycle.spec.ts +509 -0
  8. package/__tests__/features/stream-adapter/stream-adapter.listener-lifecycle.spec.ts +291 -0
  9. package/__tests__/features/stream-adapter/stream-adapter.protocol.spec.ts +609 -0
  10. package/__tests__/features/stream-adapter/stream-adapter.subscriptions.spec.ts +270 -0
  11. package/__tests__/features/websocket-adapter/websocket-adapter.environment.spec.ts +147 -0
  12. package/__tests__/features/websocket-adapter/websocket-adapter.handshake-error.spec.ts +77 -0
  13. package/__tests__/features/websocket-adapter/websocket-adapter.lifecycle.spec.ts +326 -0
  14. package/__tests__/features/websocket-adapter/websocket-adapter.listener-lifecycle.spec.ts +222 -0
  15. package/__tests__/features/websocket-adapter/websocket-adapter.protocol.spec.ts +415 -0
  16. package/__tests__/features/websocket-adapter/websocket-adapter.subscriptions.spec.ts +172 -0
  17. package/__tests__/utils/controlled-fetch.ts +160 -0
  18. package/__tests__/utils/controlled-websocket.ts +140 -0
  19. package/__tests__/utils/socket-error.ts +7 -0
  20. package/__tests__/utils/stream-socket.ts +54 -0
  21. package/__tests__/utils/websocket-socket.ts +45 -0
  22. package/__tests__/vitest.setup.ts +20 -0
  23. package/dist/adapter/adapter.schema.d.ts +32 -0
  24. package/dist/adapter/adapter.schema.d.ts.map +1 -1
  25. package/dist/adapter/adapter.utils.d.ts +22 -4
  26. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  27. package/dist/index.d.ts +3 -0
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.mjs +932 -11
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/socket/index.d.ts +3 -0
  32. package/dist/socket/index.d.ts.map +1 -0
  33. package/dist/socket/socket.subscriptions.d.ts +31 -0
  34. package/dist/socket/socket.subscriptions.d.ts.map +1 -0
  35. package/dist/socket/socket.types.d.ts +62 -0
  36. package/dist/socket/socket.types.d.ts.map +1 -0
  37. package/dist/socket/socket.utils.d.ts +56 -0
  38. package/dist/socket/socket.utils.d.ts.map +1 -0
  39. package/dist/stream-adapter/index.d.ts +3 -0
  40. package/dist/stream-adapter/index.d.ts.map +1 -0
  41. package/dist/stream-adapter/stream-adapter.d.ts +21 -0
  42. package/dist/stream-adapter/stream-adapter.d.ts.map +1 -0
  43. package/dist/stream-adapter/stream-adapter.types.d.ts +22 -0
  44. package/dist/stream-adapter/stream-adapter.types.d.ts.map +1 -0
  45. package/dist/stream-adapter/stream-adapter.utils.d.ts +22 -0
  46. package/dist/stream-adapter/stream-adapter.utils.d.ts.map +1 -0
  47. package/dist/websocket-adapter/index.d.ts +3 -0
  48. package/dist/websocket-adapter/index.d.ts.map +1 -0
  49. package/dist/websocket-adapter/websocket-adapter.d.ts +21 -0
  50. package/dist/websocket-adapter/websocket-adapter.d.ts.map +1 -0
  51. package/dist/websocket-adapter/websocket-adapter.types.d.ts +22 -0
  52. package/dist/websocket-adapter/websocket-adapter.types.d.ts.map +1 -0
  53. package/dist/websocket-adapter/websocket-adapter.utils.d.ts +35 -0
  54. package/dist/websocket-adapter/websocket-adapter.utils.d.ts.map +1 -0
  55. package/package.json +3 -1
  56. package/src/adapter/adapter.schema.ts +57 -0
  57. package/src/adapter/adapter.utils.ts +40 -10
  58. package/src/index.ts +3 -0
  59. package/src/socket/index.ts +2 -0
  60. package/src/socket/socket.subscriptions.ts +178 -0
  61. package/src/socket/socket.types.ts +64 -0
  62. package/src/socket/socket.utils.ts +110 -0
  63. package/src/stream-adapter/index.ts +2 -0
  64. package/src/stream-adapter/stream-adapter.ts +381 -0
  65. package/src/stream-adapter/stream-adapter.types.ts +31 -0
  66. package/src/stream-adapter/stream-adapter.utils.ts +98 -0
  67. package/src/websocket-adapter/index.ts +2 -0
  68. package/src/websocket-adapter/websocket-adapter.ts +417 -0
  69. package/src/websocket-adapter/websocket-adapter.types.ts +31 -0
  70. package/src/websocket-adapter/websocket-adapter.utils.ts +119 -0
@@ -0,0 +1,417 @@
1
+ /* eslint-disable @typescript-eslint/no-use-before-define */
2
+ import type { QueryParamsType } from "@hyper-fetch/core";
3
+ import { stringifyQueryParams } from "@hyper-fetch/core";
4
+ import {
5
+ getSocketError,
6
+ getSocketUrl,
7
+ getWebsocketConstructor,
8
+ SocketAdapter,
9
+ WebsocketReadyState,
10
+ } from "@hyper-fetch/sockets";
11
+ import { isORPCErrorStatus } from "@orpc/client";
12
+
13
+ import { createOrpcSerializer } from "../adapter/adapter.utils";
14
+ import { createOrpcSubscriptions } from "../socket/socket.subscriptions";
15
+ import type { OrpcSocketAdapterConfigType, OrpcSocketExtraType, OrpcSubscriptionType } from "../socket/socket.types";
16
+ import { getNotIteratorError, getOrpcResponseError, OrpcSocketError, toError } from "../socket/socket.utils";
17
+ import type { OrpcWebsocketAdapterOptionsType, OrpcWebsocketAdapterType } from "./websocket-adapter.types";
18
+ import type { OrpcPeerResponseMessageType } from "./websocket-adapter.utils";
19
+ import {
20
+ decodeOrpcResponseMessage,
21
+ encodeOrpcAbortMessage,
22
+ encodeOrpcRequestMessage,
23
+ isOrpcEventIteratorResponse,
24
+ } from "./websocket-adapter.utils";
25
+
26
+ /** Server side of one subscription - its request on the connection */
27
+ type WebsocketTransportType = { id: string; websocket: WebSocket };
28
+
29
+ type WebsocketSubscriptionType = OrpcSubscriptionType<WebsocketTransportType>;
30
+
31
+ /**
32
+ * Socket adapter for the event iterators of oRPC over one WebSocket connection. It speaks the protocol of the
33
+ * `RPCHandler` of `@orpc/server/ws` (the same as `@orpc/client/websocket`): every subscription is a request on the
34
+ * shared connection, and its events arrive as messages of that request.
35
+ *
36
+ * The adapter only subscribes. Emitting, and calling regular procedures, is not supported - use `OrpcAdapter` for
37
+ * them. Listeners of the same procedure and input share one request, the last one to unsubscribe aborts it.
38
+ * After a reconnect every running subscription starts again with the id of its last event. A subscription starts
39
+ * (`onStart`) when the server answers with the event iterator, and ends (`onEnd`) when the iterator finishes, fails
40
+ * or the server rejects the call.
41
+ *
42
+ * @example
43
+ * const socket = new Socket({ url: "ws://localhost:3000", adapter: OrpcWebsocketAdapter() });
44
+ * const sdk = createSocketSdk<typeof socket, OrpcSocketSchema<typeof router>>(socket, { camelCaseToKebabCase: false });
45
+ *
46
+ * sdk.planet.onUpdate.$listener.setPayload({ id: 1 }).listen(({ data }) => console.log(data));
47
+ */
48
+ export const OrpcWebsocketAdapter = ({
49
+ customJsonSerializers,
50
+ }: OrpcSocketAdapterConfigType = {}): OrpcWebsocketAdapterType => {
51
+ const serializer = createOrpcSerializer(customJsonSerializers);
52
+
53
+ return new SocketAdapter<
54
+ OrpcSocketExtraType,
55
+ OrpcWebsocketAdapterOptionsType,
56
+ undefined,
57
+ undefined,
58
+ QueryParamsType | string,
59
+ typeof stringifyQueryParams
60
+ >({ name: "orpc-websocket", confirmsSubscriptions: true })
61
+ .setQueryParamsMapper(stringifyQueryParams)
62
+ .setConnector((bindings) => {
63
+ const {
64
+ socket,
65
+ adapter,
66
+ getQueryParams,
67
+ onConnect,
68
+ onConnectFailed,
69
+ onReconnect,
70
+ onDisconnect,
71
+ onConnected,
72
+ onDisconnected,
73
+ onError,
74
+ } = bindings;
75
+
76
+ const autoConnect = adapter.adapterOptions?.autoConnect ?? true;
77
+
78
+ // The transport in use. Events of any other instance (replaced or closed on purpose) are ignored.
79
+ let websocket: WebSocket | undefined;
80
+ // Options of the current connection (after onConnect interceptors)
81
+ let options: OrpcWebsocketAdapterOptionsType | undefined;
82
+ // Connection attempt in progress - concurrent `connect()` calls join it
83
+ let pendingConnection: Promise<boolean> | undefined;
84
+ // Connection timeout while connecting, reconnection delay after the connection was lost
85
+ let timeout: ReturnType<typeof setTimeout> | undefined;
86
+ // Request ids are never reused, so a late message of a stopped request can't reach a new one
87
+ let lastRequestId = 0;
88
+ // Running requests of the current connection
89
+ const requests = new Map<string, WebsocketSubscriptionType>();
90
+
91
+ const subscriptions = createOrpcSubscriptions<OrpcWebsocketAdapterType, WebsocketTransportType>({
92
+ bindings,
93
+ serializer,
94
+ start: (subscription) => startSubscription(subscription),
95
+ stop: (subscription) => stopSubscription(subscription),
96
+ release: (subscription) => {
97
+ releaseSubscription(subscription);
98
+ },
99
+ });
100
+
101
+ /** Sends a frame of the subscription, reporting the failure instead of throwing */
102
+ const sendFrame = (subscription: WebsocketSubscriptionType, target: WebSocket, frame: string): boolean => {
103
+ try {
104
+ target.send(frame);
105
+ return true;
106
+ } catch (error) {
107
+ subscriptions.report(subscription, error);
108
+ return false;
109
+ }
110
+ };
111
+
112
+ const startSubscription = (subscription: WebsocketSubscriptionType) => {
113
+ // Not connected - the subscription starts on connect
114
+ const current = websocket;
115
+ if (!current || !adapter.connected) {
116
+ return;
117
+ }
118
+
119
+ lastRequestId += 1;
120
+ const id = lastRequestId.toString(36);
121
+ const { lastEventId } = subscription;
122
+ // The server reads it as `lastEventId` and can resume where the previous connection stopped
123
+ const headers =
124
+ lastEventId === undefined ? { ...options?.headers } : { ...options?.headers, "last-event-id": lastEventId };
125
+
126
+ let frame: string;
127
+ try {
128
+ frame = encodeOrpcRequestMessage({
129
+ id,
130
+ topic: subscription.topic,
131
+ payload: subscription.payload,
132
+ headers,
133
+ serializer,
134
+ });
135
+ } catch (error) {
136
+ // An input that can't be encoded never will be, so the subscription is over
137
+ subscriptions.end(subscription, error);
138
+ return;
139
+ }
140
+
141
+ if (sendFrame(subscription, current, frame)) {
142
+ subscription.transport = { id, websocket: current };
143
+ requests.set(id, subscription);
144
+ }
145
+ };
146
+
147
+ /** Forgets the request of the subscription. Messages that still come for it are ignored. */
148
+ const releaseSubscription = (subscription: WebsocketSubscriptionType) => {
149
+ const { transport } = subscription;
150
+ subscription.transport = undefined;
151
+ subscription.started = false;
152
+ if (transport) {
153
+ requests.delete(transport.id);
154
+ }
155
+ return transport;
156
+ };
157
+
158
+ const stopSubscription = (subscription: WebsocketSubscriptionType) => {
159
+ const transport = releaseSubscription(subscription);
160
+ if (transport) {
161
+ sendFrame(subscription, transport.websocket, encodeOrpcAbortMessage(transport.id));
162
+ }
163
+ };
164
+
165
+ /** The connection is gone and the server dropped every request with it */
166
+ const releaseAll = () => {
167
+ requests.forEach((subscription) => {
168
+ subscription.transport = undefined;
169
+ subscription.started = false;
170
+ });
171
+ requests.clear();
172
+ };
173
+
174
+ const handleResponse = (
175
+ subscription: WebsocketSubscriptionType,
176
+ { status, headers, body }: Extract<OrpcPeerResponseMessageType, { type: "response" }>,
177
+ ) => {
178
+ // The server rejected the call before the iterator started, e.g. a failed input validation
179
+ if (isORPCErrorStatus(status)) {
180
+ subscriptions.end(subscription, getOrpcResponseError({ status, body, serializer }));
181
+ return;
182
+ }
183
+ if (!isOrpcEventIteratorResponse(headers)) {
184
+ subscriptions.end(subscription, getNotIteratorError(subscription.topic));
185
+ return;
186
+ }
187
+ // The response of an event iterator - the subscription runs
188
+ subscriptions.confirm(subscription);
189
+ };
190
+
191
+ const handleMessage = (frame: unknown) => {
192
+ let message: OrpcPeerResponseMessageType;
193
+ try {
194
+ message = decodeOrpcResponseMessage(frame);
195
+ } catch (error) {
196
+ // A frame that can't be read can't be matched to its subscription either
197
+ onError({ error: new OrpcSocketError({ cause: error, topic: null, payload: undefined }) });
198
+ return;
199
+ }
200
+
201
+ // Late messages of stopped requests, and the abort the server sends for iterators in the input, are ignored
202
+ const subscription = requests.get(message.id);
203
+ if (!subscription || message.type === "abort") {
204
+ return;
205
+ }
206
+
207
+ if (message.type === "response") {
208
+ handleResponse(subscription, message);
209
+ return;
210
+ }
211
+ // `done` and `error` end the subscription there
212
+ subscriptions.receive(subscription, message.event);
213
+ };
214
+
215
+ /** Starts over after `delay` - the connection timeout while connecting, the reconnect delay after a loss */
216
+ const scheduleReconnect = (delay = socket.reconnectTime) => {
217
+ clearTimeout(timeout);
218
+ timeout = setTimeout(() => {
219
+ reconnect();
220
+ }, delay);
221
+ };
222
+
223
+ const openConnection = async (): Promise<boolean> => {
224
+ const connection = await onConnect();
225
+ if (!connection) {
226
+ return adapter.connected;
227
+ }
228
+
229
+ clearTimeout(timeout);
230
+ options = connection.adapterOptions;
231
+ const url = getSocketUrl(connection.url, getQueryParams(connection.queryParams));
232
+
233
+ const WebSocketConstructor = getWebsocketConstructor(options);
234
+ if (!WebSocketConstructor) {
235
+ onConnectFailed({ error: new Error("WebSocket is not available in this environment") });
236
+ return false;
237
+ }
238
+
239
+ let instance: WebSocket;
240
+ try {
241
+ instance = new WebSocketConstructor(url, options?.protocols);
242
+ } catch (error) {
243
+ onConnectFailed({ error: toError(error) });
244
+ return false;
245
+ }
246
+ // Binary frames are read synchronously, so messages keep their order
247
+ instance.binaryType = "arraybuffer";
248
+ websocket = instance;
249
+ const isCurrent = () => websocket === instance;
250
+
251
+ // Connection timeout - when the server does not answer in time, start over
252
+ scheduleReconnect(socket.connectionTimeout);
253
+
254
+ return new Promise<boolean>((resolve) => {
255
+ // A closed instance never opens, so the open event always belongs to the current one
256
+ instance.addEventListener("open", () => {
257
+ clearTimeout(timeout);
258
+ onConnected();
259
+ [...subscriptions.values()].forEach((subscription) => {
260
+ // A listener added by an `onConnected` callback is running already
261
+ if (!subscription.transport) {
262
+ startSubscription(subscription);
263
+ }
264
+ });
265
+ resolve(true);
266
+ });
267
+
268
+ /** The transport is gone - report it and get the connection back unless it was closed normally */
269
+ const onTransportClosed = (event: Pick<CloseEvent, "code"> & Event) => {
270
+ websocket = undefined;
271
+ clearTimeout(timeout);
272
+ releaseAll();
273
+ onDisconnected();
274
+ onError({ error: new Error(getSocketError(event)) });
275
+
276
+ // The connection was lost or closed by the server with an error - try to get it back
277
+ if (event.code !== 1000) {
278
+ scheduleReconnect();
279
+ }
280
+ };
281
+
282
+ instance.addEventListener("close", (event) => {
283
+ resolve(false);
284
+ if (!isCurrent()) {
285
+ return;
286
+ }
287
+ onTransportClosed(event);
288
+ });
289
+
290
+ // Node.js 22 reports a failed handshake with `error` only - no `close` follows and the transport stays
291
+ // CONNECTING. Browsers set CLOSED before the error and send the close event, which handles it as usual.
292
+ // Here the transport is detached and treated as an abnormally closed one (1006).
293
+ instance.addEventListener("error", () => {
294
+ if (!isCurrent() || instance.readyState !== WebsocketReadyState.CONNECTING) {
295
+ return;
296
+ }
297
+ resolve(false);
298
+ try {
299
+ instance.close();
300
+ } catch {
301
+ // Closing a transport that never connected may throw in some runtimes - it is detached already
302
+ }
303
+ onTransportClosed(Object.assign(new Event("close"), { code: 1006 }));
304
+ });
305
+
306
+ instance.addEventListener("message", (event) => {
307
+ if (isCurrent()) {
308
+ handleMessage(event.data);
309
+ }
310
+ });
311
+ });
312
+ };
313
+
314
+ const connect = (): Promise<boolean> => {
315
+ // Another attempt is already on its way (e.g. the automatic one) - resolve together with it
316
+ if (adapter.connecting && pendingConnection) {
317
+ return pendingConnection;
318
+ }
319
+
320
+ const attempt = openConnection();
321
+ pendingConnection = attempt;
322
+ const release = () => {
323
+ if (pendingConnection === attempt) {
324
+ pendingConnection = undefined;
325
+ }
326
+ };
327
+ attempt.then(release, release);
328
+
329
+ return attempt;
330
+ };
331
+
332
+ /**
333
+ * Closes the transport and resets the connection state. The server cancels every subscription of the
334
+ * connection, the listeners stay registered and keep the id of their last event for the next connection.
335
+ */
336
+ const closeConnection = async ({ manual }: { manual: boolean }): Promise<boolean> => {
337
+ clearTimeout(timeout);
338
+
339
+ const current = websocket;
340
+ websocket = undefined;
341
+ releaseAll();
342
+
343
+ const wasActive = adapter.connected || adapter.connecting;
344
+ onDisconnect();
345
+ if (!manual) {
346
+ // Closing the previous transport is a part of reconnecting - only `disconnect()` keeps the socket closed
347
+ adapter.setForceClosed(false);
348
+ }
349
+ if (wasActive) {
350
+ onDisconnected();
351
+ }
352
+
353
+ if (!current) {
354
+ return true;
355
+ }
356
+ return new Promise<boolean>((resolve) => {
357
+ current.addEventListener("close", () => resolve(true), { once: true });
358
+ // A transport that fails while closing may report only `error` (Node.js 22) - don't wait for a close
359
+ current.addEventListener("error", () => resolve(true), { once: true });
360
+ current.close(1000);
361
+ });
362
+ };
363
+
364
+ /** Manual disconnect - the socket stays closed until `connect()` or `reconnect()` is called */
365
+ const disconnect = (): Promise<boolean> => {
366
+ return closeConnection({ manual: true });
367
+ };
368
+
369
+ const reconnect = async () => {
370
+ // Reconnecting is a request to be connected, also after a manual disconnect
371
+ adapter.setForceClosed(false);
372
+
373
+ await onReconnect({
374
+ disconnect: () => closeConnection({ manual: false }),
375
+ connect: async () => {
376
+ // `disconnect()` called while the previous transport was closing wins over the reconnection
377
+ if (adapter.forceClosed) {
378
+ adapter.setReconnectionAttempts(0);
379
+ return false;
380
+ }
381
+ return connect();
382
+ },
383
+ });
384
+ };
385
+
386
+ // Throwing synchronously makes `emitter.emit()` fail right at the call site, the same as in the
387
+ // Server-Sent Events adapter
388
+ const emit = () => {
389
+ throw new Error("Cannot emit events in the oRPC WebSocket adapter, it only receives events of subscriptions");
390
+ };
391
+
392
+ // Initialize
393
+ if (autoConnect) {
394
+ connect();
395
+ }
396
+
397
+ const unmountOnline = socket.appManager.events.onOnline(() => {
398
+ // A socket disconnected on purpose stays closed until `connect()` or `reconnect()` is called
399
+ if (autoConnect && !adapter.connected && !adapter.forceClosed) {
400
+ connect();
401
+ }
402
+ });
403
+
404
+ return {
405
+ connect,
406
+ reconnect,
407
+ disconnect,
408
+ listen: subscriptions.listen,
409
+ emit,
410
+ // Nothing of this connector outlives the socket - no online subscription, no pending reconnect
411
+ dispose: () => {
412
+ unmountOnline();
413
+ clearTimeout(timeout);
414
+ },
415
+ };
416
+ });
417
+ };
@@ -0,0 +1,31 @@
1
+ import type { QueryParamsType, stringifyQueryParams } from "@hyper-fetch/core";
2
+ import type { SocketAdapter } from "@hyper-fetch/sockets";
3
+
4
+ import type { OrpcSocketExtraType } from "../socket/socket.types";
5
+
6
+ /** Options of the `OrpcWebsocketAdapter`, set with the `adapterOptions` of the socket or per connection in `onConnect` */
7
+ export type OrpcWebsocketAdapterOptionsType = {
8
+ /**
9
+ * Connects when the socket is created. Without it, call `socket.connect()`.
10
+ * @default true
11
+ */
12
+ autoConnect?: boolean;
13
+ /**
14
+ * The WebSocket constructor, e.g. from the `ws` package. Defaults to the global `WebSocket` of browsers,
15
+ * Node.js 22+, Bun and Deno. Pass it in runtimes without the global.
16
+ */
17
+ WebSocket?: typeof WebSocket;
18
+ /** Subprotocols passed to the `WebSocket` constructor (`Sec-WebSocket-Protocol` header) */
19
+ protocols?: string | string[];
20
+ /** Headers of every subscription request, the procedures read them the same as the headers of HTTP requests */
21
+ headers?: Record<string, string>;
22
+ };
23
+
24
+ export type OrpcWebsocketAdapterType = SocketAdapter<
25
+ OrpcSocketExtraType,
26
+ OrpcWebsocketAdapterOptionsType,
27
+ undefined,
28
+ undefined,
29
+ QueryParamsType | string,
30
+ typeof stringifyQueryParams
31
+ >;
@@ -0,0 +1,119 @@
1
+ import type { OrpcSerializerType } from "../adapter/adapter.utils";
2
+ import { orpcEndpointMapper } from "../adapter/adapter.utils";
3
+ import type { OrpcIteratorEventType } from "../socket/socket.types";
4
+ import { isRecord } from "../socket/socket.utils";
5
+
6
+ /** Message types of the oRPC peer protocol, used by `@orpc/server/ws` and `@orpc/client/websocket` */
7
+ const peerMessageType = {
8
+ REQUEST: 1,
9
+ RESPONSE: 2,
10
+ EVENT_ITERATOR: 3,
11
+ ABORT_SIGNAL: 4,
12
+ } as const;
13
+
14
+ /** JSON and binary parts of a binary frame are split by this byte */
15
+ const binaryDelimiter = 255;
16
+
17
+ /** A message the server sends for one request */
18
+ export type OrpcPeerResponseMessageType =
19
+ | { id: string; type: "response"; status: number; headers: Record<string, unknown>; body: unknown }
20
+ | { id: string; type: "event"; event: OrpcIteratorEventType }
21
+ | { id: string; type: "abort" };
22
+
23
+ const getMalformedError = (detail: string) => new TypeError(`Invalid oRPC message: ${detail}`);
24
+
25
+ /**
26
+ * Starts the call of the procedure - the same request message as the `RPCLink` of `@orpc/client/websocket`.
27
+ * The input is serialized with the RPC serializer, inputs with files are not supported.
28
+ */
29
+ export const encodeOrpcRequestMessage = ({
30
+ id,
31
+ topic,
32
+ payload,
33
+ headers,
34
+ serializer,
35
+ }: {
36
+ id: string;
37
+ topic: string;
38
+ payload: unknown;
39
+ headers: Record<string, string>;
40
+ serializer: OrpcSerializerType;
41
+ }): string => {
42
+ const body = serializer.serialize(payload);
43
+ if (body instanceof FormData) {
44
+ throw new TypeError(`Files in the input of "${topic}" are not supported by the oRPC WebSocket adapter`);
45
+ }
46
+
47
+ // The `POST` method is the default of the protocol, so it is not sent
48
+ return JSON.stringify({
49
+ i: id,
50
+ p: { u: orpcEndpointMapper(topic), b: body, h: Object.keys(headers).length > 0 ? headers : undefined },
51
+ });
52
+ };
53
+
54
+ /** Stops the call of the procedure, the server cancels its iterator */
55
+ export const encodeOrpcAbortMessage = (id: string): string => {
56
+ return JSON.stringify({ i: id, t: peerMessageType.ABORT_SIGNAL });
57
+ };
58
+
59
+ const readFrameText = (frame: unknown): string => {
60
+ if (typeof frame === "string") {
61
+ return frame;
62
+ }
63
+ if (frame instanceof ArrayBuffer || ArrayBuffer.isView(frame)) {
64
+ const bytes =
65
+ frame instanceof ArrayBuffer
66
+ ? new Uint8Array(frame)
67
+ : new Uint8Array(frame.buffer, frame.byteOffset, frame.byteLength);
68
+ // Binary frames carry a file after the delimiter, event iterators never send files
69
+ const end = bytes.indexOf(binaryDelimiter);
70
+ return new TextDecoder().decode(end === -1 ? bytes : bytes.subarray(0, end));
71
+ }
72
+ throw getMalformedError("expected a text or a binary frame");
73
+ };
74
+
75
+ /** Reads a message of the server, the same as `decodeResponseMessage` of oRPC. Throws for malformed frames. */
76
+ export const decodeOrpcResponseMessage = (frame: unknown): OrpcPeerResponseMessageType => {
77
+ const message: unknown = JSON.parse(readFrameText(frame));
78
+ if (!isRecord(message) || typeof message.i !== "string") {
79
+ throw getMalformedError("expected an object with the request id");
80
+ }
81
+
82
+ const { i: id, t: type, p: payload } = message;
83
+ if (type === peerMessageType.ABORT_SIGNAL) {
84
+ return { id, type: "abort" };
85
+ }
86
+ if (!isRecord(payload)) {
87
+ throw getMalformedError("expected the payload object");
88
+ }
89
+
90
+ if (type === peerMessageType.EVENT_ITERATOR) {
91
+ const { e: event, d: data, m: meta } = payload;
92
+ if (event !== "message" && event !== "error" && event !== "done") {
93
+ throw getMalformedError(`unknown event "${String(event)}"`);
94
+ }
95
+ return { id, type: "event", event: { event, data, meta: isRecord(meta) ? meta : undefined } };
96
+ }
97
+
98
+ // Any other message is a response, the same as in oRPC
99
+ const { s: status = 200, h: headers = {}, b: body } = payload;
100
+ if (typeof status !== "number" || !isRecord(headers)) {
101
+ throw getMalformedError("expected the status and the headers of the response");
102
+ }
103
+ return { id, type: "response", status, headers, body };
104
+ };
105
+
106
+ const flattenHeader = (header: unknown): string | undefined => {
107
+ if (typeof header === "string") {
108
+ return header;
109
+ }
110
+ return Array.isArray(header) && header.length > 0 ? header.join(", ") : undefined;
111
+ };
112
+
113
+ /** The same check as `isEventIteratorHeaders` of oRPC - an event stream that is not a file */
114
+ export const isOrpcEventIteratorResponse = (headers: Record<string, unknown>): boolean => {
115
+ return (
116
+ !!flattenHeader(headers["content-type"])?.startsWith("text/event-stream") &&
117
+ flattenHeader(headers["content-disposition"]) === undefined
118
+ );
119
+ };