@orpc/client 2.0.0-beta.5 → 2.0.0-beta.51

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 +139 -102
  2. package/dist/adapters/fetch/index.d.ts +3 -65
  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 +17 -0
  6. package/dist/adapters/fetch/transport.d.ts +32 -0
  7. package/dist/adapters/fetch/transport.js +51 -0
  8. package/dist/adapters/message-port/index.d.ts +4 -75
  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 +38 -0
  12. package/dist/adapters/message-port/rpc-link.d.ts +15 -0
  13. package/dist/adapters/message-port/rpc-link.js +18 -0
  14. package/dist/adapters/message-port/transport.d.ts +35 -0
  15. package/dist/adapters/message-port/transport.js +38 -0
  16. package/dist/adapters/standard/codec.d.ts +14 -0
  17. package/dist/adapters/standard/index.d.ts +6 -61
  18. package/dist/adapters/standard/index.js +2 -0
  19. package/dist/adapters/standard/link.d.ts +40 -0
  20. package/dist/adapters/standard/link.js +101 -0
  21. package/dist/adapters/standard/plugin.d.ts +26 -0
  22. package/dist/adapters/standard/plugin.js +14 -0
  23. package/dist/adapters/standard/rpc-link-codec.d.ts +56 -0
  24. package/dist/adapters/standard/rpc-link-codec.js +100 -0
  25. package/dist/adapters/standard/transport.d.ts +14 -0
  26. package/dist/adapters/websocket/index.d.ts +3 -121
  27. package/dist/adapters/websocket/index.js +2 -0
  28. package/dist/adapters/websocket/rpc-link.d.ts +14 -0
  29. package/dist/adapters/websocket/rpc-link.js +17 -0
  30. package/dist/adapters/websocket/transport.d.ts +116 -0
  31. package/dist/adapters/websocket/transport.js +105 -0
  32. package/dist/async-iterator-object.d.ts +2 -0
  33. package/dist/async-iterator-object.js +28 -0
  34. package/dist/client-safe.d.ts +17 -0
  35. package/dist/client-safe.js +31 -0
  36. package/dist/client.d.ts +39 -0
  37. package/dist/client.js +37 -0
  38. package/dist/consts.d.ts +10 -0
  39. package/dist/consts.js +20 -0
  40. package/dist/dynamic-link.d.ts +13 -0
  41. package/dist/dynamic-link.js +17 -0
  42. package/dist/error-utils.d.ts +20 -0
  43. package/dist/error-utils.js +54 -0
  44. package/dist/error.d.ts +141 -0
  45. package/dist/error.js +166 -0
  46. package/dist/index.d.ts +14 -155
  47. package/dist/index.js +12 -0
  48. package/dist/plugins/batch.d.ts +152 -0
  49. package/dist/plugins/batch.js +330 -0
  50. package/dist/plugins/cookie-jar.d.ts +85 -0
  51. package/dist/plugins/cookie-jar.js +231 -0
  52. package/dist/plugins/dedupe.d.ts +60 -0
  53. package/dist/plugins/dedupe.js +183 -0
  54. package/dist/plugins/index.d.ts +9 -242
  55. package/dist/plugins/index.js +8 -0
  56. package/dist/plugins/request-compression.d.ts +47 -0
  57. package/dist/plugins/request-compression.js +132 -0
  58. package/dist/plugins/response-compression.d.ts +31 -0
  59. package/dist/plugins/response-compression.js +67 -0
  60. package/dist/plugins/retry-after.d.ts +43 -0
  61. package/dist/plugins/retry-after.js +63 -0
  62. package/dist/plugins/retry.d.ts +84 -0
  63. package/dist/plugins/retry.js +121 -0
  64. package/dist/plugins/timeout.d.ts +27 -0
  65. package/dist/plugins/timeout.js +42 -0
  66. package/dist/rpc-json-serializer.d.ts +99 -0
  67. package/dist/rpc-json-serializer.js +347 -0
  68. package/dist/rpc-serializer.d.ts +31 -0
  69. package/dist/rpc-serializer.js +102 -0
  70. package/dist/types.d.ts +91 -0
  71. package/dist/utils.d.ts +36 -0
  72. package/dist/utils.js +67 -0
  73. package/package.json +47 -35
  74. package/dist/adapters/fetch/index.d.mts +0 -65
  75. package/dist/adapters/fetch/index.mjs +0 -68
  76. package/dist/adapters/message-port/index.d.mts +0 -75
  77. package/dist/adapters/message-port/index.mjs +0 -91
  78. package/dist/adapters/standard/index.d.mts +0 -61
  79. package/dist/adapters/standard/index.mjs +0 -6
  80. package/dist/adapters/websocket/index.d.mts +0 -121
  81. package/dist/adapters/websocket/index.mjs +0 -110
  82. package/dist/index.d.mts +0 -155
  83. package/dist/index.mjs +0 -154
  84. package/dist/plugins/index.d.mts +0 -242
  85. package/dist/plugins/index.mjs +0 -574
  86. package/dist/shared/client.8ug8I-zu.d.mts +0 -167
  87. package/dist/shared/client.8ug8I-zu.d.ts +0 -167
  88. package/dist/shared/client.BdItY5DT.d.mts +0 -111
  89. package/dist/shared/client.BdItY5DT.d.ts +0 -111
  90. package/dist/shared/client.CPF3hX6O.d.ts +0 -96
  91. package/dist/shared/client.Cby_-GGh.d.mts +0 -96
  92. package/dist/shared/client.DMXKFDyV.mjs +0 -343
  93. package/dist/shared/client.DXhchJ84.mjs +0 -174
  94. package/dist/shared/client.Dnfj8jnT.mjs +0 -92
