@orpc/client 2.0.0-beta.47 → 2.0.0-beta.49

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 (94) hide show
  1. package/README.md +6 -7
  2. package/dist/adapters/fetch/index.d.ts +2 -48
  3. package/dist/adapters/fetch/index.js +2 -0
  4. package/dist/adapters/fetch/rpc-link.d.ts +14 -0
  5. package/dist/adapters/fetch/rpc-link.js +14 -0
  6. package/dist/adapters/fetch/transport.d.ts +34 -0
  7. package/dist/adapters/fetch/transport.js +65 -0
  8. package/dist/adapters/message-port/index.d.ts +3 -80
  9. package/dist/adapters/message-port/index.js +3 -0
  10. package/dist/adapters/message-port/message-port.d.ts +29 -0
  11. package/dist/adapters/message-port/message-port.js +56 -0
  12. package/dist/adapters/message-port/rpc-link.d.ts +15 -0
  13. package/dist/adapters/message-port/rpc-link.js +15 -0
  14. package/dist/adapters/message-port/transport.d.ts +38 -0
  15. package/dist/adapters/message-port/transport.js +52 -0
  16. package/dist/adapters/standard/codec.d.ts +14 -0
  17. package/dist/adapters/standard/codec.js +1 -0
  18. package/dist/adapters/standard/index.d.ts +5 -60
  19. package/dist/adapters/standard/index.js +4 -0
  20. package/dist/adapters/standard/link.d.ts +40 -0
  21. package/dist/adapters/standard/link.js +85 -0
  22. package/dist/adapters/standard/plugin.d.ts +32 -0
  23. package/dist/adapters/standard/plugin.js +16 -0
  24. package/dist/adapters/standard/{index.d.mts → rpc-link-codec.d.ts} +17 -14
  25. package/dist/adapters/standard/rpc-link-codec.js +104 -0
  26. package/dist/adapters/standard/transport.d.ts +14 -0
  27. package/dist/adapters/standard/transport.js +1 -0
  28. package/dist/adapters/websocket/index.d.ts +2 -136
  29. package/dist/adapters/websocket/index.js +2 -0
  30. package/dist/adapters/websocket/rpc-link.d.ts +14 -0
  31. package/dist/adapters/websocket/rpc-link.js +14 -0
  32. package/dist/adapters/websocket/{index.d.mts → transport.d.ts} +32 -53
  33. package/dist/adapters/websocket/transport.js +133 -0
  34. package/dist/async-iterator-object.d.ts +2 -0
  35. package/dist/async-iterator-object.js +29 -0
  36. package/dist/client-safe.d.ts +18 -0
  37. package/dist/client-safe.js +36 -0
  38. package/dist/client.d.ts +40 -0
  39. package/dist/client.js +39 -0
  40. package/dist/consts.d.ts +10 -0
  41. package/dist/consts.js +43 -0
  42. package/dist/dynamic-link.d.ts +13 -0
  43. package/dist/dynamic-link.js +17 -0
  44. package/dist/error-utils.d.ts +21 -0
  45. package/dist/error-utils.js +58 -0
  46. package/dist/error.d.ts +132 -0
  47. package/dist/error.js +178 -0
  48. package/dist/index.d.ts +38 -129
  49. package/dist/index.js +40 -0
  50. package/dist/plugins/batch.d.ts +185 -0
  51. package/dist/plugins/batch.js +401 -0
  52. package/dist/plugins/cookie-jar.d.ts +82 -0
  53. package/dist/plugins/cookie-jar.js +268 -0
  54. package/dist/plugins/dedupe.d.ts +64 -0
  55. package/dist/plugins/dedupe.js +226 -0
  56. package/dist/plugins/index.d.ts +20 -412
  57. package/dist/plugins/index.js +23 -0
  58. package/dist/plugins/request-compression.d.ts +44 -0
  59. package/dist/plugins/request-compression.js +178 -0
  60. package/dist/plugins/response-compression.d.ts +28 -0
  61. package/dist/plugins/response-compression.js +91 -0
  62. package/dist/plugins/retry-after.d.ts +50 -0
  63. package/dist/plugins/retry-after.js +88 -0
  64. package/dist/plugins/retry.d.ts +84 -0
  65. package/dist/plugins/retry.js +140 -0
  66. package/dist/plugins/timeout.d.ts +25 -0
  67. package/dist/plugins/timeout.js +37 -0
  68. package/dist/{shared/client.DqIWeNhQ.d.mts → rpc-json-serializer.d.ts} +9 -41
  69. package/dist/rpc-json-serializer.js +392 -0
  70. package/dist/rpc-serializer.d.ts +32 -0
  71. package/dist/rpc-serializer.js +130 -0
  72. package/dist/types.d.ts +97 -0
  73. package/dist/types.js +1 -0
  74. package/dist/utils.d.ts +47 -0
  75. package/dist/utils.js +51 -0
  76. package/package.json +43 -45
  77. package/dist/adapters/fetch/index.d.mts +0 -48
  78. package/dist/adapters/fetch/index.mjs +0 -77
  79. package/dist/adapters/message-port/index.d.mts +0 -80
  80. package/dist/adapters/message-port/index.mjs +0 -101
  81. package/dist/adapters/standard/index.mjs +0 -6
  82. package/dist/adapters/websocket/index.mjs +0 -131
  83. package/dist/index.d.mts +0 -144
  84. package/dist/index.mjs +0 -147
  85. package/dist/plugins/index.d.mts +0 -420
  86. package/dist/plugins/index.mjs +0 -971
  87. package/dist/shared/client.BoHJeq15.d.mts +0 -233
  88. package/dist/shared/client.BoHJeq15.d.ts +0 -233
  89. package/dist/shared/client.CKQeJJ2U.mjs +0 -172
  90. package/dist/shared/client.DqIWeNhQ.d.ts +0 -131
  91. package/dist/shared/client.JBJwBhR8.d.ts +0 -90
  92. package/dist/shared/client.LF04eOvL.mjs +0 -115
  93. package/dist/shared/client._wG5INmC.mjs +0 -505
  94. package/dist/shared/client.euYjjcFz.d.mts +0 -90
