@hyper-fetch/orpc 9.9.0 → 10.1.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 (74) hide show
  1. package/README.md +117 -31
  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/adapter/adapter.lifecycle.spec.ts +23 -0
  6. package/__tests__/features/adapter/adapter.schema.spec.ts +19 -0
  7. package/__tests__/features/socket/socket.schema.spec.ts +179 -0
  8. package/__tests__/features/stream-adapter/stream-adapter.environment.spec.ts +163 -0
  9. package/__tests__/features/stream-adapter/stream-adapter.lifecycle.spec.ts +558 -0
  10. package/__tests__/features/stream-adapter/stream-adapter.listener-lifecycle.spec.ts +291 -0
  11. package/__tests__/features/stream-adapter/stream-adapter.protocol.spec.ts +609 -0
  12. package/__tests__/features/stream-adapter/stream-adapter.subscriptions.spec.ts +270 -0
  13. package/__tests__/features/websocket-adapter/websocket-adapter.environment.spec.ts +153 -0
  14. package/__tests__/features/websocket-adapter/websocket-adapter.handshake-error.spec.ts +80 -0
  15. package/__tests__/features/websocket-adapter/websocket-adapter.lifecycle.spec.ts +448 -0
  16. package/__tests__/features/websocket-adapter/websocket-adapter.listener-lifecycle.spec.ts +222 -0
  17. package/__tests__/features/websocket-adapter/websocket-adapter.protocol.spec.ts +415 -0
  18. package/__tests__/features/websocket-adapter/websocket-adapter.subscriptions.spec.ts +172 -0
  19. package/__tests__/utils/controlled-fetch.ts +160 -0
  20. package/__tests__/utils/controlled-websocket.ts +140 -0
  21. package/__tests__/utils/socket-error.ts +7 -0
  22. package/__tests__/utils/stream-socket.ts +54 -0
  23. package/__tests__/utils/websocket-socket.ts +45 -0
  24. package/__tests__/vitest.setup.ts +20 -0
  25. package/dist/adapter/adapter.fetch.d.ts.map +1 -1
  26. package/dist/adapter/adapter.schema.d.ts +32 -0
  27. package/dist/adapter/adapter.schema.d.ts.map +1 -1
  28. package/dist/adapter/adapter.utils.d.ts +22 -4
  29. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  30. package/dist/index.d.ts +3 -0
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.mjs +843 -13
  33. package/dist/index.mjs.map +1 -1
  34. package/dist/socket/index.d.ts +3 -0
  35. package/dist/socket/index.d.ts.map +1 -0
  36. package/dist/socket/socket.subscriptions.d.ts +31 -0
  37. package/dist/socket/socket.subscriptions.d.ts.map +1 -0
  38. package/dist/socket/socket.types.d.ts +62 -0
  39. package/dist/socket/socket.types.d.ts.map +1 -0
  40. package/dist/socket/socket.utils.d.ts +56 -0
  41. package/dist/socket/socket.utils.d.ts.map +1 -0
  42. package/dist/stream-adapter/index.d.ts +3 -0
  43. package/dist/stream-adapter/index.d.ts.map +1 -0
  44. package/dist/stream-adapter/stream-adapter.d.ts +21 -0
  45. package/dist/stream-adapter/stream-adapter.d.ts.map +1 -0
  46. package/dist/stream-adapter/stream-adapter.types.d.ts +22 -0
  47. package/dist/stream-adapter/stream-adapter.types.d.ts.map +1 -0
  48. package/dist/stream-adapter/stream-adapter.utils.d.ts +22 -0
  49. package/dist/stream-adapter/stream-adapter.utils.d.ts.map +1 -0
  50. package/dist/websocket-adapter/index.d.ts +3 -0
  51. package/dist/websocket-adapter/index.d.ts.map +1 -0
  52. package/dist/websocket-adapter/websocket-adapter.d.ts +21 -0
  53. package/dist/websocket-adapter/websocket-adapter.d.ts.map +1 -0
  54. package/dist/websocket-adapter/websocket-adapter.types.d.ts +22 -0
  55. package/dist/websocket-adapter/websocket-adapter.types.d.ts.map +1 -0
  56. package/dist/websocket-adapter/websocket-adapter.utils.d.ts +35 -0
  57. package/dist/websocket-adapter/websocket-adapter.utils.d.ts.map +1 -0
  58. package/package.json +3 -1
  59. package/src/adapter/adapter.fetch.ts +4 -3
  60. package/src/adapter/adapter.schema.ts +57 -0
  61. package/src/adapter/adapter.utils.ts +40 -10
  62. package/src/index.ts +3 -0
  63. package/src/socket/index.ts +2 -0
  64. package/src/socket/socket.subscriptions.ts +178 -0
  65. package/src/socket/socket.types.ts +64 -0
  66. package/src/socket/socket.utils.ts +110 -0
  67. package/src/stream-adapter/index.ts +2 -0
  68. package/src/stream-adapter/stream-adapter.ts +301 -0
  69. package/src/stream-adapter/stream-adapter.types.ts +31 -0
  70. package/src/stream-adapter/stream-adapter.utils.ts +98 -0
  71. package/src/websocket-adapter/index.ts +2 -0
  72. package/src/websocket-adapter/websocket-adapter.ts +315 -0
  73. package/src/websocket-adapter/websocket-adapter.types.ts +31 -0
  74. package/src/websocket-adapter/websocket-adapter.utils.ts +119 -0
package/dist/index.mjs CHANGED
@@ -1,5 +1,7 @@
1
1
  import { Adapter, Time, defaultMapper, getErrorMessage, parseResponse, stringifyKey, stringifyQueryParams } from "@hyper-fetch/core";
2
- import { StandardRPCJsonSerializer, StandardRPCSerializer } from "@orpc/client/standard";
2
+ import { StandardRPCJsonSerializer, StandardRPCSerializer, getMalformedResponseErrorCode } from "@orpc/client/standard";
3
+ import { ErrorEvent, ORPCError, createORPCErrorFromJson, isORPCErrorJson, isORPCErrorStatus } from "@orpc/client";
4
+ import { SocketAdapter, WebsocketReadyState, createReconnectingConnection, getSocketError, getSocketUrl, getWebsocketConstructor } from "@hyper-fetch/sockets";
3
5
  //#region src/adapter/adapter.constants.ts