@@ -0,0 +1,84 @@
1
+ import "../adapters/standard/index.js";
2
+ import { StandardLinkPlugin } from "../adapters/standard/plugin.js";
3
+ import { StandardLinkInterceptorOptions, StandardLinkOptions } from "../adapters/standard/link.js";
4
+ import { ClientContext } from "../types.js";
5
+ import { Promisable, Value } from "@orpc/shared";
6
+ export interface RetryLinkPluginAttemptOptions<T extends RetryLinkPluginContext> extends StandardLinkInterceptorOptions<T> {
7
+ /**
8
+ * Latest retry delay advertised by the server via event metadata.
9
+ */
10
+ lastEventRetry: number | undefined;
11
+ /**
12
+ * Current retry attempt number, starting at 1.
13
+ */
14
+ attempt: number;
15
+ /**
16
+ * Error that triggered this retry attempt.
17
+ */
18
+ error: unknown;
19
+ }
20
+ /**
21
+ * Client context options that control retry behavior per call
22
+ * when the `RetryLinkPlugin` is enabled.
23
+ *
24
+ * @see {@link https://orpc.dev/docs/plugins/retry | Retry Plugin}
25
+ */
26
+ export interface RetryLinkPluginContext {
27
+ /**
28
+ * Maximum retry attempts before throwing.
29
+ * Use `Number.POSITIVE_INFINITY` for infinite retries (e.g. for AsyncIteratorObject).
30
+ *
31
+ * @default 0
32
+ */
33
+ retry?: Value<Promisable<number>, [Omit<StandardLinkInterceptorOptions<RetryLinkPluginContext>, "next">]> | undefined;
34
+ /**
35
+ * Delay (in ms) before retrying.
36
+ *
37
+ * @remarks
38
+ * **Note**: Why 2000ms? The EventSource spec suggests a default retry delay of 2 seconds if it doesn't specify
39
+ *
40
+ * @default (o) => o.lastEventRetry ?? 2000
41
+ */
42
+ retryDelay?: Value<Promisable<number>, [RetryLinkPluginAttemptOptions<RetryLinkPluginContext>]> | undefined;
43
+ /**
44
+ * Determine whether to retry.
45
+ *
46
+ * @default (o) => isRetryableError(o.error)
47
+ */
48
+ shouldRetry?: Value<Promisable<boolean>, [RetryLinkPluginAttemptOptions<RetryLinkPluginContext>]> | undefined;
49
+ /**
50
+ * Hook called before each retry. Can return a cleanup callback.
51
+ */
52
+ onRetry?: ((options: RetryLinkPluginAttemptOptions<RetryLinkPluginContext>) => void | ((isSuccess: boolean) => void)) | undefined;
53
+ }
54
+ export interface RetryLinkPluginOptions<_T extends RetryLinkPluginContext> {
55
+ /**
56
+ * Default retry options. Can be overridden by individual calls via the context.
57
+ */
58
+ default?: RetryLinkPluginContext | undefined;
59
+ }
60
+ /**
61
+ * Default `shouldRetry` check of `RetryLinkPlugin`. Returns `false` only for errors
62
+ * from a 4xx response other than `408` and `429`.
63
+ *
64
+ * @see {@link https://orpc.dev/docs/plugins/retry#client-error-responses | Retry Plugin - Client Error Responses}
65
+ */
66
+ export declare function isRetryableError(error: unknown): boolean;
67
+ /**
68
+ * Automatically retries failed requests based on customizable retry strategies,
69
+ * improving the resilience of your application.
70
+ *
71
+ * @remarks
72
+ * **Note**: Retry behavior is configured through the client context on each call.
73
+ *
74
+ * @see {@link https://orpc.dev/docs/plugins/retry | Retry Plugin}
75
+ */
76
+ export declare class RetryLinkPlugin<T extends RetryLinkPluginContext & ClientContext> implements StandardLinkPlugin<T> {
77
+ private readonly defaultRetry;
78
+ private readonly defaultRetryDelay;
79
+ private readonly defaultShouldRetry;
80
+ private readonly defaultOnRetry;
81
+ name: string;
82
+ constructor(options?: RetryLinkPluginOptions<T>);
83
+ init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
84
+ }
@@ -0,0 +1,121 @@
1
+ import { COMMON_ERROR_STATUS_MAP, ORPCError, ResponseError } from "../error.js";
2
+ import { AsyncIteratorClass, isAsyncIteratorObject, override, sleep, toArray, value } from "@orpc/shared";
3
+ import { getEventMeta } from "@standard-server/core";
4
+ // src/plugins/retry.ts
5
+ /**
6
+ * Default `shouldRetry` check of `RetryLinkPlugin`. Returns `false` only for errors
7
+ * from a 4xx response other than `408` and `429`.
8
+ *
9
+ * @see {@link https://orpc.dev/docs/plugins/retry#client-error-responses | Retry Plugin - Client Error Responses}
10
+ */
11
+ function isRetryableError(error) {
12
+ const responseError = error instanceof ORPCError ? error.cause : error;
13
+ if (!(responseError instanceof ResponseError)) return true;
14
+ const { status } = responseError.response;
15
+ return status < 400 || status >= 500 || status === COMMON_ERROR_STATUS_MAP.TIMEOUT || status === COMMON_ERROR_STATUS_MAP.TOO_MANY_REQUESTS;
16
+ }
17
+ /**
18
+ * Automatically retries failed requests based on customizable retry strategies,
19
+ * improving the resilience of your application.
20
+ *
21
+ * @remarks
22
+ * **Note**: Retry behavior is configured through the client context on each call.
23
+ *
24
+ * @see {@link https://orpc.dev/docs/plugins/retry | Retry Plugin}
25
+ */
26
+ var RetryLinkPlugin = class {
27
+ defaultRetry;
28
+ defaultRetryDelay;
29
+ defaultShouldRetry;
30
+ defaultOnRetry;
31
+ name = "~retry";
32
+ constructor(options = {}) {
33
+ this.defaultRetry = options.default?.retry ?? 0;
34
+ this.defaultRetryDelay = options.default?.retryDelay ?? ((o) => o.lastEventRetry ?? 2e3);
35
+ this.defaultShouldRetry = options.default?.shouldRetry ?? ((o) => isRetryableError(o.error));
36
+ this.defaultOnRetry = options.default?.onRetry;
37
+ }
38
+ init(options) {
39
+ const interceptor = async (interceptorOptions) => {
40
+ const { next, ...callOptions } = interceptorOptions;
41
+ const maxAttempts = await value(callOptions.context.retry ?? this.defaultRetry, callOptions);
42
+ const retryDelay = callOptions.context.retryDelay ?? this.defaultRetryDelay;
43
+ const shouldRetry = callOptions.context.shouldRetry ?? this.defaultShouldRetry;
44
+ const onRetry = callOptions.context.onRetry ?? this.defaultOnRetry;
45
+ if (maxAttempts <= 0) return next(callOptions);
46
+ let lastEventId = callOptions.lastEventId;
47
+ let lastEventRetry;
48
+ let callback;
49
+ let attempt = 1;
50
+ let isIteratorAborted = false;
51
+ const callNext = async (initialError) => {
52
+ let currentError = initialError;
53
+ while (true) {
54
+ const updatedCallOptions = {
55
+ ...callOptions,
56
+ lastEventId
57
+ };
58
+ let retryDelayMs = 0;
59
+ if (currentError) {
60
+ if (isIteratorAborted || attempt > maxAttempts) throw currentError.error;
61
+ const attemptOptions = {
62
+ ...updatedCallOptions,
63
+ attempt,
64
+ error: currentError.error,
65
+ lastEventRetry
66
+ };
67
+ if (!await value(shouldRetry, attemptOptions)) throw currentError.error;
68
+ retryDelayMs = await value(retryDelay, attemptOptions);
69
+ callback = onRetry?.(attemptOptions);
70
+ }
71
+ try {
72
+ if (currentError) {
73
+ await sleep(retryDelayMs, { signal: updatedCallOptions.signal });
74
+ if (isIteratorAborted) throw currentError.error;
75
+ attempt++;
76
+ }
77
+ currentError = void 0;
78
+ return await next(updatedCallOptions);
79
+ } catch (error) {
80
+ currentError = { error };
81
+ if (updatedCallOptions.signal?.aborted) throw error;
82
+ } finally {
83
+ callback?.(!currentError);
84
+ callback = void 0;
85
+ }
86
+ }
87
+ };
88
+ const output = await callNext();
89
+ if (!isAsyncIteratorObject(output)) return output;
90
+ let current = output;
91
+ return override(() => current, new AsyncIteratorClass(async () => {
92
+ while (true) try {
93
+ const item = await current.next();
94
+ const meta = getEventMeta(item.value);
95
+ lastEventId = meta?.id ?? lastEventId;
96
+ lastEventRetry = meta?.retry ?? lastEventRetry;
97
+ return item;
98
+ } catch (error) {
99
+ const meta = getEventMeta(error);
100
+ lastEventId = meta?.id ?? lastEventId;
101
+ lastEventRetry = meta?.retry ?? lastEventRetry;
102
+ const asyncIteratorObject = await callNext({ error });
103
+ if (!isAsyncIteratorObject(asyncIteratorObject)) throw new TypeError("RetryLinkPlugin: Expected an AsyncIteratorObject, got a different type.", { cause: error });
104
+ current = asyncIteratorObject;
105
+ if (isIteratorAborted) {
106
+ await current.return?.();
107
+ throw error;
108
+ }
109
+ }
110
+ }, async ({ kind }) => {
111
+ isIteratorAborted = true;
112
+ if (kind === "cancelled") await current.return?.();
113
+ }));
114
+ };
115
+ return {
116
+ ...options,
117
+ interceptors: [interceptor, ...toArray(options.interceptors)]
118
+ };
119
+ }
120
+ };
121
+ export { RetryLinkPlugin, isRetryableError };
@@ -0,0 +1,27 @@
1
+ import "../adapters/standard/index.js";
2
+ import { StandardLinkPlugin } from "../adapters/standard/plugin.js";
3
+ import { StandardLinkInterceptorOptions, StandardLinkOptions } from "../adapters/standard/link.js";
4
+ import { ClientContext } from "../types.js";
5
+ import { Value } from "@orpc/shared";
6
+ export interface TimeoutLinkPluginOptions<T extends ClientContext> {
7
+ /**
8
+ * Timeout in milliseconds before the request is aborted.
9
+ * Use `null` or `undefined` to disable the timeout.
10
+ */
11
+ timeout: Value<number | null | undefined, [options: StandardLinkInterceptorOptions<T>]>;
12
+ }
13
+ /**
14
+ * The Timeout Link Plugin aborts requests that exceed a configured timeout with an `AbortError`.
15
+ *
16
+ * @see {@link https://orpc.dev/docs/plugins/timeout | Timeout Plugin}
17
+ */
18
+ export declare class TimeoutLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
19
+ private readonly timeout;
20
+ name: string;
21
+ /**
22
+ * Should abort if the total retry time exceeds the configured timeout
23
+ */
24
+ after: string[];
25
+ constructor(options: NoInfer<TimeoutLinkPluginOptions<T>>);
26
+ init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
27
+ }
@@ -0,0 +1,42 @@
1
+ import { AbortError, anyAbortSignal, toArray, value } from "@orpc/shared";
2
+ // src/plugins/timeout.ts
3
+ /**
4
+ * The Timeout Link Plugin aborts requests that exceed a configured timeout with an `AbortError`.
5
+ *
6
+ * @see {@link https://orpc.dev/docs/plugins/timeout | Timeout Plugin}
7
+ */
8
+ var TimeoutLinkPlugin = class {
9
+ timeout;
10
+ name = "~timeout";
11
+ /**
12
+ * Should abort if the total retry time exceeds the configured timeout
13
+ */
14
+ after = ["~retry"];
15
+ constructor(options) {
16
+ this.timeout = options.timeout;
17
+ }
18
+ init(options) {
19
+ const interceptor = async (interceptorOptions) => {
20
+ const timeoutMs = value(this.timeout, interceptorOptions);
21
+ if (timeoutMs === null || timeoutMs === void 0) return interceptorOptions.next();
22
+ const controller = new AbortController();
23
+ const timeoutId = setTimeout(() => {
24
+ controller.abort(new AbortError(`Request timed out after ${timeoutMs}ms`));
25
+ }, timeoutMs);
26
+ const signal = anyAbortSignal([interceptorOptions.signal, controller.signal]);
27
+ try {
28
+ return await interceptorOptions.next({
29
+ ...interceptorOptions,
30
+ signal
31
+ });
32
+ } finally {
33
+ clearTimeout(timeoutId);
34
+ }
35
+ };
36
+ return {
37
+ ...options,
38
+ interceptors: [interceptor, ...toArray(options.interceptors)]
39
+ };
40
+ }
41
+ };
42
+ export { TimeoutLinkPlugin };
@@ -0,0 +1,99 @@
1
+ import { Segment } from "@orpc/shared";
2
+ export type RPCJsonSerializationMeta = [type: string, ...path: Segment[]];
3
+ export type RPCJsonSerialization = {
4
+ json: unknown;
5
+ meta?: RPCJsonSerializationMeta[] | undefined;
6
+ maps?: undefined;
7
+ blobs?: undefined;
8
+ } | {
9
+ json: unknown;
10
+ meta?: RPCJsonSerializationMeta[] | undefined;
11
+ maps: Segment[][];
12
+ blobs: Blob[];
13
+ };
14
+ export interface RPCJsonSerializerHandler {
15
+ condition(value: unknown): boolean;
16
+ serialize(value: any): unknown;
17
+ /**
18
+ * `serialized` comes from the wire, so validate its type and throw on mismatch.
19
+ */
20
+ deserialize(serialized: unknown): unknown;
21
+ /**
22
+ * If false, the result of this serializer will not be further processed by other serializers,
23
+ * even if it matches their conditions and treat it as final serialized value.
24
+ * This can be useful for serializers that return primitive values, which should not be further processed.
25
+ * to improve performance and avoid potential issues with other serializers.
26
+ *
27
+ * @default false
28
+ */
29
+ isTerminal?: boolean | undefined;
30
+ }
31
+ export interface RPCJsonSerializerOptions {
32
+ /**
33
+ * Extend or override the built-in type handlers used during serialization and deserialization.
34
+ *
35
+ * Each key is a unique type identifier (e.g. `"date"`, `"bigint"`) and maps to a handler
36
+ * that defines how to detect, serialize, and deserialize values of that type.
37
+ *
38
+ * **Extending:** Add new keys to support custom types:
39
+ * ```ts
40
+ * handlers: {
41
+ * buffer: {
42
+ * condition: (v) => v instanceof Buffer,
43
+ * serialize: (v: Buffer) => v.toString('base64'),
44
+ * deserialize: (s: string) => Buffer.from(s, 'base64'),
45
+ * isTerminal: true,
46
+ * }
47
+ * }
48
+ * ```
49
+ *
50
+ * **Overriding:** Use an existing key to replace a built-in handler:
51
+ * ```ts
52
+ * handlers: {
53
+ * date: {
54
+ * condition: (v) => v instanceof Date,
55
+ * serialize: (v: Date) => v.getTime(),
56
+ * deserialize: (n: number) => new Date(n),
57
+ * isTerminal: true,
58
+ * }
59
+ * }
60
+ * ```
61
+ *
62
+ * **Disabling:** Set a key to `undefined` to remove a built-in handler:
63
+ * ```ts
64
+ * handlers: { url: undefined }
65
+ * ```
66
+ *
67
+ * During deserialization, values whose type has no handler are left in their serialized form,
68
+ * so a client and server with different handlers can still communicate.
69
+ *
70
+ * Built-in type keys: `undefined`, `bigint`, `date`, `nan`, `infinity`, `url`, `set`, `map`.
71
+ */
72
+ handlers?: Record<string, undefined | RPCJsonSerializerHandler> | undefined;
73
+ /**
74
+ * If true, properties with undefined values will be omitted during serialization.
75
+ *
76
+ * @default true
77
+ */
78
+ omitUndefinedProperties?: boolean | undefined;
79
+ }
80
+ /**
81
+ * Serializes and deserializes native types like Date, BigInt, Set, and Map
82
+ * into a JSON value plus separate metadata describing how to restore them.
83
+ *
84
+ * @see {@link https://orpc.dev/docs/rpc/serializer#rpc-json-serializer | RPC Serializer - RPC JSON Serializer}
85
+ */
86
+ export declare class RPCJsonSerializer {
87
+ private readonly handlers;
88
+ private readonly inlineBuiltInHandlers;
89
+ private readonly handlerEntries;
90
+ private readonly omitUndefinedProperties;
91
+ constructor(options?: RPCJsonSerializerOptions);
92
+ serializeJson(data: unknown): RPCJsonSerialization;
93
+ /**
94
+ * `segments` is a shared mutable stack (push/pop while walking),
95
+ * so it must be copied before being stored in `meta` or `maps`.
96
+ */
97
+ private serializeValue;
98
+ deserializeJson(serialized: RPCJsonSerialization): unknown;
99
+ }