@@ -0,0 +1,40 @@
1
+ import type { Interceptor } from '@orpc/shared';
2
+ import type { StandardLazyResponse, StandardRequest } from '@standard-server/core';
3
+ import type { ClientContext, ClientLink, ClientOptions } from '../../types.ts';
4
+ import type { StandardLinkCodec } from './codec.ts';
5
+ import type { StandardLinkPlugin } from './plugin.ts';
6
+ import type { StandardLinkTransport } from './transport.ts';
7
+ export interface StandardLinkInterceptorOptions<T extends ClientContext> extends ClientOptions<T> {
8
+ path: string[];
9
+ input: unknown;
10
+ }
11
+ export type StandardLinkInterceptor<T extends ClientContext> = Interceptor<StandardLinkInterceptorOptions<T>, Promise<unknown>>;
12
+ export interface StandardLinkTransportInterceptorOptions<T extends ClientContext> extends ClientOptions<T> {
13
+ path: string[];
14
+ request: StandardRequest;
15
+ }
16
+ export type StandardLinkTransportInterceptor<T extends ClientContext> = Interceptor<StandardLinkTransportInterceptorOptions<T>, Promise<StandardLazyResponse>>;
17
+ export interface StandardLinkOptions<T extends ClientContext> {
18
+ /**
19
+ * Interceptors that execute around the entire call, including transport and codec.
20
+ * Useful for error handling, logging, metrics, ...
21
+ */
22
+ interceptors?: StandardLinkInterceptor<T>[] | undefined;
23
+ /**
24
+ * Interceptors that execute around the transport layer, after encoding and before decoding.
25
+ * Useful for modifying the request or response, adding transport-level logging, ...
26
+ */
27
+ transportInterceptors?: StandardLinkTransportInterceptor<T>[] | undefined;
28
+ plugins?: StandardLinkPlugin<T>[] | undefined;
29
+ }
30
+ export declare class StandardLink<T extends ClientContext> implements ClientLink<T> {
31
+ private readonly codec;
32
+ private readonly transport;
33
+ private readonly interceptors;
34
+ private readonly transportInterceptors;
35
+ constructor(codec: StandardLinkCodec<T>, transport: StandardLinkTransport<T>, options?: StandardLinkOptions<T>);
36
+ /**
37
+ * @throws ORPCError, MalformedResponseError, transport-level errors (network failures, timeouts, etc.)
38
+ */
39
+ call(path: string[], input: unknown, options: ClientOptions<T>): Promise<unknown>;
40
+ }
@@ -0,0 +1,85 @@
1
+ import { getTracer, intercept, isAsyncIteratorObject, ORPC_NAME, override, runWithSpan, traceAsyncIterator, traceReadableStream, } from '@orpc/shared';
2
+ import { CompositeStandardLinkPlugin } from './plugin.js';
3
+ export class StandardLink {
4
+ codec;
5
+ transport;
6
+ interceptors;
7
+ transportInterceptors;
8
+ constructor(codec, transport, options = {}) {
9
+ this.codec = codec;
10
+ this.transport = transport;
11
+ options = new CompositeStandardLinkPlugin(options.plugins).init(options);
12
+ this.interceptors = options.interceptors;
13
+ this.transportInterceptors = options.transportInterceptors;
14
+ }
15
+ /**
16
+ * @throws ORPCError, MalformedResponseError, transport-level errors (network failures, timeouts, etc.)
17
+ */
18
+ call(path, input, options) {
19
+ return runWithSpan(`${ORPC_NAME}.${path.join('/')}`, (span) => {
20
+ /**
21
+ * [Semantic conventions for RPC spans](https://opentelemetry.io/docs/specs/semconv/rpc/rpc-spans/)
22
+ */
23
+ span?.setAttribute('rpc.system', ORPC_NAME);
24
+ span?.setAttribute('rpc.method', path.join('.'));
25
+ if (getTracer() && isAsyncIteratorObject(input)) {
26
+ /**
27
+ * @warning
28
+ * Remember use `override` for AsyncIteratorObject to remain other special properties
29
+ */
30
+ input = override(input, traceAsyncIterator('consume_async_iterator_object_input', input));
31
+ }
32
+ else if (getTracer() && input instanceof ReadableStream) {
33
+ /**
34
+ * @warning
35
+ * Remember use `override` for ReadableStream to remain other special properties
36
+ */
37
+ input = override(input, traceReadableStream('consume_octet_stream_input', input));
38
+ }
39
+ return intercept(this.interceptors, { ...options, path, input }, async ({ path, input, ...options }) => {
40
+ /**
41
+ * In browsers, the OpenTelemetry context manager may not work reliably with async functions,
42
+ * so we should manually pass the parent span here.
43
+ */
44
+ const tracer = getTracer();
45
+ const activeSpan = tracer?.getActiveSpan() ?? span;
46
+ let request = await runWithSpan({ name: 'encode_input', parent: activeSpan }, () => this.codec.encodeInput(input, path, options));
47
+ if (activeSpan && tracer?.inject) {
48
+ const headers = { ...request.headers };
49
+ tracer.inject(activeSpan, headers);
50
+ request = { ...request, headers };
51
+ }
52
+ const response = await intercept(this.transportInterceptors, { ...options, path, request }, ({ path, request, ...options }) => {
53
+ /**
54
+ * In browsers, the OpenTelemetry context manager may not work reliably with async functions,
55
+ * so we should manually pass the parent span here.
56
+ */
57
+ const activeTransportSpan = tracer?.getActiveSpan() ?? activeSpan;
58
+ return runWithSpan({ name: 'send_request', parent: activeTransportSpan }, () => this.transport.send(request, path, options));
59
+ });
60
+ const decodedResult = await runWithSpan({ name: 'decode_response', parent: activeSpan }, () => this.codec.decodeResponse(response, path, options));
61
+ if (decodedResult.kind === 'error') {
62
+ throw decodedResult.error;
63
+ }
64
+ const output = decodedResult.output;
65
+ if (getTracer() && isAsyncIteratorObject(output)) {
66
+ /**
67
+ * Do not pass the active span as parent here, as it is a lazy span.
68
+ *
69
+ * @warning
70
+ * Remember use `override` for AsyncIteratorObject to remain other special properties
71
+ */
72
+ return override(output, traceAsyncIterator('consume_async_iterator_object_output', output));
73
+ }
74
+ else if (getTracer() && output instanceof ReadableStream) {
75
+ /**
76
+ * @warning
77
+ * Remember use `override` for ReadableStream to remain other special properties
78
+ */
79
+ return override(output, traceReadableStream('consume_octet_stream_output', output));
80
+ }
81
+ return output;
82
+ });
83
+ });
84
+ }
85
+ }
@@ -0,0 +1,32 @@
1
+ import type { OrderablePlugin } from '@orpc/shared';
2
+ import type { ClientContext } from '../../types.ts';
3
+ import type { StandardLinkOptions } from './link.ts';
4
+ export interface StandardLinkPlugin<T extends ClientContext> extends OrderablePlugin {
5
+ /**
6
+ * Initializes the plugin and returns new link options.
7
+ * Called once per plugin instance during composition.
8
+ *
9
+ * This method allows plugins to wrap, extend, or transform link options
10
+ * such as interceptors, or configuration.
11
+ *
12
+ * @param options - The current link options from previous plugins or base configuration
13
+ * @returns Transformed link options with plugin's modifications applied
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * init(options) {
18
+ * return {
19
+ * ...options,
20
+ * interceptors: [...(options.interceptors || []), myInterceptor]
21
+ * }
22
+ * }
23
+ * ```
24
+ */
25
+ init?(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
26
+ }
27
+ export declare class CompositeStandardLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
28
+ name: string;
29
+ protected readonly plugins: StandardLinkPlugin<T>[];
30
+ constructor(plugins?: StandardLinkPlugin<T>[]);
31
+ init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
32
+ }
@@ -0,0 +1,16 @@
1
+ import { sortPlugins } from '@orpc/shared';
2
+ export class CompositeStandardLinkPlugin {
3
+ name = '~composite';
4
+ plugins;
5
+ constructor(plugins = []) {
6
+ this.plugins = sortPlugins(plugins);
7
+ }
8
+ init(options) {
9
+ for (const plugin of this.plugins) {
10
+ if (plugin.init) {
11
+ options = plugin.init(options);
12
+ }
13
+ }
14
+ return options;
15
+ }
16
+ }
@@ -1,11 +1,9 @@
1
- import { f as StandardLinkCodec, g as StandardLinkCodecDecodedResponse } from '../../shared/client.euYjjcFz.mjs';
2
- export { a as StandardLink, h as StandardLinkInterceptor, e as StandardLinkInterceptorOptions, b as StandardLinkOptions, c as StandardLinkPlugin, S as StandardLinkTransport, i as StandardLinkTransportInterceptor, d as StandardLinkTransportInterceptorOptions } from '../../shared/client.euYjjcFz.mjs';
3
- import { Value, Promisable, Public } from '@orpc/shared';
4
- import { StandardUrl, StandardHeaders, StandardRequest, StandardLazyResponse } from '@standard-server/core';
5
- import { ClientContext, ClientOptions } from '../../index.mjs';
6
- import { RPCSerializer } from '../../index.mjs';
7
-
8
- interface RPCLinkCodecOptions<T extends ClientContext> {
1
+ import type { Promisable, Public, Value } from '@orpc/shared';
2
+ import type { StandardHeaders, StandardLazyResponse, StandardRequest, StandardUrl } from '@standard-server/core';
3
+ import { RPCSerializer } from '../../rpc-serializer.ts';
4
+ import type { ClientContext, ClientOptions } from '../../types.ts';
5
+ import type { StandardLinkCodec, StandardLinkCodecDecodedResponse } from '../standard/index.ts';
6
+ export interface RPCLinkCodecOptions<T extends ClientContext> {
9
7
  /**
10
8
  * Base url for all requests (without origin). Should match with handler's prefix.
11
9
  *
@@ -27,7 +25,11 @@ interface RPCLinkCodecOptions<T extends ClientContext> {
27
25
  *
28
26
  * @default 'POST'
29
27
  */
30
- method?: Value<Promisable<'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'QUERY'>, [options: ClientOptions<T>, path: string[], input: unknown]> | undefined;
28
+ method?: Value<Promisable<'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'QUERY'>, [
29
+ options: ClientOptions<T>,
30
+ path: string[],
31
+ input: unknown
32
+ ]> | undefined;
31
33
  /**
32
34
  * The method to use when the payload cannot safely pass to the server with method return from method function.
33
35
  * GET is not allowed, it's very dangerous.
@@ -38,13 +40,17 @@ interface RPCLinkCodecOptions<T extends ClientContext> {
38
40
  /**
39
41
  * Inject headers to the request.
40
42
  */
41
- headers?: Value<Promisable<StandardHeaders | Headers>, [options: ClientOptions<T>, path: string[], input: unknown]> | undefined;
43
+ headers?: Value<Promisable<StandardHeaders | Headers>, [
44
+ options: ClientOptions<T>,
45
+ path: string[],
46
+ input: unknown
47
+ ]> | undefined;
42
48
  /**
43
49
  * Override the default RPC serializer.
44
50
  */
45
51
  serializer?: Public<RPCSerializer> | undefined;
46
52
  }
