@orpc/client 2.0.0-beta.48 → 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 (147) hide show
  1. package/README.md +4 -4
  2. package/dist/adapters/fetch/index.d.ts +2 -0
  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 -0
  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/index.d.ts +5 -0
  18. package/dist/adapters/standard/index.js +4 -0
  19. package/dist/adapters/standard/link.d.ts +40 -0
  20. package/dist/adapters/standard/link.js +85 -0
  21. package/dist/adapters/standard/plugin.d.ts +32 -0
  22. package/dist/adapters/standard/plugin.js +16 -0
  23. package/dist/adapters/standard/rpc-link-codec.d.ts +63 -0
  24. package/dist/adapters/standard/rpc-link-codec.js +104 -0
  25. package/dist/adapters/standard/transport.d.ts +14 -0
  26. package/dist/adapters/websocket/index.d.ts +2 -0
  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 +14 -0
  30. package/dist/adapters/websocket/transport.d.ts +115 -0
  31. package/dist/adapters/websocket/transport.js +133 -0
  32. package/dist/async-iterator-object.d.ts +2 -0
  33. package/dist/async-iterator-object.js +29 -0
  34. package/dist/client-safe.d.ts +18 -0
  35. package/dist/client-safe.js +36 -0
  36. package/dist/client.d.ts +40 -0
  37. package/dist/client.js +39 -0
  38. package/dist/consts.d.ts +10 -0
  39. package/dist/consts.js +43 -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 +21 -0
  43. package/dist/error-utils.js +58 -0
  44. package/dist/error.d.ts +132 -0
  45. package/dist/error.js +178 -0
  46. package/dist/index.d.ts +53 -0
  47. package/dist/index.js +40 -0
  48. package/dist/plugins/batch.d.ts +185 -0
  49. package/dist/plugins/batch.js +401 -0
  50. package/dist/plugins/cookie-jar.d.ts +82 -0
  51. package/dist/plugins/cookie-jar.js +268 -0
  52. package/dist/plugins/dedupe.d.ts +64 -0
  53. package/dist/plugins/dedupe.js +226 -0
  54. package/dist/plugins/index.d.ts +28 -0
  55. package/dist/plugins/index.js +23 -0
  56. package/dist/plugins/request-compression.d.ts +44 -0
  57. package/dist/plugins/request-compression.js +178 -0
  58. package/dist/plugins/response-compression.d.ts +28 -0
  59. package/dist/plugins/response-compression.js +91 -0
  60. package/dist/plugins/retry-after.d.ts +50 -0
  61. package/dist/plugins/retry-after.js +88 -0
  62. package/dist/plugins/retry.d.ts +84 -0
  63. package/dist/plugins/retry.js +140 -0
  64. package/dist/plugins/timeout.d.ts +25 -0
  65. package/dist/plugins/timeout.js +37 -0
  66. package/dist/rpc-json-serializer.d.ts +99 -0
  67. package/dist/rpc-json-serializer.js +392 -0
  68. package/dist/rpc-serializer.d.ts +32 -0
  69. package/dist/rpc-serializer.js +130 -0
  70. package/dist/types.d.ts +97 -0
  71. package/dist/utils.d.ts +47 -0
  72. package/dist/utils.js +51 -0
  73. package/package.json +43 -45
  74. package/dist/adapters/fetch/index.d.mts +0 -2
  75. package/dist/adapters/fetch/index.mjs +0 -2
  76. package/dist/adapters/fetch/rpc-link.d.mts +0 -13
  77. package/dist/adapters/fetch/rpc-link.mjs +0 -10
  78. package/dist/adapters/fetch/transport.d.mts +0 -31
  79. package/dist/adapters/fetch/transport.mjs +0 -65
  80. package/dist/adapters/message-port/index.d.mts +0 -3
  81. package/dist/adapters/message-port/index.mjs +0 -3
  82. package/dist/adapters/message-port/message-port.d.mts +0 -29
  83. package/dist/adapters/message-port/message-port.mjs +0 -43
  84. package/dist/adapters/message-port/rpc-link.d.mts +0 -14
  85. package/dist/adapters/message-port/rpc-link.mjs +0 -10
  86. package/dist/adapters/message-port/transport.d.mts +0 -35
  87. package/dist/adapters/message-port/transport.mjs +0 -47
  88. package/dist/adapters/standard/codec.d.mts +0 -14
  89. package/dist/adapters/standard/index.d.mts +0 -5
  90. package/dist/adapters/standard/index.mjs +0 -4
  91. package/dist/adapters/standard/link.d.mts +0 -40
  92. package/dist/adapters/standard/link.mjs +0 -79
  93. package/dist/adapters/standard/plugin.d.mts +0 -32
  94. package/dist/adapters/standard/plugin.mjs +0 -16
  95. package/dist/adapters/standard/rpc-link-codec.d.mts +0 -55
  96. package/dist/adapters/standard/rpc-link-codec.mjs +0 -104
  97. package/dist/adapters/standard/transport.d.mts +0 -14
  98. package/dist/adapters/websocket/index.d.mts +0 -2
  99. package/dist/adapters/websocket/index.mjs +0 -2
  100. package/dist/adapters/websocket/rpc-link.d.mts +0 -13
  101. package/dist/adapters/websocket/rpc-link.mjs +0 -10
  102. package/dist/adapters/websocket/transport.d.mts +0 -119
  103. package/dist/adapters/websocket/transport.mjs +0 -123
  104. package/dist/async-iterator-object.d.mts +0 -7
  105. package/dist/async-iterator-object.mjs +0 -30
  106. package/dist/client-safe.d.mts +0 -16
  107. package/dist/client-safe.mjs +0 -23
  108. package/dist/client.d.mts +0 -51
  109. package/dist/client.mjs +0 -32
  110. package/dist/consts.d.mts +0 -10
  111. package/dist/consts.mjs +0 -10
  112. package/dist/dynamic-link.d.mts +0 -13
  113. package/dist/dynamic-link.mjs +0 -12
  114. package/dist/error-utils.d.mts +0 -24
  115. package/dist/error-utils.mjs +0 -44
  116. package/dist/error.d.mts +0 -138
  117. package/dist/error.mjs +0 -105
  118. package/dist/index.d.mts +0 -49
  119. package/dist/index.mjs +0 -23
  120. package/dist/plugins/batch.d.mts +0 -150
  121. package/dist/plugins/batch.mjs +0 -339
  122. package/dist/plugins/cookie-jar.d.mts +0 -82
  123. package/dist/plugins/cookie-jar.mjs +0 -229
  124. package/dist/plugins/dedupe.d.mts +0 -58
  125. package/dist/plugins/dedupe.mjs +0 -199
  126. package/dist/plugins/index.d.mts +0 -28
  127. package/dist/plugins/index.mjs +0 -17
  128. package/dist/plugins/request-compression.d.mts +0 -44
  129. package/dist/plugins/request-compression.mjs +0 -150
  130. package/dist/plugins/response-compression.d.mts +0 -28
  131. package/dist/plugins/response-compression.mjs +0 -78
  132. package/dist/plugins/retry-after.d.mts +0 -41
  133. package/dist/plugins/retry-after.mjs +0 -71
  134. package/dist/plugins/retry.d.mts +0 -82
  135. package/dist/plugins/retry.mjs +0 -127
  136. package/dist/plugins/timeout.d.mts +0 -25
  137. package/dist/plugins/timeout.mjs +0 -36
  138. package/dist/rpc-json-serializer.d.mts +0 -99
  139. package/dist/rpc-json-serializer.mjs +0 -365
  140. package/dist/rpc-serializer.d.mts +0 -32
  141. package/dist/rpc-serializer.mjs +0 -100
  142. package/dist/types.d.mts +0 -93
  143. package/dist/utils.d.mts +0 -46
  144. package/dist/utils.mjs +0 -53
  145. /package/dist/adapters/standard/{codec.mjs → codec.js} +0 -0
  146. /package/dist/adapters/standard/{transport.mjs → transport.js} +0 -0
  147. /package/dist/{types.mjs → types.js} +0 -0