4
6
  var defaultTimeout = Time.SEC * 5;
5
7
  var orpcExtra = { headers: {} };
@@ -49,17 +51,24 @@ var getOrpcRequestKey = (request, serializer) => {
49
51
  var getOrpcAbortKey = (request) => {
50
52
  return `${request.method}_${orpcEndpointMapper(request.endpoint)}-${request.cancelable}`;
51
53
  };
54
+ /**
55
+ * Key of a subscription - listeners of the same topic with the same input share one server subscription.
56
+ * The input is read in the wire format, so values like `Date` or `Map` stay distinct.
57
+ */
58
+ var getOrpcSubscriptionKey = (topic, payload, serializer) => {
59
+ return `${topic}-${getOrpcInputKey(payload, serializer)}`;
60
+ };
52
61
  /** Only the user headers, the content type depends on the encoded body and is set while sending */
53
62
  var getOrpcHeaders = (request) => {
54
63
  return { ...request.headers };
55
64
  };
56
65
  /**
57
- * Encodes the call as described by the oRPC RPC protocol.
58
- * GET sends the input in the `data` query param. Files and urls over the length limit fall back to POST,
59
- * the same as the `RPCLink` of oRPC.
66
+ * Encodes a call of the procedure as described by the oRPC RPC protocol, for any base `url` - the client url of a
67
+ * request or the url of a socket. GET sends the input in the `data` query param. Files and urls over the length limit
68
+ * fall back to POST, the same as the `RPCLink` of oRPC.
60
69
  */
61
- var getOrpcHttpRequest = ({ request, endpoint, queryParams, headers, payload, queryMethod, serializer }) => {
62
- const [baseUrl, baseQuery] = request.client.url.split("?");
70
+ var getOrpcCallRequest = ({ url: base, endpoint, queryParams, headers, payload, method, serializer }) => {
71
+ const [baseUrl, baseQuery] = base.split("?");
63
72
  const searchParams = new URLSearchParams(baseQuery);
64
73
  new URLSearchParams(stringifyQueryParams(queryParams)).forEach((value, key) => {
65
74
  if (!reservedQueryParams.includes(key)) searchParams.append(key, value);
@@ -67,7 +76,7 @@ var getOrpcHttpRequest = ({ request, endpoint, queryParams, headers, payload, qu
67
76
  const url = `${baseUrl.replace(/\/+$/, "")}${endpoint}`;
68
77
  const serialized = serializer.serialize(payload);
69
78
  const userHeaders = { ...headers };
70
- if (request.method === OrpcMethods.QUERY && queryMethod === "GET" && !(serialized instanceof FormData)) {
79
+ if (method === "GET" && !(serialized instanceof FormData)) {
71
80
  const getParams = new URLSearchParams(searchParams);
72
81
  getParams.append("data", JSON.stringify(serialized));
73
82
  const getUrl = `${url}?${getParams.toString()}`;
@@ -95,12 +104,24 @@ var getOrpcHttpRequest = ({ request, endpoint, queryParams, headers, payload, qu
95
104
  body: JSON.stringify(serialized)
96
105
  };
97
106
  };
98
- var isRecord = (value) => {
107
+ /**
108
+ * Encodes the request as described by the oRPC RPC protocol.
109
+ * Queries use the `queryMethod`, mutations are always sent with POST.
110
+ */
111
+ var getOrpcHttpRequest = ({ request, queryMethod, ...call }) => {
112
+ const method = request.method === OrpcMethods.QUERY && queryMethod === "GET" ? "GET" : "POST";
113
+ return getOrpcCallRequest({
114
+ ...call,
115
+ url: request.client.url,
116
+ method
117
+ });
118
+ };
119
+ var isRecord$1 = (value) => {
99
120
  return typeof value === "object" && value !== null;
100
121
  };
101
122
  /** The same check as `isORPCErrorJson` of oRPC */
102
123
  var isOrpcError = (value) => {
103
- return isRecord(value) && typeof value.defined === "boolean" && typeof value.code === "string" && typeof value.status === "number" && typeof value.message === "string";
124
+ return isRecord$1(value) && typeof value.defined === "boolean" && typeof value.code === "string" && typeof value.status === "number" && typeof value.message === "string";
104
125
  };
105
126
  /**
106
127
  * Reads the serialized `{ json, meta }` body, or the multipart body when the output contains files.
@@ -109,7 +130,7 @@ var isOrpcError = (value) => {
109
130
  var getOrpcResult = ({ body, status, serializer }) => {
110
131
  let parsed = body || void 0;
111
132
  if (typeof parsed === "string") parsed = parseResponse(parsed);
112
- if (!(parsed === void 0 || parsed instanceof FormData || isRecord(parsed))) return {
133
+ if (!(parsed === void 0 || parsed instanceof FormData || isRecord$1(parsed))) return {
113
134
  isSuccess: false,
114
135
  error: getErrorMessage()
115
136
  };
@@ -210,9 +231,8 @@ var getOrpcAdapter = ({ queryMethod: defaultQueryMethod = "POST", customJsonSeri
210
231
  const total = getBodySize(httpRequest.body);
211
232
  if (total) onRequestProgress({
212
233
  total,
213
- loaded: total
234
+ loaded: 0
214
235
  });
215
- onRequestEnd();
216
236
  const response = await fetch(httpRequest.url, {
217
237
  ...restOptions,
218
238
  method: httpRequest.method,
@@ -220,6 +240,7 @@ var getOrpcAdapter = ({ queryMethod: defaultQueryMethod = "POST", customJsonSeri
220
240
  body: httpRequest.body,
221
241
  signal: controller.signal
222
242
  });
243
+ onRequestEnd();
223
244
  onResponseStart();
224
245
  const responseHeaders = {};
225
246
  response.headers.forEach((value, key) => {
@@ -277,6 +298,815 @@ var OrpcAdapter = (options) => {
277
298
  return getOrpcAdapter(options);
278
299
  };
279
300
  //#endregion
280
- export { OrpcAdapter, OrpcMethods, createOrpcSerializer, defaultTimeout, getOrpcAbortKey, getOrpcAdapter, getOrpcHeaders, getOrpcHttpRequest, getOrpcRequestKey, getOrpcResult, maxGetUrlLength, orpcEndpointMapper, orpcExtra, reservedQueryParams };
301
+ //#region src/socket/socket.utils.ts
302
+ var toError = (error) => {
303
+ return error instanceof Error ? error : new Error(String(error));
304
+ };
305
+ var isRecord = (value) => {
306
+ return typeof value === "object" && value !== null;
307
+ };
308
+ /**
309
+ * Turns the serialized `{ json, meta }` data into the value. Anything else is not a part of the RPC protocol.
310
+ * It throws for malformed data, the same as the serializer of oRPC.
311
+ */
312
+ var deserializeOrpcData = (data, serializer) => {
313
+ if (data !== void 0 && !isRecord(data)) throw new TypeError("Invalid RPC serialized data: expected the { json, meta } object");
314
+ return serializer.deserialize(data);
315
+ };
316
+ /**
317
+ * The error of a call the server rejected before the event iterator started, e.g. a failed input validation or
318
+ * middleware. The same as in the `RPCLink` of oRPC: an `ORPCError` from the body, or one named after the status
319
+ * when the body is not an oRPC error.
320
+ */
321
+ var getOrpcResponseError = ({ status, body, serializer }) => {
322
+ let value = body;
323
+ try {
324
+ value = deserializeOrpcData(body, serializer);
325
+ } catch {}
326
+ if (isORPCErrorJson(value)) return createORPCErrorFromJson(value);
327
+ return new ORPCError(getMalformedResponseErrorCode(status), {
328
+ status,
329
+ data: value
330
+ });
331
+ };
332
+ /** Reported when the procedure of a listener returns a regular output instead of an event iterator */
333
+ var getNotIteratorError = (topic) => {
334
+ return /* @__PURE__ */ new Error(`The procedure "${topic}" did not return an event iterator`);
335
+ };
336
+ /**
337
+ * Error of an oRPC subscription, reported to the `socket.onError` callbacks. `topic` and `payload` tell which
338
+ * subscription failed. `shape` is the error the server sent, in the shape of `ORPCError.toJSON()` - it is `null` when
339
+ * the failure did not come from a procedure, e.g. a dropped stream or a malformed message. The original error is the
340
+ * `cause`.
341
+ *
342
+ * @example
343
+ * socket.onError(({ error }) => {
344
+ * if (error instanceof OrpcSocketError && error.defined && error.code === "UNAUTHORIZED") {
345
+ * logout();
346
+ * }
347
+ * });
348
+ */
349
+ var OrpcSocketError = class extends Error {
350
+ /** Error sent by the server, `null` when the failure did not come from a procedure */
351
+ shape;
352
+ /** Topic of the failed subscription, `null` when the message can't be matched to a subscription */
353
+ topic;
354
+ /** Input of the failed subscription */
355
+ payload;
356
+ constructor({ cause, topic, payload }) {
357
+ const shape = cause instanceof ORPCError ? cause.toJSON() : null;
358
+ super(shape?.message ?? toError(cause).message, { cause });
359
+ this.name = "OrpcSocketError";
360
+ this.shape = shape;
361
+ this.topic = topic;
362
+ this.payload = payload;
363
+ }
364
+ /** `true` for the errors from the `.errors()` map of the procedure */
365
+ get defined() {
366
+ return this.shape?.defined ?? false;
367
+ }
368
+ /** Code of the server error, e.g. `"NOT_FOUND"` */
369
+ get code() {
370
+ return this.shape?.code;
371
+ }
372
+ /** Status of the server error */
373
+ get status() {
374
+ return this.shape?.status;
375
+ }
376
+ /** Data of the server error */
377
+ get data() {
378
+ return this.shape?.data;
379
+ }
380
+ };
381
+ //#endregion
382
+ //#region src/socket/socket.subscriptions.ts
383
+ /**
384
+ * Keeps one server subscription per procedure and input, shared by every listener with the same topic and payload.
385
+ * The adapter starts and stops the server side, this module counts the listeners, turns the events of the server
386
+ * iterator into listener messages and errors, and reports the lifecycle of the subscription to the listeners.
387
+ *
388
+ * - `start` is called for a subscription that has no running server side. It does nothing until the adapter can
389
+ * start it, the adapter starts the rest when it connects.
390
+ * - `stop` is called when the last listener of a running subscription unsubscribes - it cancels the server side.
391
+ * - `release` forgets the server side of a subscription the server ended, without telling the server.
392
+ */
393
+ var createOrpcSubscriptions = ({ bindings, serializer, start, stop, release }) => {
394
+ const { onListen, onEvent, onError, onListenerStart, onListenerEnd } = bindings;
395
+ const subscriptions = /* @__PURE__ */ new Map();
396
+ /** The callbacks of a subscription as the bindings of the adapter type them */
397
+ const callbacksOf = (subscription) => subscription.callbacks;
398
+ const createError = (subscription, cause) => {
399
+ return new OrpcSocketError({
400
+ cause,
401
+ topic: subscription.topic,
402
+ payload: subscription.payload
403
+ });
404
+ };
405
+ /**
406
+ * Reports a failure of the subscription that does not end it, e.g. a dropped stream that starts again, as an
407
+ * `OrpcSocketError`, so the user can tell which subscription failed
408
+ */
409
+ const report = (subscription, cause) => {
410
+ onError({ error: createError(subscription, cause) });
411
+ };
412
+ /** The server confirmed the subscription - after the first start and after every restart */
413
+ const confirm = (subscription) => {
414
+ subscription.started = true;
415
+ onListenerStart({
416
+ topic: subscription.topic,
417
+ callbacks: callbacksOf(subscription)
418
+ });
419
+ };
420
+ /**
421
+ * The server ended the subscription - finished it when `cause` is not set, failed it otherwise. The error is
422
+ * reported to `onError` too. The listeners unsubscribe, and a later `listen()` starts a new subscription.
423
+ */
424
+ const end = (subscription, cause) => {
425
+ release(subscription);
426
+ subscription.started = false;
427
+ subscriptions.delete(subscription.key);
428
+ const error = cause === void 0 ? null : createError(subscription, cause);
429
+ if (error) onError({ error });
430
+ onListenerEnd({
431
+ topic: subscription.topic,
432
+ callbacks: new Set(callbacksOf(subscription)),
433
+ error
434
+ });
435
+ };
436
+ const listen = (listener, callback) => {
437
+ const key = getOrpcSubscriptionKey(listener.topic, listener.payload, serializer);
438
+ const subscription = subscriptions.get(key) ?? {
439
+ key,
440
+ topic: listener.topic,
441
+ payload: listener.payload,
442
+ callbacks: /* @__PURE__ */ new Set(),
443
+ lastEventId: void 0,
444
+ lastEventRetry: void 0,
445
+ transport: void 0,
446
+ started: false
447
+ };
448
+ subscriptions.set(key, subscription);
449
+ subscription.callbacks.add(callback);
450
+ const removeListener = onListen({
451
+ listener,
452
+ callback,
453
+ onUnmount: () => {
454
+ subscription.callbacks.delete(callback);
455
+ if (subscription.callbacks.size === 0 && subscriptions.get(key) === subscription) {
456
+ subscriptions.delete(key);
457
+ stop(subscription);
458
+ }
459
+ }
460
+ });
461
+ if (subscription.started) onListenerStart({
462
+ topic: subscription.topic,
463
+ callbacks: new Set([callback])
464
+ });
465
+ else if (!subscription.transport) start(subscription);
466
+ return removeListener;
467
+ };
468
+ /**
469
+ * Applies an event of the server iterator to the subscription. `done` and `error` end the subscription, then it
470
+ * returns `true`. Nothing here throws into the transport: errors of the server
471
+ * and malformed data are reported as an `OrpcSocketError`, errors thrown by listener callbacks as they are.
472
+ */
473
+ const receive = (subscription, { event, data, meta }) => {
474
+ const id = typeof meta?.id === "string" ? meta.id : void 0;
475
+ const retry = typeof meta?.retry === "number" ? meta.retry : void 0;
476
+ subscription.lastEventId = id ?? subscription.lastEventId;
477
+ subscription.lastEventRetry = retry ?? subscription.lastEventRetry;
478
+ if (event === "done") {
479
+ end(subscription);
480
+ return true;
481
+ }
482
+ let value;
483
+ try {
484
+ value = deserializeOrpcData(data, serializer);
485
+ } catch (error) {
486
+ if (event === "error") {
487
+ end(subscription, error);
488
+ return true;
489
+ }
490
+ report(subscription, error);
491
+ return false;
492
+ }
493
+ if (event === "error") {
494
+ end(subscription, isORPCErrorJson(value) ? createORPCErrorFromJson(value) : new ErrorEvent({ data: value }));
495
+ return true;
496
+ }
497
+ const extra = {
498
+ id,
499
+ retry
500
+ };
501
+ try {
502
+ onEvent({
503
+ topic: subscription.topic,
504
+ data: value,
505
+ extra,
506
+ callbacks: callbacksOf(subscription)
507
+ });
508
+ } catch (error) {
509
+ onError({ error: toError(error) });
510
+ }
511
+ return false;
512
+ };
513
+ return {
514
+ listen,
515
+ receive,
516
+ report,
517
+ confirm,
518
+ end,
519
+ values: () => [...subscriptions.values()]
520
+ };
521
+ };
522
+ //#endregion
523
+ //#region src/stream-adapter/stream-adapter.utils.ts
524
+ var lineEnding = /\r\n|\r(?!\n)|\n/;
525
+ var messageDelimiter = /(?:\r\n|\r(?!\n)|\n){2}/g;
526
+ /** Reads the fields of one message, the same as `decodeEventMessage` of oRPC */
527
+ var decodeEventStreamMessage = (encoded) => {
528
+ const message = {
529
+ event: void 0,
530
+ data: void 0,
531
+ id: void 0,
532
+ retry: void 0
533
+ };
534
+ encoded.split(lineEnding).forEach((line) => {
535
+ const index = line.indexOf(":");
536
+ if (line === "" || index === 0) return;
537
+ const field = index === -1 ? line : line.slice(0, index);
538
+ const value = index === -1 ? "" : line.slice(line.charAt(index + 1) === " " ? index + 2 : index + 1);
539
+ if (field === "data") message.data = message.data === void 0 ? value : `${message.data}\n${value}`;
540
+ else if (field === "event") message.event = value;
541
+ else if (field === "id") message.id = value;
542
+ else if (field === "retry") {
543
+ const retry = Number.parseInt(value, 10);
544
+ if (retry >= 0 && retry.toString() === value) message.retry = retry;
545
+ }
546
+ });
547
+ return message;
548
+ };
549
+ /**
550
+ * Splits the text of a `text/event-stream` into messages, the same as the `EventDecoder` of oRPC. Chunks can end
551
+ * anywhere, the text after the last complete message waits for the next chunk.
552
+ */
553
+ var createEventStreamDecoder = (onMessage) => {
554
+ let pending = "";
555
+ let discardLeadingLineFeed = false;
556
+ const feed = (chunk) => {
557
+ pending += discardLeadingLineFeed && chunk.startsWith("\n") ? chunk.slice(1) : chunk;
558
+ discardLeadingLineFeed = false;
559
+ let start = 0;
560
+ const messages = [];
561
+ [...pending.matchAll(messageDelimiter)].forEach((match) => {
562
+ const { index = 0 } = match;
563
+ messages.push(pending.slice(start, index));
564
+ start = index + match[0].length;
565
+ });
566
+ if (messages.length > 0) discardLeadingLineFeed = start === pending.length && pending.endsWith("\r");
567
+ pending = pending.slice(start);
568
+ messages.forEach((message) => onMessage(decodeEventStreamMessage(message)));
569
+ };
570
+ /** The same as oRPC - a stream that stops in the middle of a message is broken */
571
+ const end = () => {
572
+ if (pending !== "") throw new Error("The event stream ended before the last message was complete");
573
+ };
574
+ return {
575
+ feed,
576
+ end
577
+ };
578
+ };
579
+ /**
580
+ * Maps a message to the event of the server iterator, the same as `toEventIterator` of oRPC. Messages without an
581
+ * event and data are keep-alive pings and return `null`. Throws when the data is not JSON.
582
+ */
583
+ var getEventStreamIteratorEvent = (message) => {
584
+ const event = message.event ?? (message.data !== void 0 ? "message" : void 0);
585
+ const meta = {
586
+ id: message.id,
587
+ retry: message.retry
588
+ };
589
+ if (event === "message" || event === "error") return {
590
+ event,
591
+ data: message.data ? JSON.parse(message.data) : void 0,
592
+ meta
593
+ };
594
+ if (event === "done" || event === "close") return {
595
+ event: "done",
596
+ data: void 0,
597
+ meta
598
+ };
599
+ return null;
600
+ };
601
+ //#endregion
602
+ //#region src/stream-adapter/stream-adapter.ts
603
+ /**
604
+ * Socket adapter for the event iterators of oRPC over HTTP. Every subscription is a call of the procedure with the
605
+ * RPC protocol - a `POST {url}/planet/onUpdate` with the serialized input - answered with a `text/event-stream`.
606
+ * The same protocol as the `RPCLink` of oRPC, so it works with the `RPCHandler` of `@orpc/server/fetch` or `/node`.
607
+ *
608
+ * There is no shared connection: "connected" means the adapter opens streams. `connect()` starts every
609
+ * subscription, `disconnect()` aborts them, `reconnect()` starts them again with the id of their last event.
610
+ * Listeners of the same procedure and input share one stream, the last one to unsubscribe aborts it.
611
+ * A subscription starts (`onStart`) when the server answers with the event stream, and ends (`onEnd`) when the
612
+ * iterator finishes, fails or the server rejects the call.
613
+ *
614
+ * @example
615
+ * const socket = new Socket({ url: "http://localhost:3000/rpc", adapter: OrpcStreamAdapter() });
616
+ * const sdk = createSocketSdk<typeof socket, OrpcSocketSchema<typeof router>>(socket, { camelCaseToKebabCase: false });
617
+ *
618
+ * sdk.planet.onUpdate.$listener.setPayload({ id: 1 }).listen(({ data, extra }) => console.log(data, extra.id));
619
+ */
620
+ var OrpcStreamAdapter = ({ customJsonSerializers } = {}) => {
621
+ const serializer = createOrpcSerializer(customJsonSerializers);
622
+ return new SocketAdapter({
623
+ name: "orpc-stream",
624
+ confirmsSubscriptions: true
625
+ }).setQueryParamsMapper(stringifyQueryParams).setConnector((bindings) => {
626
+ const { socket, adapter, getQueryParams, onConnectFailed } = bindings;
627
+ let connection;
628
+ const subscriptions = createOrpcSubscriptions({
629
+ bindings,
630
+ serializer,
631
+ start: (subscription) => startStream(subscription, 0),
632
+ stop: (subscription) => stopStream(subscription),
633
+ release: (subscription) => stopStream(subscription)
634
+ });
635
+ /**
636
+ * Aborts the request or the wait of the subscription. Whatever the old request reports later is ignored.
637
+ * For a stream the server ended it only releases the response.
638
+ */
639
+ const stopStream = (subscription) => {
640
+ const { transport } = subscription;
641
+ subscription.transport = void 0;
642
+ subscription.started = false;
643
+ if (transport) {
644
+ clearTimeout(transport.timer);
645
+ transport.controller?.abort();
646
+ }
647
+ };
648
+ /** After a failure the stream starts again, after the `retry` of the last event or the socket reconnect time */
649
+ const scheduleRestart = (subscription, attempts) => {
650
+ if (attempts > socket.reconnectAttempts) {
651
+ subscriptions.end(subscription, /* @__PURE__ */ new Error(`Stopped restarting the stream of "${subscription.topic}" after ${attempts - 1} attempts`));
652
+ return;
653
+ }
654
+ const transport = {
655
+ controller: void 0,
656
+ timer: void 0,
657
+ attempts,
658
+ timedOut: false
659
+ };
660
+ transport.timer = setTimeout(() => {
661
+ startStream(subscription, attempts);
662
+ }, subscription.lastEventRetry ?? socket.reconnectTime);
663
+ subscription.transport = transport;
664
+ };
665
+ /** Returns `true` when the server ended the iterator */
666
+ const receiveMessage = (subscription, message) => {
667
+ try {
668
+ const event = getEventStreamIteratorEvent(message);
669
+ return event ? subscriptions.receive(subscription, event) : false;
670
+ } catch (error) {
671
+ subscriptions.report(subscription, error);
672
+ return false;
673
+ }
674
+ };
675
+ /**
676
+ * Reads the stream until the server ends it. Resolves the error of a call the server rejected, rejects when
677
+ * the transport failed - the network, the timeout or a stream cut in the middle of a message.
678
+ */
679
+ const readStream = async ({ subscription, transport, controller, details: { url, queryParams, adapterOptions } }) => {
680
+ const { headers, fetchOptions, fetch: customFetch } = adapterOptions ?? {};
681
+ const { lastEventId } = subscription;
682
+ const request = getOrpcCallRequest({
683
+ url,
684
+ endpoint: orpcEndpointMapper(subscription.topic),
685
+ queryParams: getQueryParams(queryParams),
686
+ headers: lastEventId === void 0 ? { ...headers } : {
687
+ ...headers,
688
+ "last-event-id": lastEventId
689
+ },
690
+ payload: subscription.payload,
691
+ method: "POST",
692
+ serializer
693
+ });
694
+ const response = await (customFetch ?? globalThis.fetch)(request.url, {
695
+ ...fetchOptions,
696
+ method: request.method,
697
+ headers: request.headers,
698
+ body: request.body,
699
+ signal: controller.signal
700
+ });
701
+ clearTimeout(transport.timer);
702
+ if (isORPCErrorStatus(response.status)) {
703
+ const body = parseResponse(await response.text());
704
+ return getOrpcResponseError({
705
+ status: response.status,
706
+ body,
707
+ serializer
708
+ });
709
+ }
710
+ if (!response.headers.get("content-type")?.startsWith("text/event-stream")) return getNotIteratorError(subscription.topic);
711
+ transport.attempts = 0;
712
+ if (subscription.transport === transport) subscriptions.confirm(subscription);
713
+ if (!response.body) return null;
714
+ const reader = response.body.getReader();
715
+ const textDecoder = new TextDecoder();
716
+ let ended = false;
717
+ const eventDecoder = createEventStreamDecoder((message) => {
718
+ if (!ended && subscription.transport === transport) ended = receiveMessage(subscription, message);
719
+ });
720
+ let chunk = await reader.read();
721
+ while (!chunk.done) {
722
+ eventDecoder.feed(textDecoder.decode(chunk.value, { stream: true }));
723
+ if (ended) return null;
724
+ chunk = await reader.read();
725
+ }
726
+ eventDecoder.feed(textDecoder.decode());
727
+ eventDecoder.end();
728
+ return null;
729
+ };
730
+ const startStream = (subscription, attempts) => {
731
+ const details = connection;
732
+ if (!details) return;
733
+ const controller = new AbortController();
734
+ const transport = {
735
+ controller,
736
+ timer: void 0,
737
+ attempts,
738
+ timedOut: false
739
+ };
740
+ subscription.transport = transport;
741
+ const isCurrent = () => subscription.transport === transport;
742
+ transport.timer = setTimeout(() => {
743
+ transport.timedOut = true;
744
+ controller.abort();
745
+ }, socket.connectionTimeout);
746
+ readStream({
747
+ subscription,
748
+ transport,
749
+ controller,
750
+ details
751
+ }).then((rejection) => {
752
+ if (!isCurrent()) return;
753
+ subscriptions.end(subscription, rejection ?? void 0);
754
+ }, (error) => {
755
+ if (!isCurrent()) return;
756
+ stopStream(subscription);
757
+ subscriptions.report(subscription, transport.timedOut ? /* @__PURE__ */ new Error(`The stream of "${subscription.topic}" did not open in ${socket.connectionTimeout}ms`) : error);
758
+ scheduleRestart(subscription, transport.attempts + 1);
759
+ });
760
+ };
761
+ /** Aborts every stream. Listeners stay registered and keep the id of their last event for the next connection. */
762
+ const stopStreams = () => {
763
+ subscriptions.values().forEach(stopStream);
764
+ };
765
+ /**
766
+ * There is no shared transport - the connection is the set of streams opened with its details. It is ready at
767
+ * once, and it is never lost as a whole: every stream fails and starts again on its own (`scheduleRestart`).
768
+ */
769
+ const connectionLifecycle = createReconnectingConnection({
770
+ bindings,
771
+ autoConnect: adapter.adapterOptions?.autoConnect ?? true,
772
+ open: (attempt) => {
773
+ const details = attempt.connection;
774
+ if (typeof (details.adapterOptions?.fetch ?? globalThis.fetch) !== "function") {
775
+ onConnectFailed({ error: /* @__PURE__ */ new Error("fetch is not available in this environment") });
776
+ return null;
777
+ }
778
+ connection = details;
779
+ attempt.ready();
780
+ subscriptions.values().forEach((subscription) => {
781
+ if (!subscription.transport) startStream(subscription, 0);
782
+ });
783
+ return { close: () => {
784
+ connection = void 0;
785
+ stopStreams();
786
+ } };
787
+ }
788
+ });
789
+ const emit = () => {
790
+ throw new Error("Cannot emit events in the oRPC stream adapter, it only receives events of subscriptions");
791
+ };
792
+ return {
793
+ connect: connectionLifecycle.connect,
794
+ reconnect: connectionLifecycle.reconnect,
795
+ disconnect: connectionLifecycle.disconnect,
796
+ listen: subscriptions.listen,
797
+ emit,
798
+ dispose: () => {
799
+ connectionLifecycle.dispose();
800
+ connection = void 0;
801
+ stopStreams();
802
+ }
803
+ };
804
+ });
805
+ };
806
+ //#endregion
807
+ //#region src/websocket-adapter/websocket-adapter.utils.ts
808
+ /** Message types of the oRPC peer protocol, used by `@orpc/server/ws` and `@orpc/client/websocket` */
809
+ var peerMessageType = {
810
+ REQUEST: 1,
811
+ RESPONSE: 2,
812
+ EVENT_ITERATOR: 3,
813
+ ABORT_SIGNAL: 4
814
+ };
815
+ /** JSON and binary parts of a binary frame are split by this byte */
816
+ var binaryDelimiter = 255;
817
+ var getMalformedError = (detail) => /* @__PURE__ */ new TypeError(`Invalid oRPC message: ${detail}`);
818
+ /**
819
+ * Starts the call of the procedure - the same request message as the `RPCLink` of `@orpc/client/websocket`.
820
+ * The input is serialized with the RPC serializer, inputs with files are not supported.
821
+ */
822
+ var encodeOrpcRequestMessage = ({ id, topic, payload, headers, serializer }) => {
823
+ const body = serializer.serialize(payload);
824
+ if (body instanceof FormData) throw new TypeError(`Files in the input of "${topic}" are not supported by the oRPC WebSocket adapter`);
825
+ return JSON.stringify({
826
+ i: id,
827
+ p: {
828
+ u: orpcEndpointMapper(topic),
829
+ b: body,
830
+ h: Object.keys(headers).length > 0 ? headers : void 0
831
+ }
832
+ });
833
+ };
834
+ /** Stops the call of the procedure, the server cancels its iterator */
835
+ var encodeOrpcAbortMessage = (id) => {
836
+ return JSON.stringify({
837
+ i: id,
838
+ t: peerMessageType.ABORT_SIGNAL
839
+ });
840
+ };
841
+ var readFrameText = (frame) => {
842
+ if (typeof frame === "string") return frame;
843
+ if (frame instanceof ArrayBuffer || ArrayBuffer.isView(frame)) {
844
+ const bytes = frame instanceof ArrayBuffer ? new Uint8Array(frame) : new Uint8Array(frame.buffer, frame.byteOffset, frame.byteLength);
845
+ const end = bytes.indexOf(binaryDelimiter);
846
+ return new TextDecoder().decode(end === -1 ? bytes : bytes.subarray(0, end));
847
+ }
848
+ throw getMalformedError("expected a text or a binary frame");
849
+ };
850
+ /** Reads a message of the server, the same as `decodeResponseMessage` of oRPC. Throws for malformed frames. */
851
+ var decodeOrpcResponseMessage = (frame) => {
852
+ const message = JSON.parse(readFrameText(frame));
853
+ if (!isRecord(message) || typeof message.i !== "string") throw getMalformedError("expected an object with the request id");
854
+ const { i: id, t: type, p: payload } = message;
855
+ if (type === peerMessageType.ABORT_SIGNAL) return {
856
+ id,
857
+ type: "abort"
858
+ };
859
+ if (!isRecord(payload)) throw getMalformedError("expected the payload object");
860
+ if (type === peerMessageType.EVENT_ITERATOR) {
861
+ const { e: event, d: data, m: meta } = payload;
862
+ if (event !== "message" && event !== "error" && event !== "done") throw getMalformedError(`unknown event "${String(event)}"`);
863
+ return {
864
+ id,
865
+ type: "event",
866
+ event: {
867
+ event,
868
+ data,
869
+ meta: isRecord(meta) ? meta : void 0
870
+ }
871
+ };
872
+ }
873
+ const { s: status = 200, h: headers = {}, b: body } = payload;
874
+ if (typeof status !== "number" || !isRecord(headers)) throw getMalformedError("expected the status and the headers of the response");
875
+ return {
876
+ id,
877
+ type: "response",
878
+ status,
879
+ headers,
880
+ body
881
+ };
882
+ };
883
+ var flattenHeader = (header) => {
884
+ if (typeof header === "string") return header;
885
+ return Array.isArray(header) && header.length > 0 ? header.join(", ") : void 0;
886
+ };
887
+ /** The same check as `isEventIteratorHeaders` of oRPC - an event stream that is not a file */
888
+ var isOrpcEventIteratorResponse = (headers) => {
889
+ return !!flattenHeader(headers["content-type"])?.startsWith("text/event-stream") && flattenHeader(headers["content-disposition"]) === void 0;
890
+ };
891
+ //#endregion
892
+ //#region src/websocket-adapter/websocket-adapter.ts
893
+ /**
894
+ * Socket adapter for the event iterators of oRPC over one WebSocket connection. It speaks the protocol of the
895
+ * `RPCHandler` of `@orpc/server/ws` (the same as `@orpc/client/websocket`): every subscription is a request on the
896
+ * shared connection, and its events arrive as messages of that request.
897
+ *
898
+ * The adapter only subscribes. Emitting, and calling regular procedures, is not supported - use `OrpcAdapter` for
899
+ * them. Listeners of the same procedure and input share one request, the last one to unsubscribe aborts it.
900
+ * After a reconnect every running subscription starts again with the id of its last event. A subscription starts
901
+ * (`onStart`) when the server answers with the event iterator, and ends (`onEnd`) when the iterator finishes, fails
902
+ * or the server rejects the call.
903
+ *
904
+ * @example
905
+ * const socket = new Socket({ url: "ws://localhost:3000", adapter: OrpcWebsocketAdapter() });
906
+ * const sdk = createSocketSdk<typeof socket, OrpcSocketSchema<typeof router>>(socket, { camelCaseToKebabCase: false });
907
+ *
908
+ * sdk.planet.onUpdate.$listener.setPayload({ id: 1 }).listen(({ data }) => console.log(data));
909
+ */
910
+ var OrpcWebsocketAdapter = ({ customJsonSerializers } = {}) => {
911
+ const serializer = createOrpcSerializer(customJsonSerializers);
912
+ return new SocketAdapter({
913
+ name: "orpc-websocket",
914
+ confirmsSubscriptions: true
915
+ }).setQueryParamsMapper(stringifyQueryParams).setConnector((bindings) => {
916
+ const { adapter, getQueryParams, onConnectFailed, onError } = bindings;
917
+ let websocket;
918
+ let options;
919
+ let lastRequestId = 0;
920
+ const requests = /* @__PURE__ */ new Map();
921
+ const subscriptions = createOrpcSubscriptions({
922
+ bindings,
923
+ serializer,
924
+ start: (subscription) => startSubscription(subscription),
925
+ stop: (subscription) => stopSubscription(subscription),
926
+ release: (subscription) => {
927
+ releaseSubscription(subscription);
928
+ }
929
+ });
930
+ /** Sends a frame of the subscription, reporting the failure instead of throwing */
931
+ const sendFrame = (subscription, target, frame) => {
932
+ try {
933
+ target.send(frame);
934
+ return true;
935
+ } catch (error) {
936
+ subscriptions.report(subscription, error);
937
+ return false;
938
+ }
939
+ };
940
+ const startSubscription = (subscription) => {
941
+ const current = websocket;
942
+ if (!current || !adapter.connected) return;
943
+ lastRequestId += 1;
944
+ const id = lastRequestId.toString(36);
945
+ const { lastEventId } = subscription;
946
+ const headers = lastEventId === void 0 ? { ...options?.headers } : {
947
+ ...options?.headers,
948
+ "last-event-id": lastEventId
949
+ };
950
+ let frame;
951
+ try {
952
+ frame = encodeOrpcRequestMessage({
953
+ id,
954
+ topic: subscription.topic,
955
+ payload: subscription.payload,
956
+ headers,
957
+ serializer
958
+ });
959
+ } catch (error) {
960
+ subscriptions.end(subscription, error);
961
+ return;
962
+ }
963
+ if (sendFrame(subscription, current, frame)) {
964
+ subscription.transport = {
965
+ id,
966
+ websocket: current
967
+ };
968
+ requests.set(id, subscription);
969
+ }
970
+ };
971
+ /** Forgets the request of the subscription. Messages that still come for it are ignored. */
972
+ const releaseSubscription = (subscription) => {
973
+ const { transport } = subscription;
974
+ subscription.transport = void 0;
975
+ subscription.started = false;
976
+ if (transport) requests.delete(transport.id);
977
+ return transport;
978
+ };
979
+ const stopSubscription = (subscription) => {
980
+ const transport = releaseSubscription(subscription);
981
+ if (transport) sendFrame(subscription, transport.websocket, encodeOrpcAbortMessage(transport.id));
982
+ };
983
+ /** The connection is gone and the server dropped every request with it */
984
+ const releaseAll = () => {
985
+ requests.forEach((subscription) => {
986
+ subscription.transport = void 0;
987
+ subscription.started = false;
988
+ });
989
+ requests.clear();
990
+ };
991
+ const handleResponse = (subscription, { status, headers, body }) => {
992
+ if (isORPCErrorStatus(status)) {
993
+ subscriptions.end(subscription, getOrpcResponseError({
994
+ status,
995
+ body,
996
+ serializer
997
+ }));
998
+ return;
999
+ }
1000
+ if (!isOrpcEventIteratorResponse(headers)) {
1001
+ subscriptions.end(subscription, getNotIteratorError(subscription.topic));
1002
+ return;
1003
+ }
1004
+ subscriptions.confirm(subscription);
1005
+ };
1006
+ const handleMessage = (frame) => {
1007
+ let message;
1008
+ try {
1009
+ message = decodeOrpcResponseMessage(frame);
1010
+ } catch (error) {
1011
+ onError({ error: new OrpcSocketError({
1012
+ cause: error,
1013
+ topic: null,
1014
+ payload: void 0
1015
+ }) });
1016
+ return;
1017
+ }
1018
+ const subscription = requests.get(message.id);
1019
+ if (!subscription || message.type === "abort") return;
1020
+ if (message.type === "response") {
1021
+ handleResponse(subscription, message);
1022
+ return;
1023
+ }
1024
+ subscriptions.receive(subscription, message.event);
1025
+ };
1026
+ /** Creates the transport, reporting a failed attempt when the environment or the connection details are invalid */
1027
+ const createWebsocket = (url) => {
1028
+ const WebSocketConstructor = getWebsocketConstructor(options);
1029
+ if (!WebSocketConstructor) {
1030
+ onConnectFailed({ error: /* @__PURE__ */ new Error("WebSocket is not available in this environment") });
1031
+ return null;
1032
+ }
1033
+ try {
1034
+ return new WebSocketConstructor(url, options?.protocols);
1035
+ } catch (error) {
1036
+ onConnectFailed({ error: toError(error) });
1037
+ return null;
1038
+ }
1039
+ };
1040
+ /**
1041
+ * Closes a detached transport. The server cancels every subscription of the connection, the listeners stay
1042
+ * registered and keep the id of their last event for the next connection. Resolves on the close - or on an
1043
+ * error, as a transport that fails while closing may report only `error` (Node.js 22).
1044
+ */
1045
+ const closeWebsocket = (transport) => {
1046
+ websocket = void 0;
1047
+ releaseAll();
1048
+ if (transport.readyState === WebsocketReadyState.CLOSED) return Promise.resolve();
1049
+ return new Promise((resolve) => {
1050
+ transport.addEventListener("close", () => resolve(), { once: true });
1051
+ transport.addEventListener("error", () => resolve(), { once: true });
1052
+ try {
1053
+ transport.close(1e3);
1054
+ } catch {
1055
+ resolve();
1056
+ }
1057
+ });
1058
+ };
1059
+ const connection = createReconnectingConnection({
1060
+ bindings,
1061
+ autoConnect: adapter.adapterOptions?.autoConnect ?? true,
1062
+ open: (attempt) => {
1063
+ options = attempt.connection.adapterOptions;
1064
+ const transport = createWebsocket(getSocketUrl(attempt.connection.url, getQueryParams(attempt.connection.queryParams)));
1065
+ if (!transport) return null;
1066
+ transport.binaryType = "arraybuffer";
1067
+ websocket = transport;
1068
+ /** The transport is gone - report it and let the engine decide about the next attempt */
1069
+ const onTransportClosed = (event) => {
1070
+ attempt.lost({
1071
+ code: event.code,
1072
+ reason: event.reason || void 0
1073
+ });
1074
+ onError({ error: new Error(getSocketError(event)) });
1075
+ };
1076
+ transport.addEventListener("open", () => {
1077
+ attempt.ready();
1078
+ if (!attempt.isCurrent()) return;
1079
+ subscriptions.values().forEach((subscription) => {
1080
+ if (!subscription.transport) startSubscription(subscription);
1081
+ });
1082
+ });
1083
+ transport.addEventListener("close", (event) => {
1084
+ if (attempt.isCurrent()) onTransportClosed(event);
1085
+ });
1086
+ transport.addEventListener("error", () => {
1087
+ if (!attempt.isCurrent() || transport.readyState !== WebsocketReadyState.CONNECTING) return;
1088
+ onTransportClosed(Object.assign(new Event("close"), { code: 1006 }));
1089
+ });
1090
+ transport.addEventListener("message", (event) => {
1091
+ if (attempt.isCurrent()) handleMessage(event.data);
1092
+ });
1093
+ return { close: () => closeWebsocket(transport) };
1094
+ }
1095
+ });
1096
+ const emit = () => {
1097
+ throw new Error("Cannot emit events in the oRPC WebSocket adapter, it only receives events of subscriptions");
1098
+ };
1099
+ return {
1100
+ connect: connection.connect,
1101
+ reconnect: connection.reconnect,
1102
+ disconnect: connection.disconnect,
1103
+ listen: subscriptions.listen,
1104
+ emit,
1105
+ dispose: connection.dispose
1106
+ };
1107
+ });
1108
+ };
1109
+ //#endregion
1110
+ export { OrpcAdapter, OrpcMethods, OrpcSocketError, OrpcStreamAdapter, OrpcWebsocketAdapter, createOrpcSerializer, defaultTimeout, getOrpcAbortKey, getOrpcAdapter, getOrpcCallRequest, getOrpcHeaders, getOrpcHttpRequest, getOrpcRequestKey, getOrpcResult, getOrpcSubscriptionKey, maxGetUrlLength, orpcEndpointMapper, orpcExtra, reservedQueryParams };
281
1111
 
282
1112
  //# sourceMappingURL=index.mjs.map