47
- declare class RPCLinkCodec<T extends ClientContext> implements StandardLinkCodec<T> {
53
+ export declare class RPCLinkCodec<T extends ClientContext> implements StandardLinkCodec<T> {
48
54
  private readonly baseUrl;
49
55
  private readonly maxUrlLength;
50
56
  private readonly fallbackMethod;
@@ -55,6 +61,3 @@ declare class RPCLinkCodec<T extends ClientContext> implements StandardLinkCodec
55
61
  encodeInput(input: unknown, path: string[], options: ClientOptions<T>): Promise<StandardRequest>;
56
62
  decodeResponse(response: StandardLazyResponse): Promise<StandardLinkCodecDecodedResponse>;
57
63
  }
58
-
59
- export { RPCLinkCodec, StandardLinkCodec, StandardLinkCodecDecodedResponse };
60
- export type { RPCLinkCodecOptions };
@@ -0,0 +1,104 @@
1
+ import { isAsyncIteratorObject, pathToHttpPath, stringifyJSON, value } from '@orpc/shared';
2
+ import { mergeStandardHeaders, parseStandardUrl } from '@standard-server/core';
3
+ import { toStandardHeaders } from '@standard-server/fetch';
4
+ import { createORPCErrorFromJson, isORPCErrorJson } from '../../error-utils.js';
5
+ import { MalformedResponseError, ResponseError } from '../../error.js';
6
+ import { RPCSerializer } from '../../rpc-serializer.js';
7
+ const END_SLASH_REGEX = /\/$/;
8
+ export class RPCLinkCodec {
9
+ baseUrl;
10
+ maxUrlLength;
11
+ fallbackMethod;
12
+ expectedMethod;
13
+ headers;
14
+ serializer;
15
+ constructor(options) {
16
+ this.baseUrl = options.url ?? '/';
17
+ this.maxUrlLength = options.maxUrlLength ?? 2083;
18
+ this.fallbackMethod = options.fallbackMethod ?? 'POST';
19
+ this.expectedMethod = options.method ?? this.fallbackMethod;
20
+ this.headers = options.headers ?? {};
21
+ this.serializer = options.serializer ?? new RPCSerializer();
22
+ }
23
+ async encodeInput(input, path, options) {
24
+ let headers = toResolvedStandardHeaders(await value(this.headers, options, path, input));
25
+ if (options.lastEventId !== undefined) {
26
+ headers = mergeStandardHeaders(headers, { 'last-event-id': options.lastEventId });
27
+ }
28
+ const expectedMethod = await value(this.expectedMethod, options, path, input);
29
+ const baseUrl = await value(this.baseUrl, options, path, input);
30
+ const [pathname, search, hash] = parseStandardUrl(baseUrl);
31
+ const newPathname = `${pathname.replace(END_SLASH_REGEX, '')}${pathToHttpPath(path)}`;
32
+ const serialized = this.serializer.serialize(input);
33
+ if (expectedMethod === 'GET' &&
34
+ !(serialized instanceof Blob) &&
35
+ !(serialized instanceof ReadableStream) &&
36
+ !(serialized instanceof FormData) &&
37
+ !isAsyncIteratorObject(serialized)) {
38
+ const maxUrlLength = await value(this.maxUrlLength, options, path, input);
39
+ const mergedSearch = new URLSearchParams(search);
40
+ mergedSearch.append('data', stringifyJSON(serialized) ?? '');
41
+ const url = `${newPathname}?${mergedSearch}${hash ?? ''}`;
42
+ if (url.length <= maxUrlLength) {
43
+ return {
44
+ body: undefined,
45
+ method: expectedMethod,
46
+ headers,
47
+ url,
48
+ signal: options.signal,
49
+ };
50
+ }
51
+ }
52
+ const url = `${newPathname}${search ?? ''}${hash ?? ''}`;
53
+ return {
54
+ url,
55
+ method: expectedMethod === 'GET' ? this.fallbackMethod : expectedMethod,
56
+ headers,
57
+ body: serialized,
58
+ signal: options.signal,
59
+ };
60
+ }
61
+ async decodeResponse(response) {
62
+ const isOk = response.status < 400;
63
+ const body = await response.resolveBody();
64
+ const deserialized = await (async () => {
65
+ try {
66
+ return this.serializer.deserialize(body);
67
+ }
68
+ catch (cause) {
69
+ throw new MalformedResponseError({
70
+ message: isOk ? 'Invalid RPC response format.' : undefined,
71
+ response: { status: response.status, headers: response.headers, body },
72
+ cause,
73
+ });
74
+ }
75
+ })();
76
+ if (!isOk) {
77
+ if (isORPCErrorJson(deserialized)) {
78
+ return {
79
+ kind: 'error',
80
+ error: createORPCErrorFromJson(deserialized, {
81
+ cause: new ResponseError({
82
+ response: { status: response.status, headers: response.headers, body },
83
+ }),
84
+ }),
85
+ };
86
+ }
87
+ throw new MalformedResponseError({
88
+ response: { headers: response.headers, status: response.status, body },
89
+ });
90
+ }
91
+ return { kind: 'output', output: deserialized };
92
+ }
93
+ }
94
+ function toResolvedStandardHeaders(headers) {
95
+ /**
96
+ * Headers class might not be available in some environments,
97
+ * so we check for the existence of `forEach` and `get`
98
+ * methods to determine if it's a Headers instance.
99
+ */
100
+ if (typeof headers.forEach === 'function') {
101
+ return toStandardHeaders(headers);
102
+ }
103
+ return headers;
104
+ }
@@ -0,0 +1,14 @@
1
+ import type { StandardLazyResponse, StandardRequest } from '@standard-server/core';
2
+ import type { ClientContext, ClientOptions } from '../../types.ts';
3
+ /**
4
+ * Handles the transport layer for sending requests and receiving responses.
5
+ *
6
+ * Implementations are responsible for the actual network communication,
7
+ * such as HTTP fetch, WebSocket, or other transport mechanisms.
8
+ */
9
+ export interface StandardLinkTransport<T extends ClientContext> {
10
+ /**
11
+ * @throws Transport-level errors (network failures, timeouts, etc.)
12
+ */
13
+ send(request: StandardRequest, path: string[], options: ClientOptions<T>): Promise<StandardLazyResponse>;
14
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,136 +1,2 @@
1
- import { ClientContext, ClientOptions } from '../../index.js';
2
- import { Promisable } from '@orpc/shared';
3
- import { StandardRequest, StandardLazyResponse } from '@standard-server/core';
4
- import { EncodePeerMessageOptions, DecodePeerMessageOptions } from '@standard-server/peer';
5
- import { StandardLinkTransport, StandardLink, StandardLinkOptions } from '../standard/index.js';
6
- import { RPCLinkCodecOptions } from '../standard/index.js';
7
- import '../../shared/client.DqIWeNhQ.js';
8
-
9
- type WebSocketLike = Pick<WebSocket, 'addEventListener' | 'removeEventListener' | 'send' | 'readyState'>;
10
- interface WebSocketLinkTransportAttemptInfo {
11
- /**
12
- * Total number of connection attempts for this transport's lifetime.
13
- * Starts at 1 on the first attempt, increments on every subsequent
14
- * attempt, and never resets.
15
- */
16
- totalAttempt: number;
17
- /**
18
- * Attempt number within the current (re)connect cycle.
19
- * Starts at 1, increments on each consecutive failure, and resets to 1
20
- * once a connection succeeds or the cycle gives up. Use this for backoff calculations.
21
- */
22
- attempt: number;
23
- }
24
- interface WebSocketLinkTransportReconnectOptions {
25
- /**
26
- * Whether to automatically reconnect when the connection is lost.
27
- *
28
- * @default false
29
- */
30
- enabled: boolean;
31
- /**
32
- * Delay before a (re)connect attempt, in milliseconds.
33
- *
34
- * @default info => info.attempt === 1 ? 0 : 2_000
35
- */
36
- delay?: ((info: WebSocketLinkTransportAttemptInfo) => number) | undefined;
37
- /**
38
- * Maximum number of consecutive failed attempts before giving up.
39
- * When reached, calls waiting for the connection fail, and the next
40
- * call starts a new reconnect cycle.
41
- * Should greater than 1
42
- *
43
- * @default Infinity
44
- */
45
- maxAttempt?: number | undefined;
46
- /**
47
- * Maximum number of connection attempts over the transport's lifetime,
48
- * successful ones included (see `totalAttempt`).
49
- * When reached, calls that need a new connection fail instead of connecting.
50
- *
51
- * @default Infinity
52
- */
53
- maxTotalAttempt?: number | undefined;
54
- /**
55
- * Whether to proactively reconnect right after the socket closes,
56
- * rather than waiting for the next call to trigger reconnection.
57
- * Reduces latency for the next request.
58
- *
59
- * @default { enabled: false }
60
- */
61
- onClose?: {
62
- /**
63
- * Whether to proactively reconnect right after the socket closes,
64
- * rather than waiting for the next call to trigger reconnection.
65
- * Reduces latency for the next request.
66
- *
67
- * @default false
68
- */
69
- enabled: boolean;
70
- /**
71
- * Delay before reconnecting after the socket closes, in milliseconds.
72
- *
73
- * @default 0
74
- */
75
- delay?: number | undefined;
76
- } | undefined;
77
- }
78
- interface WebSocketLinkTransportOptions<_T extends ClientContext> {
79
- /**
80
- * Returns a WebSocket instance for peer communication.
81
- * Can be async for lazy resolution.
82
- */
83
- connect: (info: WebSocketLinkTransportAttemptInfo) => Promisable<WebSocketLike>;
84
- /**
85
- * Whether to connect immediately on initialization, instead of waiting
86
- * for the first call. Reduces latency for the first request.
87
- *
88
- * @default false
89
- */
90
- connectOnInit?: boolean | undefined;
91
- /**
92
- * Reconnection behavior when the connection is lost.
93
- *
94
- * @default { enabled: false }
95
- */
96
- reconnect?: WebSocketLinkTransportReconnectOptions | undefined;
97
- /**
98
- * Options for encoding peer messages. such as `prefix` for distinguishing messages on the same channel..
99
- */
100
- encodePeerMessage?: EncodePeerMessageOptions | undefined;
101
- /**
102
- * Options for decoding peer messages. such as `prefix` for distinguishing messages on the same channel..
103
- */
104
- decodePeerMessage?: DecodePeerMessageOptions | undefined;
105
- }
106
- declare class WebSocketLinkTransport<T extends ClientContext> implements StandardLinkTransport<T> {
107
- private readonly connect;
108
- private readonly reconnectEnabled;
109
- private readonly reconnectDelay;
110
- private readonly reconnectMaxAttempt;
111
- private readonly reconnectMaxTotalAttempt;
112
- private readonly reconnectOnCloseEnabled;
113
- private readonly reconnectOnCloseDelay;
114
- private readonly encodePeerMessageOptions;
115
- private readonly decodePeerMessageOptions;
116
- constructor(options: WebSocketLinkTransportOptions<T>);
117
- send(standardRequest: StandardRequest, _path: string[], _options: ClientOptions<T>): Promise<StandardLazyResponse>;
118
- private totalAttempt;
119
- private attempt;
120
- private current;
121
- private getConnectedPeer;
122
- }
123
-
124
- interface RPCLinkOptions<T extends ClientContext> extends StandardLinkOptions<T>, WebSocketLinkTransportOptions<T>, RPCLinkCodecOptions<T> {
125
- }
126
- /**
127
- * Client link that communicates with an RPC Handler over a WebSocket connection.
128
- *
129
- * @see {@link https://orpc.dev/docs/adapters/websocket | WebSocket Adapters}
130
- */
131
- declare class RPCLink<T extends ClientContext> extends StandardLink<T> {
132
- constructor(options: RPCLinkOptions<T>);
133
- }
134
-
135
- export { RPCLink, WebSocketLinkTransport };
136
- export type { RPCLinkOptions, WebSocketLike, WebSocketLinkTransportAttemptInfo, WebSocketLinkTransportOptions, WebSocketLinkTransportReconnectOptions };
1
+ export * from './rpc-link.ts';
2
+ export * from './transport.ts';
@@ -0,0 +1,2 @@
1
+ export * from './rpc-link.js';
2
+ export * from './transport.js';
@@ -0,0 +1,14 @@
1
+ import type { ClientContext } from '../../types.ts';
2
+ import type { RPCLinkCodecOptions, StandardLinkOptions } from '../standard/index.ts';
3
+ import { StandardLink } from '../standard/index.ts';
4
+ import type { WebSocketLinkTransportOptions } from './transport.ts';
5
+ export interface RPCLinkOptions<T extends ClientContext> extends StandardLinkOptions<T>, WebSocketLinkTransportOptions<T>, RPCLinkCodecOptions<T> {
6
+ }
7
+ /**
8
+ * Client link that communicates with an RPC Handler over a WebSocket connection.
9
+ *
10
+ * @see {@link https://orpc.dev/docs/adapters/websocket | WebSocket Adapters}
11
+ */
12
+ export declare class RPCLink<T extends ClientContext> extends StandardLink<T> {
13
+ constructor(options: RPCLinkOptions<T>);
14
+ }
@@ -0,0 +1,14 @@
1
+ import { RPCLinkCodec, StandardLink } from '../standard/index.js';
2
+ import { WebSocketLinkTransport } from './transport.js';
3
+ /**
4
+ * Client link that communicates with an RPC Handler over a WebSocket connection.
5
+ *
6
+ * @see {@link https://orpc.dev/docs/adapters/websocket | WebSocket Adapters}
7
+ */
8
+ export class RPCLink extends StandardLink {
9
+ constructor(options) {
10
+ const codec = new RPCLinkCodec(options);
11
+ const transport = new WebSocketLinkTransport(options);
12
+ super(codec, transport, options);
13
+ }
14
+ }
@@ -1,13 +1,10 @@
1
- import { ClientContext, ClientOptions } from '../../index.mjs';
2
- import { Promisable } from '@orpc/shared';
3
- import { StandardRequest, StandardLazyResponse } from '@standard-server/core';
4
- import { EncodePeerMessageOptions, DecodePeerMessageOptions } from '@standard-server/peer';
5
- import { StandardLinkTransport, StandardLink, StandardLinkOptions } from '../standard/index.mjs';
6
- import { RPCLinkCodecOptions } from '../standard/index.mjs';
7
- import '../../shared/client.DqIWeNhQ.mjs';
8
-
9
- type WebSocketLike = Pick<WebSocket, 'addEventListener' | 'removeEventListener' | 'send' | 'readyState'>;
10
- interface WebSocketLinkTransportAttemptInfo {
1
+ import type { Promisable } from '@orpc/shared';
2
+ import type { StandardLazyResponse, StandardRequest } from '@standard-server/core';
3
+ import type { DecodePeerMessageOptions, EncodePeerMessageOptions } from '@standard-server/peer';
4
+ import type { ClientContext, ClientOptions } from '../../types.ts';
5
+ import type { StandardLinkTransport } from '../standard/index.ts';
6
+ export type WebSocketLike = Pick<WebSocket, 'addEventListener' | 'removeEventListener' | 'send' | 'readyState'>;
7
+ export interface WebSocketLinkTransportAttemptInfo {
11
8
  /**
12
9
  * Total number of connection attempts for this transport's lifetime.
13
10
  * Starts at 1 on the first attempt, increments on every subsequent
@@ -21,13 +18,10 @@ interface WebSocketLinkTransportAttemptInfo {
21
18
  */
22
19
  attempt: number;
23
20
  }
24
- interface WebSocketLinkTransportReconnectOptions {
25
- /**
26
- * Whether to automatically reconnect when the connection is lost.
27
- *
28
- * @default false
29
- */
30
- enabled: boolean;
21
+ /**
22
+ * Reconnection behavior when the connection is lost. Passing it enables reconnection.
23
+ */
24
+ export interface WebSocketLinkTransportReconnectOptions {
31
25
  /**
32
26
  * Delay before a (re)connect attempt, in milliseconds.
33
27
  *
@@ -56,26 +50,24 @@ interface WebSocketLinkTransportReconnectOptions {
56
50
  * rather than waiting for the next call to trigger reconnection.
57
51
  * Reduces latency for the next request.
58
52
  *
59
- * @default { enabled: false }
53
+ * `true` enables it, {@link WebSocketLinkTransportReconnectOnCloseOptions} enables and customizes it.
54
+ *
55
+ * @default false
60
56
  */
61
- onClose?: {
62
- /**
63
- * Whether to proactively reconnect right after the socket closes,
64
- * rather than waiting for the next call to trigger reconnection.
65
- * Reduces latency for the next request.
66
- *
67
- * @default false
68
- */
69
- enabled: boolean;
70
- /**
71
- * Delay before reconnecting after the socket closes, in milliseconds.
72
- *
73
- * @default 0
74
- */
75
- delay?: number | undefined;
76
- } | undefined;
57
+ onClose?: boolean | WebSocketLinkTransportReconnectOnCloseOptions | undefined;
77
58
  }
78
- interface WebSocketLinkTransportOptions<_T extends ClientContext> {
59
+ /**
60
+ * Proactive reconnection right after the socket closes. Passing it enables it.
61
+ */
62
+ export interface WebSocketLinkTransportReconnectOnCloseOptions {
63
+ /**
64
+ * Delay before reconnecting after the socket closes, in milliseconds.
65
+ *
66
+ * @default 0
67
+ */
68
+ delay?: number | undefined;
69
+ }
70
+ export interface WebSocketLinkTransportOptions<_T extends ClientContext> {
79
71
  /**
80
72
  * Returns a WebSocket instance for peer communication.
81
73
  * Can be async for lazy resolution.
@@ -89,11 +81,12 @@ interface WebSocketLinkTransportOptions<_T extends ClientContext> {
89
81
  */
90
82
  connectOnInit?: boolean | undefined;
91
83
  /**
92
- * Reconnection behavior when the connection is lost.
84
+ * Reconnection when the connection is lost. `true` enables it,
85
+ * {@link WebSocketLinkTransportReconnectOptions} enables and customizes it.
93
86
  *
94
- * @default { enabled: false }
87
+ * @default false
95
88
  */
96
- reconnect?: WebSocketLinkTransportReconnectOptions | undefined;
89
+ reconnect?: boolean | WebSocketLinkTransportReconnectOptions | undefined;
97
90
  /**
98
91
  * Options for encoding peer messages. such as `prefix` for distinguishing messages on the same channel..
99
92
  */
@@ -103,7 +96,7 @@ interface WebSocketLinkTransportOptions<_T extends ClientContext> {
103
96
  */
104
97
  decodePeerMessage?: DecodePeerMessageOptions | undefined;
105
98
  }
106
- declare class WebSocketLinkTransport<T extends ClientContext> implements StandardLinkTransport<T> {
99
+ export declare class WebSocketLinkTransport<T extends ClientContext> implements StandardLinkTransport<T> {
107
100
  private readonly connect;
108
101
  private readonly reconnectEnabled;
109
102
  private readonly reconnectDelay;
@@ -120,17 +113,3 @@ declare class WebSocketLinkTransport<T extends ClientContext> implements Standar
120
113
  private current;
121
114
  private getConnectedPeer;
122
115
  }
123
-
124
- interface RPCLinkOptions<T extends ClientContext> extends StandardLinkOptions<T>, WebSocketLinkTransportOptions<T>, RPCLinkCodecOptions<T> {
125
- }
126
- /**
127
- * Client link that communicates with an RPC Handler over a WebSocket connection.
128
- *
129
- * @see {@link https://orpc.dev/docs/adapters/websocket | WebSocket Adapters}
130
- */
131
- declare class RPCLink<T extends ClientContext> extends StandardLink<T> {
132
- constructor(options: RPCLinkOptions<T>);
133
- }
134
-
135
- export { RPCLink, WebSocketLinkTransport };
136
- export type { RPCLinkOptions, WebSocketLike, WebSocketLinkTransportAttemptInfo, WebSocketLinkTransportOptions, WebSocketLinkTransportReconnectOptions };