@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.
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
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, 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
  };
@@ -277,6 +298,906 @@ 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, onConnect, onConnectFailed, onReconnect, onDisconnect, onConnected, onDisconnected } = bindings;
627
+ const autoConnect = adapter.adapterOptions?.autoConnect ?? true;
628
+ let connection;
629
+ let pendingConnection;
630
+ const subscriptions = createOrpcSubscriptions({
631
+ bindings,
632
+ serializer,
633
+ start: (subscription) => startStream(subscription, 0),
634
+ stop: (subscription) => stopStream(subscription),
635
+ release: (subscription) => stopStream(subscription)
636
+ });
637
+ /**
638
+ * Aborts the request or the wait of the subscription. Whatever the old request reports later is ignored.
639
+ * For a stream the server ended it only releases the response.
640
+ */
641
+ const stopStream = (subscription) => {
642
+ const { transport } = subscription;
643
+ subscription.transport = void 0;
644
+ subscription.started = false;
645
+ if (transport) {
646
+ clearTimeout(transport.timer);
647
+ transport.controller?.abort();
648
+ }
649
+ };
650
+ /** After a failure the stream starts again, after the `retry` of the last event or the socket reconnect time */
651
+ const scheduleRestart = (subscription, attempts) => {
652
+ if (attempts > socket.reconnectAttempts) {
653
+ subscriptions.end(subscription, /* @__PURE__ */ new Error(`Stopped restarting the stream of "${subscription.topic}" after ${attempts - 1} attempts`));
654
+ return;
655
+ }
656
+ const transport = {
657
+ controller: void 0,
658
+ timer: void 0,
659
+ attempts,
660
+ timedOut: false
661
+ };
662
+ transport.timer = setTimeout(() => {
663
+ if (socket.appManager.isOnline) startStream(subscription, attempts);
664
+ }, subscription.lastEventRetry ?? socket.reconnectTime);
665
+ subscription.transport = transport;
666
+ };
667
+ /** Returns `true` when the server ended the iterator */
668
+ const receiveMessage = (subscription, message) => {
669
+ try {
670
+ const event = getEventStreamIteratorEvent(message);
671
+ return event ? subscriptions.receive(subscription, event) : false;
672
+ } catch (error) {
673
+ subscriptions.report(subscription, error);
674
+ return false;
675
+ }
676
+ };
677
+ /**
678
+ * Reads the stream until the server ends it. Resolves the error of a call the server rejected, rejects when
679
+ * the transport failed - the network, the timeout or a stream cut in the middle of a message.
680
+ */
681
+ const readStream = async ({ subscription, transport, controller, details: { url, queryParams, adapterOptions } }) => {
682
+ const { headers, fetchOptions, fetch: customFetch } = adapterOptions ?? {};
683
+ const { lastEventId } = subscription;
684
+ const request = getOrpcCallRequest({
685
+ url,
686
+ endpoint: orpcEndpointMapper(subscription.topic),
687
+ queryParams: getQueryParams(queryParams),
688
+ headers: lastEventId === void 0 ? { ...headers } : {
689
+ ...headers,
690
+ "last-event-id": lastEventId
691
+ },
692
+ payload: subscription.payload,
693
+ method: "POST",
694
+ serializer
695
+ });
696
+ const response = await (customFetch ?? globalThis.fetch)(request.url, {
697
+ ...fetchOptions,
698
+ method: request.method,
699
+ headers: request.headers,
700
+ body: request.body,
701
+ signal: controller.signal
702
+ });
703
+ clearTimeout(transport.timer);
704
+ if (isORPCErrorStatus(response.status)) {
705
+ const body = parseResponse(await response.text());
706
+ return getOrpcResponseError({
707
+ status: response.status,
708
+ body,
709
+ serializer
710
+ });
711
+ }
712
+ if (!response.headers.get("content-type")?.startsWith("text/event-stream")) return getNotIteratorError(subscription.topic);
713
+ transport.attempts = 0;
714
+ if (subscription.transport === transport) subscriptions.confirm(subscription);
715
+ if (!response.body) return null;
716
+ const reader = response.body.getReader();
717
+ const textDecoder = new TextDecoder();
718
+ let ended = false;
719
+ const eventDecoder = createEventStreamDecoder((message) => {
720
+ if (!ended && subscription.transport === transport) ended = receiveMessage(subscription, message);
721
+ });
722
+ let chunk = await reader.read();
723
+ while (!chunk.done) {
724
+ eventDecoder.feed(textDecoder.decode(chunk.value, { stream: true }));
725
+ if (ended) return null;
726
+ chunk = await reader.read();
727
+ }
728
+ eventDecoder.feed(textDecoder.decode());
729
+ eventDecoder.end();
730
+ return null;
731
+ };
732
+ const startStream = (subscription, attempts) => {
733
+ const details = connection;
734
+ if (!details) return;
735
+ const controller = new AbortController();
736
+ const transport = {
737
+ controller,
738
+ timer: void 0,
739
+ attempts,
740
+ timedOut: false
741
+ };
742
+ subscription.transport = transport;
743
+ const isCurrent = () => subscription.transport === transport;
744
+ transport.timer = setTimeout(() => {
745
+ transport.timedOut = true;
746
+ controller.abort();
747
+ }, socket.connectionTimeout);
748
+ readStream({
749
+ subscription,
750
+ transport,
751
+ controller,
752
+ details
753
+ }).then((rejection) => {
754
+ if (!isCurrent()) return;
755
+ subscriptions.end(subscription, rejection ?? void 0);
756
+ }, (error) => {
757
+ if (!isCurrent()) return;
758
+ stopStream(subscription);
759
+ subscriptions.report(subscription, transport.timedOut ? /* @__PURE__ */ new Error(`The stream of "${subscription.topic}" did not open in ${socket.connectionTimeout}ms`) : error);
760
+ scheduleRestart(subscription, transport.attempts + 1);
761
+ });
762
+ };
763
+ const openConnection = async () => {
764
+ const details = await onConnect();
765
+ if (!details) return adapter.connected;
766
+ if (typeof (details.adapterOptions?.fetch ?? globalThis.fetch) !== "function") {
767
+ onConnectFailed({ error: /* @__PURE__ */ new Error("fetch is not available in this environment") });
768
+ return false;
769
+ }
770
+ connection = details;
771
+ onConnected();
772
+ [...subscriptions.values()].forEach((subscription) => {
773
+ if (!subscription.transport) startStream(subscription, 0);
774
+ });
775
+ return true;
776
+ };
777
+ const connect = () => {
778
+ if (adapter.connecting && pendingConnection) return pendingConnection;
779
+ const attempt = openConnection();
780
+ pendingConnection = attempt;
781
+ const release = () => {
782
+ if (pendingConnection === attempt) pendingConnection = void 0;
783
+ };
784
+ attempt.then(release, release);
785
+ return attempt;
786
+ };
787
+ /** Aborts every stream. Listeners stay registered and keep the id of their last event for the next connection. */
788
+ const closeConnection = async ({ manual }) => {
789
+ const wasActive = adapter.connected || adapter.connecting;
790
+ connection = void 0;
791
+ [...subscriptions.values()].forEach(stopStream);
792
+ onDisconnect();
793
+ if (!manual) adapter.setForceClosed(false);
794
+ if (wasActive) onDisconnected();
795
+ return true;
796
+ };
797
+ /** Manual disconnect - the socket stays closed until `connect()` or `reconnect()` is called */
798
+ const disconnect = () => {
799
+ return closeConnection({ manual: true });
800
+ };
801
+ const reconnect = async () => {
802
+ adapter.setForceClosed(false);
803
+ await onReconnect({
804
+ disconnect: () => closeConnection({ manual: false }),
805
+ connect: async () => {
806
+ if (adapter.forceClosed) {
807
+ adapter.setReconnectionAttempts(0);
808
+ return false;
809
+ }
810
+ return connect();
811
+ }
812
+ });
813
+ };
814
+ const emit = () => {
815
+ throw new Error("Cannot emit events in the oRPC stream adapter, it only receives events of subscriptions");
816
+ };
817
+ if (autoConnect) connect();
818
+ const unmountOnline = socket.appManager.events.onOnline(() => {
819
+ if (connection) {
820
+ [...subscriptions.values()].forEach((subscription) => {
821
+ const { transport } = subscription;
822
+ if (transport && !transport.controller) {
823
+ clearTimeout(transport.timer);
824
+ startStream(subscription, transport.attempts);
825
+ }
826
+ });
827
+ return;
828
+ }
829
+ if (autoConnect && !adapter.forceClosed) connect();
830
+ });
831
+ return {
832
+ connect,
833
+ reconnect,
834
+ disconnect,
835
+ listen: subscriptions.listen,
836
+ emit,
837
+ dispose: () => {
838
+ unmountOnline();
839
+ connection = void 0;
840
+ [...subscriptions.values()].forEach(stopStream);
841
+ }
842
+ };
843
+ });
844
+ };
845
+ //#endregion
846
+ //#region src/websocket-adapter/websocket-adapter.utils.ts
847
+ /** Message types of the oRPC peer protocol, used by `@orpc/server/ws` and `@orpc/client/websocket` */
848
+ var peerMessageType = {
849
+ REQUEST: 1,
850
+ RESPONSE: 2,
851
+ EVENT_ITERATOR: 3,
852
+ ABORT_SIGNAL: 4
853
+ };
854
+ /** JSON and binary parts of a binary frame are split by this byte */
855
+ var binaryDelimiter = 255;
856
+ var getMalformedError = (detail) => /* @__PURE__ */ new TypeError(`Invalid oRPC message: ${detail}`);
857
+ /**
858
+ * Starts the call of the procedure - the same request message as the `RPCLink` of `@orpc/client/websocket`.
859
+ * The input is serialized with the RPC serializer, inputs with files are not supported.
860
+ */
861
+ var encodeOrpcRequestMessage = ({ id, topic, payload, headers, serializer }) => {
862
+ const body = serializer.serialize(payload);
863
+ if (body instanceof FormData) throw new TypeError(`Files in the input of "${topic}" are not supported by the oRPC WebSocket adapter`);
864
+ return JSON.stringify({
865
+ i: id,
866
+ p: {
867
+ u: orpcEndpointMapper(topic),
868
+ b: body,
869
+ h: Object.keys(headers).length > 0 ? headers : void 0
870
+ }
871
+ });
872
+ };
873
+ /** Stops the call of the procedure, the server cancels its iterator */
874
+ var encodeOrpcAbortMessage = (id) => {
875
+ return JSON.stringify({
876
+ i: id,
877
+ t: peerMessageType.ABORT_SIGNAL
878
+ });
879
+ };
880
+ var readFrameText = (frame) => {
881
+ if (typeof frame === "string") return frame;
882
+ if (frame instanceof ArrayBuffer || ArrayBuffer.isView(frame)) {
883
+ const bytes = frame instanceof ArrayBuffer ? new Uint8Array(frame) : new Uint8Array(frame.buffer, frame.byteOffset, frame.byteLength);
884
+ const end = bytes.indexOf(binaryDelimiter);
885
+ return new TextDecoder().decode(end === -1 ? bytes : bytes.subarray(0, end));
886
+ }
887
+ throw getMalformedError("expected a text or a binary frame");
888
+ };
889
+ /** Reads a message of the server, the same as `decodeResponseMessage` of oRPC. Throws for malformed frames. */
890
+ var decodeOrpcResponseMessage = (frame) => {
891
+ const message = JSON.parse(readFrameText(frame));
892
+ if (!isRecord(message) || typeof message.i !== "string") throw getMalformedError("expected an object with the request id");
893
+ const { i: id, t: type, p: payload } = message;
894
+ if (type === peerMessageType.ABORT_SIGNAL) return {
895
+ id,
896
+ type: "abort"
897
+ };
898
+ if (!isRecord(payload)) throw getMalformedError("expected the payload object");
899
+ if (type === peerMessageType.EVENT_ITERATOR) {
900
+ const { e: event, d: data, m: meta } = payload;
901
+ if (event !== "message" && event !== "error" && event !== "done") throw getMalformedError(`unknown event "${String(event)}"`);
902
+ return {
903
+ id,
904
+ type: "event",
905
+ event: {
906
+ event,
907
+ data,
908
+ meta: isRecord(meta) ? meta : void 0
909
+ }
910
+ };
911
+ }
912
+ const { s: status = 200, h: headers = {}, b: body } = payload;
913
+ if (typeof status !== "number" || !isRecord(headers)) throw getMalformedError("expected the status and the headers of the response");
914
+ return {
915
+ id,
916
+ type: "response",
917
+ status,
918
+ headers,
919
+ body
920
+ };
921
+ };
922
+ var flattenHeader = (header) => {
923
+ if (typeof header === "string") return header;
924
+ return Array.isArray(header) && header.length > 0 ? header.join(", ") : void 0;
925
+ };
926
+ /** The same check as `isEventIteratorHeaders` of oRPC - an event stream that is not a file */
927
+ var isOrpcEventIteratorResponse = (headers) => {
928
+ return !!flattenHeader(headers["content-type"])?.startsWith("text/event-stream") && flattenHeader(headers["content-disposition"]) === void 0;
929
+ };
930
+ //#endregion
931
+ //#region src/websocket-adapter/websocket-adapter.ts
932
+ /**
933
+ * Socket adapter for the event iterators of oRPC over one WebSocket connection. It speaks the protocol of the
934
+ * `RPCHandler` of `@orpc/server/ws` (the same as `@orpc/client/websocket`): every subscription is a request on the
935
+ * shared connection, and its events arrive as messages of that request.
936
+ *
937
+ * The adapter only subscribes. Emitting, and calling regular procedures, is not supported - use `OrpcAdapter` for
938
+ * them. Listeners of the same procedure and input share one request, the last one to unsubscribe aborts it.
939
+ * After a reconnect every running subscription starts again with the id of its last event. A subscription starts
940
+ * (`onStart`) when the server answers with the event iterator, and ends (`onEnd`) when the iterator finishes, fails
941
+ * or the server rejects the call.
942
+ *
943
+ * @example
944
+ * const socket = new Socket({ url: "ws://localhost:3000", adapter: OrpcWebsocketAdapter() });
945
+ * const sdk = createSocketSdk<typeof socket, OrpcSocketSchema<typeof router>>(socket, { camelCaseToKebabCase: false });
946
+ *
947
+ * sdk.planet.onUpdate.$listener.setPayload({ id: 1 }).listen(({ data }) => console.log(data));
948
+ */
949
+ var OrpcWebsocketAdapter = ({ customJsonSerializers } = {}) => {
950
+ const serializer = createOrpcSerializer(customJsonSerializers);
951
+ return new SocketAdapter({
952
+ name: "orpc-websocket",
953
+ confirmsSubscriptions: true
954
+ }).setQueryParamsMapper(stringifyQueryParams).setConnector((bindings) => {
955
+ const { socket, adapter, getQueryParams, onConnect, onConnectFailed, onReconnect, onDisconnect, onConnected, onDisconnected, onError } = bindings;
956
+ const autoConnect = adapter.adapterOptions?.autoConnect ?? true;
957
+ let websocket;
958
+ let options;
959
+ let pendingConnection;
960
+ let timeout;
961
+ let lastRequestId = 0;
962
+ const requests = /* @__PURE__ */ new Map();
963
+ const subscriptions = createOrpcSubscriptions({
964
+ bindings,
965
+ serializer,
966
+ start: (subscription) => startSubscription(subscription),
967
+ stop: (subscription) => stopSubscription(subscription),
968
+ release: (subscription) => {
969
+ releaseSubscription(subscription);
970
+ }
971
+ });
972
+ /** Sends a frame of the subscription, reporting the failure instead of throwing */
973
+ const sendFrame = (subscription, target, frame) => {
974
+ try {
975
+ target.send(frame);
976
+ return true;
977
+ } catch (error) {
978
+ subscriptions.report(subscription, error);
979
+ return false;
980
+ }
981
+ };
982
+ const startSubscription = (subscription) => {
983
+ const current = websocket;
984
+ if (!current || !adapter.connected) return;
985
+ lastRequestId += 1;
986
+ const id = lastRequestId.toString(36);
987
+ const { lastEventId } = subscription;
988
+ const headers = lastEventId === void 0 ? { ...options?.headers } : {
989
+ ...options?.headers,
990
+ "last-event-id": lastEventId
991
+ };
992
+ let frame;
993
+ try {
994
+ frame = encodeOrpcRequestMessage({
995
+ id,
996
+ topic: subscription.topic,
997
+ payload: subscription.payload,
998
+ headers,
999
+ serializer
1000
+ });
1001
+ } catch (error) {
1002
+ subscriptions.end(subscription, error);
1003
+ return;
1004
+ }
1005
+ if (sendFrame(subscription, current, frame)) {
1006
+ subscription.transport = {
1007
+ id,
1008
+ websocket: current
1009
+ };
1010
+ requests.set(id, subscription);
1011
+ }
1012
+ };
1013
+ /** Forgets the request of the subscription. Messages that still come for it are ignored. */
1014
+ const releaseSubscription = (subscription) => {
1015
+ const { transport } = subscription;
1016
+ subscription.transport = void 0;
1017
+ subscription.started = false;
1018
+ if (transport) requests.delete(transport.id);
1019
+ return transport;
1020
+ };
1021
+ const stopSubscription = (subscription) => {
1022
+ const transport = releaseSubscription(subscription);
1023
+ if (transport) sendFrame(subscription, transport.websocket, encodeOrpcAbortMessage(transport.id));
1024
+ };
1025
+ /** The connection is gone and the server dropped every request with it */
1026
+ const releaseAll = () => {
1027
+ requests.forEach((subscription) => {
1028
+ subscription.transport = void 0;
1029
+ subscription.started = false;
1030
+ });
1031
+ requests.clear();
1032
+ };
1033
+ const handleResponse = (subscription, { status, headers, body }) => {
1034
+ if (isORPCErrorStatus(status)) {
1035
+ subscriptions.end(subscription, getOrpcResponseError({
1036
+ status,
1037
+ body,
1038
+ serializer
1039
+ }));
1040
+ return;
1041
+ }
1042
+ if (!isOrpcEventIteratorResponse(headers)) {
1043
+ subscriptions.end(subscription, getNotIteratorError(subscription.topic));
1044
+ return;
1045
+ }
1046
+ subscriptions.confirm(subscription);
1047
+ };
1048
+ const handleMessage = (frame) => {
1049
+ let message;
1050
+ try {
1051
+ message = decodeOrpcResponseMessage(frame);
1052
+ } catch (error) {
1053
+ onError({ error: new OrpcSocketError({
1054
+ cause: error,
1055
+ topic: null,
1056
+ payload: void 0
1057
+ }) });
1058
+ return;
1059
+ }
1060
+ const subscription = requests.get(message.id);
1061
+ if (!subscription || message.type === "abort") return;
1062
+ if (message.type === "response") {
1063
+ handleResponse(subscription, message);
1064
+ return;
1065
+ }
1066
+ subscriptions.receive(subscription, message.event);
1067
+ };
1068
+ /** Starts over after `delay` - the connection timeout while connecting, the reconnect delay after a loss */
1069
+ const scheduleReconnect = (delay = socket.reconnectTime) => {
1070
+ clearTimeout(timeout);
1071
+ timeout = setTimeout(() => {
1072
+ reconnect();
1073
+ }, delay);
1074
+ };
1075
+ const openConnection = async () => {
1076
+ const connection = await onConnect();
1077
+ if (!connection) return adapter.connected;
1078
+ clearTimeout(timeout);
1079
+ options = connection.adapterOptions;
1080
+ const url = getSocketUrl(connection.url, getQueryParams(connection.queryParams));
1081
+ const WebSocketConstructor = getWebsocketConstructor(options);
1082
+ if (!WebSocketConstructor) {
1083
+ onConnectFailed({ error: /* @__PURE__ */ new Error("WebSocket is not available in this environment") });
1084
+ return false;
1085
+ }
1086
+ let instance;
1087
+ try {
1088
+ instance = new WebSocketConstructor(url, options?.protocols);
1089
+ } catch (error) {
1090
+ onConnectFailed({ error: toError(error) });
1091
+ return false;
1092
+ }
1093
+ instance.binaryType = "arraybuffer";
1094
+ websocket = instance;
1095
+ const isCurrent = () => websocket === instance;
1096
+ scheduleReconnect(socket.connectionTimeout);
1097
+ return new Promise((resolve) => {
1098
+ instance.addEventListener("open", () => {
1099
+ clearTimeout(timeout);
1100
+ onConnected();
1101
+ [...subscriptions.values()].forEach((subscription) => {
1102
+ if (!subscription.transport) startSubscription(subscription);
1103
+ });
1104
+ resolve(true);
1105
+ });
1106
+ /** The transport is gone - report it and get the connection back unless it was closed normally */
1107
+ const onTransportClosed = (event) => {
1108
+ websocket = void 0;
1109
+ clearTimeout(timeout);
1110
+ releaseAll();
1111
+ onDisconnected();
1112
+ onError({ error: new Error(getSocketError(event)) });
1113
+ if (event.code !== 1e3) scheduleReconnect();
1114
+ };
1115
+ instance.addEventListener("close", (event) => {
1116
+ resolve(false);
1117
+ if (!isCurrent()) return;
1118
+ onTransportClosed(event);
1119
+ });
1120
+ instance.addEventListener("error", () => {
1121
+ if (!isCurrent() || instance.readyState !== WebsocketReadyState.CONNECTING) return;
1122
+ resolve(false);
1123
+ try {
1124
+ instance.close();
1125
+ } catch {}
1126
+ onTransportClosed(Object.assign(new Event("close"), { code: 1006 }));
1127
+ });
1128
+ instance.addEventListener("message", (event) => {
1129
+ if (isCurrent()) handleMessage(event.data);
1130
+ });
1131
+ });
1132
+ };
1133
+ const connect = () => {
1134
+ if (adapter.connecting && pendingConnection) return pendingConnection;
1135
+ const attempt = openConnection();
1136
+ pendingConnection = attempt;
1137
+ const release = () => {
1138
+ if (pendingConnection === attempt) pendingConnection = void 0;
1139
+ };
1140
+ attempt.then(release, release);
1141
+ return attempt;
1142
+ };
1143
+ /**
1144
+ * Closes the transport and resets the connection state. The server cancels every subscription of the
1145
+ * connection, the listeners stay registered and keep the id of their last event for the next connection.
1146
+ */
1147
+ const closeConnection = async ({ manual }) => {
1148
+ clearTimeout(timeout);
1149
+ const current = websocket;
1150
+ websocket = void 0;
1151
+ releaseAll();
1152
+ const wasActive = adapter.connected || adapter.connecting;
1153
+ onDisconnect();
1154
+ if (!manual) adapter.setForceClosed(false);
1155
+ if (wasActive) onDisconnected();
1156
+ if (!current) return true;
1157
+ return new Promise((resolve) => {
1158
+ current.addEventListener("close", () => resolve(true), { once: true });
1159
+ current.addEventListener("error", () => resolve(true), { once: true });
1160
+ current.close(1e3);
1161
+ });
1162
+ };
1163
+ /** Manual disconnect - the socket stays closed until `connect()` or `reconnect()` is called */
1164
+ const disconnect = () => {
1165
+ return closeConnection({ manual: true });
1166
+ };
1167
+ const reconnect = async () => {
1168
+ adapter.setForceClosed(false);
1169
+ await onReconnect({
1170
+ disconnect: () => closeConnection({ manual: false }),
1171
+ connect: async () => {
1172
+ if (adapter.forceClosed) {
1173
+ adapter.setReconnectionAttempts(0);
1174
+ return false;
1175
+ }
1176
+ return connect();
1177
+ }
1178
+ });
1179
+ };
1180
+ const emit = () => {
1181
+ throw new Error("Cannot emit events in the oRPC WebSocket adapter, it only receives events of subscriptions");
1182
+ };
1183
+ if (autoConnect) connect();
1184
+ const unmountOnline = socket.appManager.events.onOnline(() => {
1185
+ if (autoConnect && !adapter.connected && !adapter.forceClosed) connect();
1186
+ });
1187
+ return {
1188
+ connect,
1189
+ reconnect,
1190
+ disconnect,
1191
+ listen: subscriptions.listen,
1192
+ emit,
1193
+ dispose: () => {
1194
+ unmountOnline();
1195
+ clearTimeout(timeout);
1196
+ }
1197
+ };
1198
+ });
1199
+ };
1200
+ //#endregion
1201
+ export { OrpcAdapter, OrpcMethods, OrpcSocketError, OrpcStreamAdapter, OrpcWebsocketAdapter, createOrpcSerializer, defaultTimeout, getOrpcAbortKey, getOrpcAdapter, getOrpcCallRequest, getOrpcHeaders, getOrpcHttpRequest, getOrpcRequestKey, getOrpcResult, getOrpcSubscriptionKey, maxGetUrlLength, orpcEndpointMapper, orpcExtra, reservedQueryParams };
281
1202
 
282
1203
  //# sourceMappingURL=index.mjs.map