@@ -1,150 +0,0 @@
1
- import { isAsyncIteratorObject, isCompressibleContentType, toArray } from "@orpc/shared";
2
- import { flattenStandardHeader, generateContentDisposition } from "@standard-server/core";
3
- import { toFetchBody } from "@standard-server/fetch";
4
-
5
-
6
- const AVG_BYTES_PER_CHAR = 1.2;
7
-
8
- export class RequestCompressionLinkPlugin {
9
- name = "~request-compression";
10
-
11
- after = ["~batch"];
12
- encoding;
13
- threshold;
14
- isCompressibleContentType;
15
- constructor(options = {}) {
16
- this.encoding = options.encoding ?? "gzip";
17
- this.threshold = options.threshold ?? 1024;
18
- this.isCompressibleContentType = options.isCompressibleContentType ?? isCompressibleContentType;
19
- }
20
- init(options) {
21
- const transportInterceptor = async ({ next, ...interceptorOptions }) => {
22
- const request = interceptorOptions.request;
23
- const contentEncoding = flattenStandardHeader(request.headers["content-encoding"])?.trim()?.toLowerCase();
24
- if (contentEncoding !== undefined) {
25
- return next();
26
- }
27
- if (request.body instanceof ReadableStream) {
28
- const contentLength = Number(flattenStandardHeader(request.headers["content-length"]));
29
- if ((!Number.isFinite(contentLength) || contentLength >= this.threshold) && this.isCompressibleContentType(flattenStandardHeader(request.headers["content-type"]), interceptorOptions)) {
30
- const compressedStream = request.body.pipeThrough(new CompressionStream(this.encoding));
31
- return next({
32
- ...interceptorOptions,
33
- request: {
34
- ...interceptorOptions.request,
35
- body: compressedStream,
36
- headers: {
37
- ...request.headers,
38
- "content-length": [],
39
- "content-encoding": this.encoding
40
- }
41
- }
42
- });
43
- }
44
- } else if (request.body instanceof Blob) {
45
- const contentType = request.headers["content-type"] ?? request.body.type;
46
- if ((!Number.isFinite(request.body.size) || request.body.size >= this.threshold) && this.isCompressibleContentType(flattenStandardHeader(contentType), interceptorOptions)) {
47
- const compressedStream = request.body.stream().pipeThrough(new CompressionStream(this.encoding));
48
- const contentDisposition = request.headers["content-disposition"] ?? generateContentDisposition(request.body instanceof File ? request.body.name : "blob");
49
- return next({
50
- ...interceptorOptions,
51
- request: {
52
- ...interceptorOptions.request,
53
- body: compressedStream,
54
- headers: {
55
- ...request.headers,
56
- "standard-server": request.headers["standard-server"] ?? "file",
57
- "content-type": contentType,
58
- "content-length": [],
59
- "content-disposition": contentDisposition,
60
- "content-encoding": this.encoding
61
- }
62
- }
63
- });
64
- }
65
- } else if (request.body instanceof FormData) {
66
- const PART_OVERHEAD = 64;
67
- let contentLength = 0;
68
- for (const [key, value] of request.body) {
69
- contentLength += PART_OVERHEAD + key.length;
70
- if (value instanceof Blob) {
71
- if (!Number.isFinite(value.size)) {
72
- if (!this.isCompressibleContentType(value.type, interceptorOptions)) {
73
-
74
- contentLength = -Infinity;
75
- break;
76
- }
77
-
78
- contentLength = Infinity;
79
- } else {
80
- contentLength += this.isCompressibleContentType(value.type, interceptorOptions) ? value.size : -value.size;
81
- }
82
- } else {
83
- contentLength += value.length * AVG_BYTES_PER_CHAR;
84
- }
85
- }
86
- if (contentLength >= this.threshold) {
87
- const res = new Response(request.body);
88
- const compressedStream = res.body.pipeThrough(new CompressionStream(this.encoding));
89
- return next({
90
- ...interceptorOptions,
91
- request: {
92
- ...interceptorOptions.request,
93
- body: compressedStream,
94
- headers: {
95
- ...request.headers,
96
- "standard-server": [],
97
- "content-type": res.headers.get("content-type"),
98
- "content-length": [],
99
- "content-encoding": this.encoding
100
- }
101
- }
102
- });
103
- }
104
- } else if (request.body instanceof URLSearchParams) {
105
- const string = request.body.toString();
106
- if (string.length * AVG_BYTES_PER_CHAR >= this.threshold) {
107
- const compressedStream = new Blob([string]).stream().pipeThrough(new CompressionStream(this.encoding));
108
- const [, bodyHeaders] = toFetchBody(request.body, request.headers);
109
- return next({
110
- ...interceptorOptions,
111
- request: {
112
- ...interceptorOptions.request,
113
- body: compressedStream,
114
- headers: {
115
- ...bodyHeaders,
116
-
117
- "standard-server": bodyHeaders["standard-server"] ?? [],
118
- "content-length": [],
119
- "content-encoding": this.encoding
120
- }
121
- }
122
- });
123
- }
124
- } else if (request.body !== undefined && !isAsyncIteratorObject(request.body)) {
125
- const [string, bodyHeaders] = toFetchBody(request.body, request.headers);
126
- if (string.length * AVG_BYTES_PER_CHAR >= this.threshold) {
127
- const compressedStream = new Blob([string]).stream().pipeThrough(new CompressionStream(this.encoding));
128
- return next({
129
- ...interceptorOptions,
130
- request: {
131
- ...interceptorOptions.request,
132
- body: compressedStream,
133
- headers: {
134
- ...bodyHeaders,
135
- "standard-server": bodyHeaders["standard-server"] ?? [],
136
- "content-length": [],
137
- "content-encoding": this.encoding
138
- }
139
- }
140
- });
141
- }
142
- }
143
- return next();
144
- };
145
- return {
146
- ...options,
147
- transportInterceptors: [...toArray(options.transportInterceptors), transportInterceptor]
148
- };
149
- }
150
- }
@@ -1,28 +0,0 @@
1
- import type { StandardLinkOptions, StandardLinkPlugin } from "../adapters/standard/index.mjs";
2
- import type { ClientContext } from "../types.mjs";
3
- export interface ResponseCompressionLinkPluginOptions<_T extends ClientContext> {
4
- /**
5
- * Compression schemes to advertise via Accept-Encoding, in preference order.
6
- * Only schemes that can be decompressed by this plugin should be listed.
7
- *
8
- * @default ['gzip', 'deflate']
9
- */
10
- encodings?: readonly ("gzip" | "deflate" | "deflate-raw")[] | undefined;
11
- }
12
- /**
13
- * Advertises Accept-Encoding on requests and decompresses response bodies
14
- * based on the Content-Encoding header. Works at the standard link level,
15
- * so it supports all adapters.
16
- *
17
- * @see {@link https://orpc.dev/docs/plugins/response-compression | Response Compression Plugin}
18
- */
19
- export declare class ResponseCompressionLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
20
- name: string;
21
- /**
22
- * Decompression should wrap the final batch response instead of sub-responses.
23
- */
24
- after: string[];
25
- private readonly encodings;
26
- constructor(options?: ResponseCompressionLinkPluginOptions<T>);
27
- init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
28
- }
@@ -1,78 +0,0 @@
1
- import { toArray } from "@orpc/shared";
2
- import { flattenStandardHeader } from "@standard-server/core";
3
- import { toFetchHeaders, toStandardBody } from "@standard-server/fetch";
4
-
5
- const MAX_CONTENT_ENCODINGS = 5;
6
-
7
- export class ResponseCompressionLinkPlugin {
8
- name = "~response-compression";
9
-
10
- after = ["~batch"];
11
- encodings;
12
- constructor(options = {}) {
13
- this.encodings = options.encodings ?? ["gzip", "deflate"];
14
- }
15
- init(options) {
16
- const acceptEncodingHeader = this.encodings.join(", ");
17
- const transportInterceptor = async ({ next, ...interceptorOptions }) => {
18
- const response = await next({
19
- ...interceptorOptions,
20
- request: {
21
- ...interceptorOptions.request,
22
- headers: {
23
- ...interceptorOptions.request.headers,
24
- "accept-encoding": acceptEncodingHeader
25
- }
26
- }
27
- });
28
- const encodings = parseContentEncodings(flattenStandardHeader(response.headers["content-encoding"]));
29
- if (encodings.length === 0 || !encodings.every(isSupportedEncoding)) {
30
- return response;
31
- }
32
- const decompressedHeaders = {
33
- ...response.headers,
34
- "content-length": undefined,
35
- "content-encoding": undefined
36
- };
37
- return {
38
- ...response,
39
- headers: decompressedHeaders,
40
- async resolveBody(hint) {
41
- const stream = await response.resolveBody("octet-stream");
42
-
43
- if (!(stream instanceof ReadableStream)) {
44
- return stream;
45
- }
46
- if (encodings.length > MAX_CONTENT_ENCODINGS) {
47
- throw new TypeError("Too many content encodings.");
48
- }
49
- let decompressedStream = stream;
50
- for (let i = encodings.length - 1; i >= 0; i--) {
51
- decompressedStream = decompressedStream.pipeThrough(new DecompressionStream(encodings[i]));
52
- }
53
- const fetchResponse = new Response(decompressedStream, { headers: toFetchHeaders(decompressedHeaders) });
54
- return toStandardBody(fetchResponse, { hint });
55
- }
56
- };
57
- };
58
- return {
59
- ...options,
60
- transportInterceptors: [...toArray(options.transportInterceptors), transportInterceptor]
61
- };
62
- }
63
- }
64
- const SUPPORTED_ENCODINGS = [
65
- "gzip",
66
- "deflate",
67
- "deflate-raw"
68
- ];
69
- function isSupportedEncoding(encoding) {
70
- return SUPPORTED_ENCODINGS.includes(encoding);
71
- }
72
-
73
- function parseContentEncodings(header) {
74
- if (header === undefined) {
75
- return [];
76
- }
77
- return header.split(",").map((part) => part.trim().toLowerCase());
78
- }
@@ -1,41 +0,0 @@
1
- import type { Value } from "@orpc/shared";
2
- import type { StandardLazyResponse } from "@standard-server/core";
3
- import type { StandardLinkOptions, StandardLinkPlugin, StandardLinkTransportInterceptorOptions } from "../adapters/standard/index.mjs";
4
- import type { ClientContext } from "../types.mjs";
5
- export interface RetryAfterLinkPluginOptions<T extends ClientContext> {
6
- /**
7
- * Override condition to determine whether to retry or not.
8
- *
9
- * @default ((response) => response.status === 429 || response.status === 503)
10
- */
11
- condition?: Value<boolean, [response: StandardLazyResponse, options: StandardLinkTransportInterceptorOptions<T>]> | undefined;
12
- /**
13
- * Maximum attempts before giving up retries.
14
- *
15
- * @default 3
16
- */
17
- maxAttempts?: Value<number, [response: StandardLazyResponse, options: StandardLinkTransportInterceptorOptions<T>]> | undefined;
18
- /**
19
- * Maximum timeout in milliseconds to wait before giving up retries.
20
- *
21
- * @default 5 * 60 * 1000 (5 minutes)
22
- */
23
- timeout?: Value<number, [response: StandardLazyResponse, options: StandardLinkTransportInterceptorOptions<T>]> | undefined;
24
- }
25
- /**
26
- * The Retry After Link Plugin automatically retries requests based on server `retry-after` header.
27
- * This is particularly useful for handling rate limiting and temporary server unavailability.
28
- *
29
- * @remarks
30
- * **Note**: Requests with a stream or async iterator body are never retried, since the body cannot be resent.
31
- *
32
- * @see {@link https://orpc.dev/docs/plugins/retry-after | Retry After Plugin}
33
- */
34
- export declare class RetryAfterLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
35
- private readonly condition;
36
- private readonly maxAttempts;
37
- private readonly timeout;
38
- name: string;
39
- constructor(options?: RetryAfterLinkPluginOptions<T>);
40
- init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
41
- }
@@ -1,71 +0,0 @@
1
- import { isAsyncIteratorObject, sleep, toArray, value } from "@orpc/shared";
2
- import { flattenStandardHeader } from "@standard-server/core";
3
- import { COMMON_ERROR_STATUS_MAP } from "../error.mjs";
4
-
5
- export class RetryAfterLinkPlugin {
6
- condition;
7
- maxAttempts;
8
- timeout;
9
- name = "~retry-after";
10
- constructor(options = {}) {
11
- this.condition = options.condition ?? ((response) => response.status === COMMON_ERROR_STATUS_MAP.TOO_MANY_REQUESTS || response.status === COMMON_ERROR_STATUS_MAP.SERVICE_UNAVAILABLE);
12
- this.maxAttempts = options.maxAttempts ?? 3;
13
- this.timeout = options.timeout ?? 5 * 60 * 1e3;
14
- }
15
- init(options) {
16
- const interceptor = async (interceptorOptions) => {
17
- const { body } = interceptorOptions.request;
18
-
19
- if (body instanceof ReadableStream || isAsyncIteratorObject(body)) {
20
- return interceptorOptions.next();
21
- }
22
- const startTime = Date.now();
23
- let attemptCount = 0;
24
- while (true) {
25
- attemptCount++;
26
- const response = await interceptorOptions.next();
27
- if (!value(this.condition, response, interceptorOptions)) {
28
- return response;
29
- }
30
- const retryAfterHeader = flattenStandardHeader(response.headers["retry-after"]);
31
- const retryAfterMs = parseRetryAfterHeader(retryAfterHeader);
32
- if (retryAfterMs === undefined) {
33
- return response;
34
- }
35
- if (attemptCount >= value(this.maxAttempts, response, interceptorOptions)) {
36
- return response;
37
- }
38
- const timeoutMs = value(this.timeout, response, interceptorOptions);
39
- const elapsedTime = Date.now() - startTime;
40
- if (elapsedTime + retryAfterMs > timeoutMs) {
41
- return response;
42
- }
43
- try {
44
- await sleep(retryAfterMs, { signal: interceptorOptions.signal });
45
- } catch {}
46
- if (interceptorOptions.signal?.aborted) {
47
- return response;
48
- }
49
- }
50
- };
51
- return {
52
- ...options,
53
- transportInterceptors: [interceptor, ...toArray(options.transportInterceptors)]
54
- };
55
- }
56
- }
57
- function parseRetryAfterHeader(value) {
58
- value = value?.trim();
59
- if (!value) {
60
- return undefined;
61
- }
62
- const seconds = Number(value);
63
- if (Number.isFinite(seconds)) {
64
- return Math.max(0, seconds * 1e3);
65
- }
66
- const retryDate = Date.parse(value);
67
- if (!Number.isNaN(retryDate)) {
68
- return Math.max(0, retryDate - Date.now());
69
- }
70
- return undefined;
71
- }
@@ -1,82 +0,0 @@
1
- import type { Promisable, Value } from "@orpc/shared";
2
- import type { StandardLinkInterceptorOptions, StandardLinkOptions, StandardLinkPlugin } from "../adapters/standard/index.mjs";
3
- import type { ClientContext } from "../types.mjs";
4
- export interface RetryLinkPluginAttemptOptions<T extends RetryLinkPluginContext> extends StandardLinkInterceptorOptions<T> {
5
- /**
6
- * Latest retry delay advertised by the server via event metadata.
7
- */
8
- lastEventRetry: number | undefined;
9
- /**
10
- * Current retry attempt number, starting at 1.
11
- */
12
- attempt: number;
13
- /**
14
- * Error that triggered this retry attempt.
15
- */
16
- error: unknown;
17
- }
18
- /**
19
- * Client context options that control retry behavior per call
20
- * when the `RetryLinkPlugin` is enabled.
21
- *
22
- * @see {@link https://orpc.dev/docs/plugins/retry | Retry Plugin}
23
- */
24
- export interface RetryLinkPluginContext {
25
- /**
26
- * Maximum retry attempts before throwing.
27
- * Use `Number.POSITIVE_INFINITY` for infinite retries (e.g. for AsyncIteratorObject).
28
- *
29
- * @default 0
30
- */
31
- retry?: Value<Promisable<number>, [Omit<StandardLinkInterceptorOptions<RetryLinkPluginContext>, "next">]> | undefined;
32
- /**
33
- * Delay (in ms) before retrying.
34
- *
35
- * @remarks
36
- * **Note**: Why 2000ms? The EventSource spec suggests a default retry delay of 2 seconds if it doesn't specify
37
- *
38
- * @default (o) => o.lastEventRetry ?? 2000
39
- */
40
- retryDelay?: Value<Promisable<number>, [RetryLinkPluginAttemptOptions<RetryLinkPluginContext>]> | undefined;
41
- /**
42
- * Determine whether to retry.
43
- *
44
- * @default (o) => isRetryableError(o.error)
45
- */
46
- shouldRetry?: Value<Promisable<boolean>, [RetryLinkPluginAttemptOptions<RetryLinkPluginContext>]> | undefined;
47
- /**
48
- * Hook called before each retry. Can return a cleanup callback.
49
- */
50
- onRetry?: ((options: RetryLinkPluginAttemptOptions<RetryLinkPluginContext>) => void | ((isSuccess: boolean) => void)) | undefined;
51
- }
52
- export interface RetryLinkPluginOptions<_T extends RetryLinkPluginContext> {
53
- /**
54
- * Default retry options. Can be overridden by individual calls via the context.
55
- */
56
- default?: RetryLinkPluginContext | undefined;
57
- }
58
- /**
59
- * Default `shouldRetry` check of `RetryLinkPlugin`. Returns `false` only for errors
60
- * from a 4xx response other than `408` and `429`.
61
- *
62
- * @see {@link https://orpc.dev/docs/plugins/retry#client-error-responses | Retry Plugin - Client Error Responses}
63
- */
64
- export declare function isRetryableError(error: unknown): boolean;
65
- /**
66
- * Automatically retries failed requests based on customizable retry strategies,
67
- * improving the resilience of your application.
68
- *
69
- * @remarks
70
- * **Note**: Retry behavior is configured through the client context on each call.
71
- *
72
- * @see {@link https://orpc.dev/docs/plugins/retry | Retry Plugin}
73
- */
74
- export declare class RetryLinkPlugin<T extends RetryLinkPluginContext & ClientContext> implements StandardLinkPlugin<T> {
75
- private readonly defaultRetry;
76
- private readonly defaultRetryDelay;
77
- private readonly defaultShouldRetry;
78
- private readonly defaultOnRetry;
79
- name: string;
80
- constructor(options?: RetryLinkPluginOptions<T>);
81
- init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
82
- }
@@ -1,127 +0,0 @@
1
- import { AsyncIteratorClass, isAsyncIteratorObject, override, sleep, toArray, value } from "@orpc/shared";
2
- import { getEventMeta } from "@standard-server/core";
3
- import { COMMON_ERROR_STATUS_MAP, ORPCError, ResponseError } from "../error.mjs";
4
-
5
- export function isRetryableError(error) {
6
- const responseError = error instanceof ORPCError ? error.cause : error;
7
- if (!(responseError instanceof ResponseError)) {
8
- return true;
9
- }
10
- const { status } = responseError.response;
11
- return status < 400 || status >= 500 || status === COMMON_ERROR_STATUS_MAP.TIMEOUT || status === COMMON_ERROR_STATUS_MAP.TOO_MANY_REQUESTS;
12
- }
13
-
14
- export class RetryLinkPlugin {
15
- defaultRetry;
16
- defaultRetryDelay;
17
- defaultShouldRetry;
18
- defaultOnRetry;
19
- name = "~retry";
20
- constructor(options = {}) {
21
- this.defaultRetry = options.default?.retry ?? 0;
22
- this.defaultRetryDelay = options.default?.retryDelay ?? ((o) => o.lastEventRetry ?? 2e3);
23
- this.defaultShouldRetry = options.default?.shouldRetry ?? ((o) => isRetryableError(o.error));
24
- this.defaultOnRetry = options.default?.onRetry;
25
- }
26
- init(options) {
27
- const interceptor = async (interceptorOptions) => {
28
- const { next, ...callOptions } = interceptorOptions;
29
- const maxAttempts = await value(callOptions.context.retry ?? this.defaultRetry, callOptions);
30
- const retryDelay = callOptions.context.retryDelay ?? this.defaultRetryDelay;
31
- const shouldRetry = callOptions.context.shouldRetry ?? this.defaultShouldRetry;
32
- const onRetry = callOptions.context.onRetry ?? this.defaultOnRetry;
33
- if (maxAttempts <= 0) {
34
- return next(callOptions);
35
- }
36
- let lastEventId = callOptions.lastEventId;
37
- let lastEventRetry;
38
- let callback;
39
- let attempt = 1;
40
- let isIteratorAborted = false;
41
- const callNext = async (initialError) => {
42
- let currentError = initialError;
43
- while (true) {
44
- const updatedCallOptions = {
45
- ...callOptions,
46
- lastEventId
47
- };
48
- let retryDelayMs = 0;
49
- if (currentError) {
50
- if (isIteratorAborted || attempt > maxAttempts) {
51
- throw currentError.error;
52
- }
53
- const attemptOptions = {
54
- ...updatedCallOptions,
55
- attempt,
56
- error: currentError.error,
57
- lastEventRetry
58
- };
59
- const shouldRetryBool = await value(shouldRetry, attemptOptions);
60
- if (!shouldRetryBool) {
61
- throw currentError.error;
62
- }
63
- retryDelayMs = await value(retryDelay, attemptOptions);
64
- callback = onRetry?.(attemptOptions);
65
- }
66
- try {
67
- if (currentError) {
68
- await sleep(retryDelayMs, { signal: updatedCallOptions.signal });
69
- if (isIteratorAborted) {
70
- throw currentError.error;
71
- }
72
- attempt++;
73
- }
74
- currentError = undefined;
75
- return await next(updatedCallOptions);
76
- } catch (error) {
77
- currentError = { error };
78
- if (updatedCallOptions.signal?.aborted) {
79
- throw error;
80
- }
81
- } finally {
82
- callback?.(!currentError);
83
- callback = undefined;
84
- }
85
- }
86
- };
87
- const output = await callNext();
88
- if (!isAsyncIteratorObject(output)) {
89
- return output;
90
- }
91
- let current = output;
92
- return override(() => current, new AsyncIteratorClass(async () => {
93
- while (true) {
94
- try {
95
- const item = await current.next();
96
- const meta = getEventMeta(item.value);
97
- lastEventId = meta?.id ?? lastEventId;
98
- lastEventRetry = meta?.retry ?? lastEventRetry;
99
- return item;
100
- } catch (error) {
101
- const meta = getEventMeta(error);
102
- lastEventId = meta?.id ?? lastEventId;
103
- lastEventRetry = meta?.retry ?? lastEventRetry;
104
- const asyncIteratorObject = await callNext({ error });
105
- if (!isAsyncIteratorObject(asyncIteratorObject)) {
106
- throw new TypeError("RetryLinkPlugin: Expected an AsyncIteratorObject, got a different type.");
107
- }
108
- current = asyncIteratorObject;
109
- if (isIteratorAborted) {
110
- await current.return?.();
111
- throw error;
112
- }
113
- }
114
- }
115
- }, async ({ kind }) => {
116
- isIteratorAborted = true;
117
- if (kind === "cancelled") {
118
- await current.return?.();
119
- }
120
- }));
121
- };
122
- return {
123
- ...options,
124
- interceptors: [interceptor, ...toArray(options.interceptors)]
125
- };
126
- }
127
- }
@@ -1,25 +0,0 @@
1
- import type { Value } from "@orpc/shared";
2
- import type { StandardLinkInterceptorOptions, StandardLinkOptions, StandardLinkPlugin } from "../adapters/standard/index.mjs";
3
- import type { ClientContext } from "../types.mjs";
4
- export interface TimeoutLinkPluginOptions<T extends ClientContext> {
5
- /**
6
- * Timeout in milliseconds before the request is aborted.
7
- * Use `null` or `undefined` to disable the timeout.
8
- */
9
- timeout: Value<number | null | undefined, [options: StandardLinkInterceptorOptions<T>]>;
10
- }
11
- /**
12
- * The Timeout Link Plugin aborts requests that exceed a configured timeout with an `AbortError`.
13
- *
14
- * @see {@link https://orpc.dev/docs/plugins/timeout | Timeout Plugin}
15
- */
16
- export declare class TimeoutLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
17
- private readonly timeout;
18
- name: string;
19
- /**
20
- * Should abort if the total retry time exceeds the configured timeout
21
- */
22
- after: string[];
23
- constructor(options: NoInfer<TimeoutLinkPluginOptions<T>>);
24
- init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
25
- }
@@ -1,36 +0,0 @@
1
- import { AbortError, anyAbortSignal, toArray, value } from "@orpc/shared";
2
-
3
- export class TimeoutLinkPlugin {
4
- timeout;
5
- name = "~timeout";
6
-
7
- after = ["~retry"];
8
- constructor(options) {
9
- this.timeout = options.timeout;
10
- }
11
- init(options) {
12
- const interceptor = async (interceptorOptions) => {
13
- const timeoutMs = value(this.timeout, interceptorOptions);
14
- if (timeoutMs === null || timeoutMs === undefined) {
15
- return interceptorOptions.next();
16
- }
17
- const controller = new AbortController();
18
- const timeoutId = setTimeout(() => {
19
- controller.abort(new AbortError(`Request timed out after ${timeoutMs}ms`));
20
- }, timeoutMs);
21
- const signal = anyAbortSignal([interceptorOptions.signal, controller.signal]);
22
- try {
23
- return await interceptorOptions.next({
24
- ...interceptorOptions,
25
- signal
26
- });
27
- } finally {
28
- clearTimeout(timeoutId);
29
- }
30
- };
31
- return {
32
- ...options,
33
- interceptors: [interceptor, ...toArray(options.interceptors)]
34
- };
35
- }
36
- }