@orpc/client 2.0.0-beta.47 → 2.0.0-beta.48
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.
- package/README.md +2 -3
- package/dist/adapters/fetch/index.d.mts +2 -48
- package/dist/adapters/fetch/index.mjs +2 -77
- package/dist/adapters/fetch/rpc-link.d.mts +13 -0
- package/dist/adapters/fetch/rpc-link.mjs +10 -0
- package/dist/adapters/fetch/transport.d.mts +31 -0
- package/dist/adapters/fetch/transport.mjs +65 -0
- package/dist/adapters/message-port/index.d.mts +3 -80
- package/dist/adapters/message-port/index.mjs +3 -101
- package/dist/adapters/message-port/message-port.d.mts +29 -0
- package/dist/adapters/message-port/message-port.mjs +43 -0
- package/dist/adapters/message-port/rpc-link.d.mts +14 -0
- package/dist/adapters/message-port/rpc-link.mjs +10 -0
- package/dist/adapters/message-port/transport.d.mts +35 -0
- package/dist/adapters/message-port/transport.mjs +47 -0
- package/dist/adapters/standard/codec.d.mts +14 -0
- package/dist/adapters/standard/codec.mjs +1 -0
- package/dist/adapters/standard/index.d.mts +5 -60
- package/dist/adapters/standard/index.mjs +4 -6
- package/dist/adapters/standard/link.d.mts +40 -0
- package/dist/adapters/standard/link.mjs +79 -0
- package/dist/adapters/standard/plugin.d.mts +32 -0
- package/dist/adapters/standard/plugin.mjs +16 -0
- package/dist/adapters/standard/rpc-link-codec.d.mts +55 -0
- package/dist/adapters/standard/rpc-link-codec.mjs +104 -0
- package/dist/adapters/standard/transport.d.mts +14 -0
- package/dist/adapters/standard/transport.mjs +1 -0
- package/dist/adapters/websocket/index.d.mts +2 -136
- package/dist/adapters/websocket/index.mjs +2 -131
- package/dist/adapters/websocket/rpc-link.d.mts +13 -0
- package/dist/adapters/websocket/rpc-link.mjs +10 -0
- package/dist/adapters/websocket/transport.d.mts +119 -0
- package/dist/adapters/websocket/transport.mjs +123 -0
- package/dist/async-iterator-object.d.mts +7 -0
- package/dist/async-iterator-object.mjs +30 -0
- package/dist/client-safe.d.mts +16 -0
- package/dist/client-safe.mjs +23 -0
- package/dist/client.d.mts +51 -0
- package/dist/client.mjs +32 -0
- package/dist/consts.d.mts +10 -0
- package/dist/consts.mjs +10 -0
- package/dist/dynamic-link.d.mts +13 -0
- package/dist/dynamic-link.mjs +12 -0
- package/dist/error-utils.d.mts +24 -0
- package/dist/error-utils.mjs +44 -0
- package/dist/error.d.mts +138 -0
- package/dist/error.mjs +105 -0
- package/dist/index.d.mts +42 -137
- package/dist/index.mjs +18 -142
- package/dist/plugins/batch.d.mts +150 -0
- package/dist/plugins/batch.mjs +339 -0
- package/dist/plugins/cookie-jar.d.mts +82 -0
- package/dist/plugins/cookie-jar.mjs +229 -0
- package/dist/plugins/dedupe.d.mts +58 -0
- package/dist/plugins/dedupe.mjs +199 -0
- package/dist/plugins/index.d.mts +28 -420
- package/dist/plugins/index.mjs +17 -971
- package/dist/plugins/request-compression.d.mts +44 -0
- package/dist/plugins/request-compression.mjs +150 -0
- package/dist/plugins/response-compression.d.mts +28 -0
- package/dist/plugins/response-compression.mjs +78 -0
- package/dist/plugins/retry-after.d.mts +41 -0
- package/dist/plugins/retry-after.mjs +71 -0
- package/dist/plugins/retry.d.mts +82 -0
- package/dist/plugins/retry.mjs +127 -0
- package/dist/plugins/timeout.d.mts +25 -0
- package/dist/plugins/timeout.mjs +36 -0
- package/dist/rpc-json-serializer.d.mts +99 -0
- package/dist/rpc-json-serializer.mjs +365 -0
- package/dist/rpc-serializer.d.mts +32 -0
- package/dist/rpc-serializer.mjs +100 -0
- package/dist/types.d.mts +93 -0
- package/dist/types.mjs +1 -0
- package/dist/utils.d.mts +46 -0
- package/dist/utils.mjs +53 -0
- package/package.json +5 -5
- package/dist/adapters/fetch/index.d.ts +0 -48
- package/dist/adapters/message-port/index.d.ts +0 -80
- package/dist/adapters/standard/index.d.ts +0 -60
- package/dist/adapters/websocket/index.d.ts +0 -136
- package/dist/index.d.ts +0 -144
- package/dist/plugins/index.d.ts +0 -420
- package/dist/shared/client.BoHJeq15.d.mts +0 -233
- package/dist/shared/client.BoHJeq15.d.ts +0 -233
- package/dist/shared/client.CKQeJJ2U.mjs +0 -172
- package/dist/shared/client.DqIWeNhQ.d.mts +0 -131
- package/dist/shared/client.DqIWeNhQ.d.ts +0 -131
- package/dist/shared/client.JBJwBhR8.d.ts +0 -90
- package/dist/shared/client.LF04eOvL.mjs +0 -115
- package/dist/shared/client._wG5INmC.mjs +0 -505
- package/dist/shared/client.euYjjcFz.d.mts +0 -90
package/dist/plugins/index.mjs
CHANGED
|
@@ -1,971 +1,17 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
batchHeaders;
|
|
19
|
-
mapSubrequest;
|
|
20
|
-
mapSubresponse;
|
|
21
|
-
queue = /* @__PURE__ */ new Map();
|
|
22
|
-
constructor(options) {
|
|
23
|
-
this.groups = options.groups;
|
|
24
|
-
this.filter = options.filter ?? (() => true);
|
|
25
|
-
this.scope = options.scope ?? (() => void 0);
|
|
26
|
-
this.maxSize = options.maxSize ?? DEFAULT_BATCH_MAX_SIZE;
|
|
27
|
-
this.wait = options.wait ?? 0;
|
|
28
|
-
this.batchUrl = options.url ?? ((options2) => {
|
|
29
|
-
const [pathname] = parseStandardUrl(options2[0].request.url);
|
|
30
|
-
return `${pathname}/__batch__`;
|
|
31
|
-
});
|
|
32
|
-
this.maxUrlLength = options.maxUrlLength ?? 2083;
|
|
33
|
-
this.batchHeaders = options.headers ?? (async (options2) => {
|
|
34
|
-
const headersList = options2.map((o) => o.request.headers);
|
|
35
|
-
const commonHeaders = {};
|
|
36
|
-
for (const headers of headersList) {
|
|
37
|
-
for (const key of Object.keys(headers)) {
|
|
38
|
-
const value2 = headers[key];
|
|
39
|
-
if (headersList.every((h) => h[key] === value2)) {
|
|
40
|
-
commonHeaders[key] = value2;
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
return commonHeaders;
|
|
45
|
-
});
|
|
46
|
-
this.mapSubrequest = options.mapSubrequest ?? (({ request }, { headers }) => {
|
|
47
|
-
const subHeaders = { ...request.headers };
|
|
48
|
-
for (const key of Object.keys(headers)) {
|
|
49
|
-
const value2 = headers[key];
|
|
50
|
-
if (subHeaders[key] === value2) {
|
|
51
|
-
subHeaders[key] = void 0;
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
return {
|
|
55
|
-
...request,
|
|
56
|
-
headers: subHeaders
|
|
57
|
-
};
|
|
58
|
-
});
|
|
59
|
-
this.mapSubresponse = options.mapSubresponse ?? ((subResponse, batchResponse) => {
|
|
60
|
-
return {
|
|
61
|
-
...subResponse,
|
|
62
|
-
headers: {
|
|
63
|
-
...batchResponse.headers,
|
|
64
|
-
// low-priority
|
|
65
|
-
...subResponse.headers
|
|
66
|
-
}
|
|
67
|
-
};
|
|
68
|
-
});
|
|
69
|
-
}
|
|
70
|
-
init(options) {
|
|
71
|
-
const transportInterceptor = async (interceptorOptions) => {
|
|
72
|
-
const { body, signal } = interceptorOptions.request;
|
|
73
|
-
if (body instanceof Blob || body instanceof FormData || body instanceof ReadableStream || isAsyncIteratorObject(body) || signal?.aborted || !value(this.filter, interceptorOptions)) {
|
|
74
|
-
return interceptorOptions.next();
|
|
75
|
-
}
|
|
76
|
-
const group = this.groups.find((group2) => value(group2.condition, interceptorOptions));
|
|
77
|
-
if (!group) {
|
|
78
|
-
return interceptorOptions.next();
|
|
79
|
-
}
|
|
80
|
-
const scope = this.scope(interceptorOptions);
|
|
81
|
-
return new Promise((resolve, reject) => {
|
|
82
|
-
if (!this.queue.size) {
|
|
83
|
-
defer(() => this.processPendingBatches(), this.wait);
|
|
84
|
-
}
|
|
85
|
-
let groups = this.queue.get(scope);
|
|
86
|
-
if (!groups) {
|
|
87
|
-
groups = /* @__PURE__ */ new Map();
|
|
88
|
-
this.queue.set(scope, groups);
|
|
89
|
-
}
|
|
90
|
-
let queue = groups.get(group);
|
|
91
|
-
if (!queue) {
|
|
92
|
-
queue = [];
|
|
93
|
-
groups.set(group, queue);
|
|
94
|
-
}
|
|
95
|
-
queue.push([interceptorOptions, resolve, reject, captureAsyncContext()]);
|
|
96
|
-
});
|
|
97
|
-
};
|
|
98
|
-
return {
|
|
99
|
-
...options,
|
|
100
|
-
transportInterceptors: [...toArray(options.transportInterceptors), transportInterceptor]
|
|
101
|
-
};
|
|
102
|
-
}
|
|
103
|
-
processPendingBatches() {
|
|
104
|
-
const pending = [...this.queue.values()];
|
|
105
|
-
this.queue.clear();
|
|
106
|
-
for (const groups of pending) {
|
|
107
|
-
for (const [group, items] of groups) {
|
|
108
|
-
const getItems = items.filter(([options]) => options.request.method === "GET");
|
|
109
|
-
const queryItems = items.filter(([options]) => options.request.method === "QUERY");
|
|
110
|
-
const unsafeItems = items.filter(([options]) => options.request.method !== "GET" && options.request.method !== "QUERY");
|
|
111
|
-
this.executeBatchInOwnContext("GET", group, getItems);
|
|
112
|
-
this.executeBatchInOwnContext("QUERY", group, queryItems);
|
|
113
|
-
this.executeBatchInOwnContext("POST", group, unsafeItems);
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
/**
|
|
118
|
-
* Runs the batch in the async context of its first request instead of the timer's,
|
|
119
|
-
* so the transport and batch options see that caller's request state.
|
|
120
|
-
* `executeBatch` always runs in the context of its first request.
|
|
121
|
-
*/
|
|
122
|
-
async executeBatchInOwnContext(method, group, groupItems) {
|
|
123
|
-
await groupItems[0]?.[3](() => this.executeBatch(method, group, groupItems));
|
|
124
|
-
}
|
|
125
|
-
async executeBatch(method, group, groupItems) {
|
|
126
|
-
try {
|
|
127
|
-
if (groupItems.length === 1) {
|
|
128
|
-
const [options, resolve, reject] = groupItems[0];
|
|
129
|
-
options.next().then(resolve).catch(reject);
|
|
130
|
-
return;
|
|
131
|
-
}
|
|
132
|
-
const subOptionsList = groupItems.map(([options]) => options);
|
|
133
|
-
const maxSize = await value(this.maxSize, subOptionsList);
|
|
134
|
-
if (groupItems.length > maxSize) {
|
|
135
|
-
const [first, second] = splitInHalf(groupItems);
|
|
136
|
-
await Promise.all([
|
|
137
|
-
this.executeBatch(method, group, first),
|
|
138
|
-
this.executeBatchInOwnContext(method, group, second)
|
|
139
|
-
]);
|
|
140
|
-
return;
|
|
141
|
-
}
|
|
142
|
-
const url = await value(this.batchUrl, subOptionsList);
|
|
143
|
-
const headers = await value(this.batchHeaders, subOptionsList);
|
|
144
|
-
let suppressErrorFromCurrentBatch = false;
|
|
145
|
-
const controller = new AbortController();
|
|
146
|
-
const pendingMessages = [];
|
|
147
|
-
const subrequests = groupItems.map(([subOptions]) => this.mapSubrequest(subOptions, { url, headers }));
|
|
148
|
-
let batchResponse;
|
|
149
|
-
let markRequestSent;
|
|
150
|
-
const openRequestIds = /* @__PURE__ */ new Set();
|
|
151
|
-
const cancelledRunningRequestIds = /* @__PURE__ */ new Set();
|
|
152
|
-
let isBatchSent = false;
|
|
153
|
-
const abortIfOnlyCancelledRemain = () => {
|
|
154
|
-
if (openRequestIds.size === 0 && cancelledRunningRequestIds.size > 0) {
|
|
155
|
-
controller.abort();
|
|
156
|
-
}
|
|
157
|
-
};
|
|
158
|
-
const peer = new ClientPeer(async (message) => {
|
|
159
|
-
pendingMessages.push(message);
|
|
160
|
-
if (message.kind === "request") {
|
|
161
|
-
openRequestIds.add(message.id);
|
|
162
|
-
markRequestSent?.();
|
|
163
|
-
} else if (message.kind === "cancel" && openRequestIds.delete(message.id) && isBatchSent) {
|
|
164
|
-
cancelledRunningRequestIds.add(message.id);
|
|
165
|
-
abortIfOnlyCancelledRemain();
|
|
166
|
-
}
|
|
167
|
-
});
|
|
168
|
-
for (const [index, [subOptions, resolve, reject]] of groupItems.entries()) {
|
|
169
|
-
const sent = promiseWithResolvers();
|
|
170
|
-
markRequestSent = sent.resolve;
|
|
171
|
-
peer.request(subrequests[index]).then((subResponse) => resolve(this.mapSubresponse(subResponse, batchResponse, subOptions))).catch((error) => {
|
|
172
|
-
if (!suppressErrorFromCurrentBatch) {
|
|
173
|
-
reject(error);
|
|
174
|
-
}
|
|
175
|
-
}).then(sent.resolve);
|
|
176
|
-
await sent.promise;
|
|
177
|
-
}
|
|
178
|
-
if (openRequestIds.size === 0) {
|
|
179
|
-
return;
|
|
180
|
-
}
|
|
181
|
-
isBatchSent = true;
|
|
182
|
-
const outgoingMessages = pendingMessages.filter((message) => openRequestIds.has(message.id));
|
|
183
|
-
try {
|
|
184
|
-
const request = {
|
|
185
|
-
url,
|
|
186
|
-
method,
|
|
187
|
-
headers: { ...headers, [BATCH_HEADER]: "1" },
|
|
188
|
-
signal: controller.signal
|
|
189
|
-
};
|
|
190
|
-
if (method === "GET") {
|
|
191
|
-
const [pathname, search, hash] = parseStandardUrl(url);
|
|
192
|
-
const dataParam = `data=${safeEncodeURIComponent(stringifyJSON(outgoingMessages))}`;
|
|
193
|
-
const newUrl = search ? `${pathname}${search}&${dataParam}${hash ?? ""}` : `${pathname}?${dataParam}${hash ?? ""}`;
|
|
194
|
-
const maxUrlLength = await value(this.maxUrlLength, subOptionsList);
|
|
195
|
-
if (newUrl.length > maxUrlLength) {
|
|
196
|
-
const [first, second] = splitInHalf(groupItems);
|
|
197
|
-
suppressErrorFromCurrentBatch = true;
|
|
198
|
-
await Promise.all([
|
|
199
|
-
this.executeBatch(method, group, first),
|
|
200
|
-
this.executeBatchInOwnContext(method, group, second),
|
|
201
|
-
peer.close()
|
|
202
|
-
]);
|
|
203
|
-
return;
|
|
204
|
-
}
|
|
205
|
-
request.url = newUrl;
|
|
206
|
-
} else {
|
|
207
|
-
request.body = outgoingMessages;
|
|
208
|
-
}
|
|
209
|
-
batchResponse = await groupItems[0][0].next({
|
|
210
|
-
...subOptionsList[0],
|
|
211
|
-
context: value(group.context, subOptionsList),
|
|
212
|
-
path: value(group.path, subOptionsList) ?? [],
|
|
213
|
-
request,
|
|
214
|
-
signal: controller.signal
|
|
215
|
-
});
|
|
216
|
-
if (batchResponse.status >= 400) {
|
|
217
|
-
const resolveBody = once(() => batchResponse.resolveBody());
|
|
218
|
-
const errorResponse = { ...batchResponse, resolveBody };
|
|
219
|
-
groupItems.forEach(([subOptions, resolve]) => {
|
|
220
|
-
resolve(this.mapSubresponse(errorResponse, batchResponse, subOptions));
|
|
221
|
-
});
|
|
222
|
-
suppressErrorFromCurrentBatch = true;
|
|
223
|
-
await peer.close();
|
|
224
|
-
return;
|
|
225
|
-
}
|
|
226
|
-
const body = await batchResponse.resolveBody();
|
|
227
|
-
if (Array.isArray(body) && body.every((v) => isPeerMessage(v) && isServerPeerSendMessage(v))) {
|
|
228
|
-
for (const message of body) {
|
|
229
|
-
await peer.message(message);
|
|
230
|
-
}
|
|
231
|
-
} else if (body instanceof Blob) {
|
|
232
|
-
await decodeLengthPrefixedBlob(body, peer);
|
|
233
|
-
} else if (body instanceof ReadableStream) {
|
|
234
|
-
await decodeLengthPrefixedStream(body, async (message) => {
|
|
235
|
-
await peer.message(message);
|
|
236
|
-
if (isLastServerMessage(message)) {
|
|
237
|
-
openRequestIds.delete(message.id);
|
|
238
|
-
cancelledRunningRequestIds.delete(message.id);
|
|
239
|
-
abortIfOnlyCancelledRemain();
|
|
240
|
-
}
|
|
241
|
-
});
|
|
242
|
-
} else {
|
|
243
|
-
throw new TypeError("Invalid batch response format.");
|
|
244
|
-
}
|
|
245
|
-
await peer.close(new TypeError("Batch response is incomplete."));
|
|
246
|
-
} catch (error) {
|
|
247
|
-
await peer.close(error);
|
|
248
|
-
}
|
|
249
|
-
} catch (error) {
|
|
250
|
-
groupItems.forEach(([, , reject]) => reject(error));
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
function isLastServerMessage(message) {
|
|
255
|
-
switch (message.kind) {
|
|
256
|
-
case "response":
|
|
257
|
-
return message.json.body !== void 0 || message.binary !== void 0 || message.json.headers?.["content-type"] === void 0 && message.json.headers?.["standard-server"] === void 0;
|
|
258
|
-
case "event-stream":
|
|
259
|
-
return message.json.event === "close" || message.json.event === "error";
|
|
260
|
-
case "octet-stream":
|
|
261
|
-
return message.json.close === true;
|
|
262
|
-
case "cancel":
|
|
263
|
-
return true;
|
|
264
|
-
default:
|
|
265
|
-
return false;
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
async function decodeLengthPrefixedBlob(blob, peer) {
|
|
269
|
-
const buffer = await loadBytes(blob);
|
|
270
|
-
let offset = 0;
|
|
271
|
-
while (offset < buffer.length) {
|
|
272
|
-
if (offset + 4 > buffer.length) {
|
|
273
|
-
throw new TypeError("Invalid batch response: incomplete length header.");
|
|
274
|
-
}
|
|
275
|
-
const view = new DataView(buffer.buffer, buffer.byteOffset + offset, 4);
|
|
276
|
-
const length = view.getUint32(0, false);
|
|
277
|
-
offset += 4;
|
|
278
|
-
if (offset + length > buffer.length) {
|
|
279
|
-
throw new TypeError("Invalid batch response: incomplete message.");
|
|
280
|
-
}
|
|
281
|
-
const messageBytes = buffer.subarray(offset, offset + length);
|
|
282
|
-
offset += length;
|
|
283
|
-
const result = decodePeerMessage(messageBytes);
|
|
284
|
-
if (!result.matched || !isServerPeerSendMessage(result.message)) {
|
|
285
|
-
throw new TypeError("Invalid batch response: invalid message.");
|
|
286
|
-
}
|
|
287
|
-
await peer.message(result.message);
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
async function decodeLengthPrefixedStream(stream, receive) {
|
|
291
|
-
const reader = stream.getReader();
|
|
292
|
-
let buffer = new Uint8Array(0);
|
|
293
|
-
try {
|
|
294
|
-
while (true) {
|
|
295
|
-
const { done, value: chunk } = await reader.read();
|
|
296
|
-
if (chunk) {
|
|
297
|
-
const newBuffer = new Uint8Array(buffer.length + chunk.length);
|
|
298
|
-
newBuffer.set(buffer);
|
|
299
|
-
newBuffer.set(chunk, buffer.length);
|
|
300
|
-
buffer = newBuffer;
|
|
301
|
-
}
|
|
302
|
-
while (buffer.length >= 4) {
|
|
303
|
-
const view = new DataView(buffer.buffer, buffer.byteOffset, 4);
|
|
304
|
-
const length = view.getUint32(0, false);
|
|
305
|
-
if (length === 0) {
|
|
306
|
-
buffer = buffer.subarray(4);
|
|
307
|
-
continue;
|
|
308
|
-
}
|
|
309
|
-
if (buffer.length < 4 + length) {
|
|
310
|
-
break;
|
|
311
|
-
}
|
|
312
|
-
const messageBytes = buffer.subarray(4, 4 + length);
|
|
313
|
-
buffer = buffer.subarray(4 + length);
|
|
314
|
-
const result = decodePeerMessage(messageBytes);
|
|
315
|
-
if (!result.matched || !isServerPeerSendMessage(result.message)) {
|
|
316
|
-
throw new TypeError("Invalid batch response: invalid message.");
|
|
317
|
-
}
|
|
318
|
-
await receive(result.message);
|
|
319
|
-
}
|
|
320
|
-
if (done) {
|
|
321
|
-
break;
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
} finally {
|
|
325
|
-
reader.releaseLock();
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
class DedupeLinkPlugin {
|
|
330
|
-
name = "~dedupe";
|
|
331
|
-
before = ["~batch"];
|
|
332
|
-
groups;
|
|
333
|
-
filter;
|
|
334
|
-
scope;
|
|
335
|
-
wait;
|
|
336
|
-
queue = /* @__PURE__ */ new Map();
|
|
337
|
-
constructor(options) {
|
|
338
|
-
this.groups = options.groups;
|
|
339
|
-
this.filter = options.filter ?? (({ request }) => request.method === "GET" || request.method === "QUERY");
|
|
340
|
-
this.scope = options.scope ?? (() => void 0);
|
|
341
|
-
this.wait = options.wait ?? 0;
|
|
342
|
-
}
|
|
343
|
-
init(options) {
|
|
344
|
-
const transportInterceptor = (interceptorOptions) => {
|
|
345
|
-
if (!canDedupeRequest(interceptorOptions.request) || !value(this.filter, interceptorOptions)) {
|
|
346
|
-
return interceptorOptions.next();
|
|
347
|
-
}
|
|
348
|
-
const group = this.groups.find((group2) => value(group2.condition, interceptorOptions));
|
|
349
|
-
if (!group) {
|
|
350
|
-
return interceptorOptions.next();
|
|
351
|
-
}
|
|
352
|
-
const scope = this.scope(interceptorOptions);
|
|
353
|
-
return runWithSignal(interceptorOptions.request.signal, () => new Promise((resolve, reject) => {
|
|
354
|
-
if (!this.queue.size) {
|
|
355
|
-
defer(() => this.processPendingRequests(), this.wait);
|
|
356
|
-
}
|
|
357
|
-
this.enqueue(scope, group, { options: interceptorOptions, resolve, reject, runInOwnContext: captureAsyncContext() });
|
|
358
|
-
}));
|
|
359
|
-
};
|
|
360
|
-
return {
|
|
361
|
-
...options,
|
|
362
|
-
transportInterceptors: [...toArray(options.transportInterceptors), transportInterceptor]
|
|
363
|
-
};
|
|
364
|
-
}
|
|
365
|
-
enqueue(scope, group, caller) {
|
|
366
|
-
let groups = this.queue.get(scope);
|
|
367
|
-
if (!groups) {
|
|
368
|
-
groups = /* @__PURE__ */ new Map();
|
|
369
|
-
this.queue.set(scope, groups);
|
|
370
|
-
}
|
|
371
|
-
let queue = groups.get(group);
|
|
372
|
-
if (!queue) {
|
|
373
|
-
queue = /* @__PURE__ */ new Map();
|
|
374
|
-
groups.set(group, queue);
|
|
375
|
-
}
|
|
376
|
-
const requestKey = createRequestKey(caller.options.path, caller.options.request);
|
|
377
|
-
const matched = queue.get(requestKey);
|
|
378
|
-
if (matched) {
|
|
379
|
-
matched.push(caller);
|
|
380
|
-
return;
|
|
381
|
-
}
|
|
382
|
-
queue.set(requestKey, [caller]);
|
|
383
|
-
}
|
|
384
|
-
async processPendingRequests() {
|
|
385
|
-
const pending = [...this.queue.values()];
|
|
386
|
-
this.queue.clear();
|
|
387
|
-
const executions = [];
|
|
388
|
-
for (const groups of pending) {
|
|
389
|
-
for (const [group, items] of groups) {
|
|
390
|
-
for (const callers of items.values()) {
|
|
391
|
-
const activeCallers = callers.filter((caller) => !caller.options.request.signal?.aborted);
|
|
392
|
-
const [first] = activeCallers;
|
|
393
|
-
if (first) {
|
|
394
|
-
executions.push(first.runInOwnContext(() => this.execute(group, activeCallers)));
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
|
-
}
|
|
399
|
-
await Promise.all(executions);
|
|
400
|
-
}
|
|
401
|
-
async execute(group, activeCallers) {
|
|
402
|
-
const first = activeCallers[0];
|
|
403
|
-
const matchedOptions = activeCallers.map((caller) => caller.options);
|
|
404
|
-
try {
|
|
405
|
-
if (!shouldDedupe(matchedOptions)) {
|
|
406
|
-
const response2 = await first.options.next(first.options);
|
|
407
|
-
first.resolve(response2);
|
|
408
|
-
return;
|
|
409
|
-
}
|
|
410
|
-
const context = value(group.context, matchedOptions);
|
|
411
|
-
const signals = matchedOptions.map((options) => options.request.signal);
|
|
412
|
-
const request = {
|
|
413
|
-
...first.options.request,
|
|
414
|
-
signal: allAbortSignal(signals)
|
|
415
|
-
};
|
|
416
|
-
const response = await first.options.next({
|
|
417
|
-
...first.options,
|
|
418
|
-
request,
|
|
419
|
-
signal: request.signal,
|
|
420
|
-
context
|
|
421
|
-
});
|
|
422
|
-
const replicatedResponses = replicateLazyResponse(response, signals);
|
|
423
|
-
activeCallers.forEach((caller, index) => caller.resolve(replicatedResponses[index]));
|
|
424
|
-
} catch (error) {
|
|
425
|
-
for (const caller of activeCallers) {
|
|
426
|
-
caller.reject(error);
|
|
427
|
-
}
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
}
|
|
431
|
-
function canDedupeRequest(request) {
|
|
432
|
-
return !(request.body instanceof Blob || request.body instanceof FormData || request.body instanceof URLSearchParams || request.body instanceof ReadableStream || isAsyncIteratorObject(request.body) || request.signal?.aborted);
|
|
433
|
-
}
|
|
434
|
-
function createRequestKey(path, request) {
|
|
435
|
-
return stringifyJSON({
|
|
436
|
-
path,
|
|
437
|
-
body: request.body,
|
|
438
|
-
headers: request.headers,
|
|
439
|
-
method: request.method,
|
|
440
|
-
url: request.url
|
|
441
|
-
});
|
|
442
|
-
}
|
|
443
|
-
function replicateLazyResponse(response, signals) {
|
|
444
|
-
let bodiesPromise;
|
|
445
|
-
return signals.map((signal, i) => ({
|
|
446
|
-
...response,
|
|
447
|
-
resolveBody: (hint) => runWithSignal(signal, async () => {
|
|
448
|
-
bodiesPromise ??= response.resolveBody(hint).then((body) => {
|
|
449
|
-
if (isAsyncIteratorObject(body)) {
|
|
450
|
-
return replicateAsyncIterator(body, signals.length).map((replica, index) => closeAsyncIteratorOnAbort(replica, signals[index]));
|
|
451
|
-
}
|
|
452
|
-
if (body instanceof ReadableStream) {
|
|
453
|
-
return replicateReadableStream(body, signals.length).map((replica, index) => closeReadableStreamOnAbort(replica, signals[index]));
|
|
454
|
-
}
|
|
455
|
-
return signals.map(() => body);
|
|
456
|
-
});
|
|
457
|
-
return (await bodiesPromise)[i];
|
|
458
|
-
})
|
|
459
|
-
}));
|
|
460
|
-
}
|
|
461
|
-
function closeAsyncIteratorOnAbort(replica, signal) {
|
|
462
|
-
if (!signal) {
|
|
463
|
-
return replica;
|
|
464
|
-
}
|
|
465
|
-
const abort = () => replica.return().catch(() => {
|
|
466
|
-
});
|
|
467
|
-
if (signal.aborted) {
|
|
468
|
-
void abort();
|
|
469
|
-
} else {
|
|
470
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
471
|
-
}
|
|
472
|
-
return wrapAsyncIterator(replica, {
|
|
473
|
-
mapResult(result) {
|
|
474
|
-
throwIfAborted(signal);
|
|
475
|
-
return result;
|
|
476
|
-
},
|
|
477
|
-
onFinish: () => signal.removeEventListener("abort", abort)
|
|
478
|
-
});
|
|
479
|
-
}
|
|
480
|
-
function closeReadableStreamOnAbort(replica, signal) {
|
|
481
|
-
if (!signal) {
|
|
482
|
-
return replica;
|
|
483
|
-
}
|
|
484
|
-
const reader = replica.getReader();
|
|
485
|
-
const abort = () => reader.cancel(signal.reason).catch(() => {
|
|
486
|
-
});
|
|
487
|
-
if (signal.aborted) {
|
|
488
|
-
void abort();
|
|
489
|
-
} else {
|
|
490
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
491
|
-
}
|
|
492
|
-
return new ReadableStream({
|
|
493
|
-
async pull(controller) {
|
|
494
|
-
try {
|
|
495
|
-
const result = await reader.read();
|
|
496
|
-
throwIfAborted(signal);
|
|
497
|
-
if (result.done) {
|
|
498
|
-
signal.removeEventListener("abort", abort);
|
|
499
|
-
controller.close();
|
|
500
|
-
} else {
|
|
501
|
-
controller.enqueue(result.value);
|
|
502
|
-
}
|
|
503
|
-
} catch (error) {
|
|
504
|
-
signal.removeEventListener("abort", abort);
|
|
505
|
-
throw error;
|
|
506
|
-
}
|
|
507
|
-
},
|
|
508
|
-
async cancel(reason) {
|
|
509
|
-
signal.removeEventListener("abort", abort);
|
|
510
|
-
await reader.cancel(reason);
|
|
511
|
-
}
|
|
512
|
-
}, { highWaterMark: 0 });
|
|
513
|
-
}
|
|
514
|
-
function shouldDedupe(items) {
|
|
515
|
-
return items.length >= 2;
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
const AVG_BYTES_PER_CHAR = 1.2;
|
|
519
|
-
class RequestCompressionLinkPlugin {
|
|
520
|
-
name = "~request-compression";
|
|
521
|
-
/**
|
|
522
|
-
* Compression should be done after batching, to compress the final request
|
|
523
|
-
*/
|
|
524
|
-
after = ["~batch"];
|
|
525
|
-
encoding;
|
|
526
|
-
threshold;
|
|
527
|
-
isCompressibleContentType;
|
|
528
|
-
constructor(options = {}) {
|
|
529
|
-
this.encoding = options.encoding ?? "gzip";
|
|
530
|
-
this.threshold = options.threshold ?? 1024;
|
|
531
|
-
this.isCompressibleContentType = options.isCompressibleContentType ?? isCompressibleContentType;
|
|
532
|
-
}
|
|
533
|
-
init(options) {
|
|
534
|
-
const transportInterceptor = async ({ next, ...interceptorOptions }) => {
|
|
535
|
-
const request = interceptorOptions.request;
|
|
536
|
-
const contentEncoding = flattenStandardHeader(request.headers["content-encoding"])?.trim()?.toLowerCase();
|
|
537
|
-
if (contentEncoding !== void 0) {
|
|
538
|
-
return next();
|
|
539
|
-
}
|
|
540
|
-
if (request.body instanceof ReadableStream) {
|
|
541
|
-
const contentLength = Number(flattenStandardHeader(request.headers["content-length"]));
|
|
542
|
-
if ((!Number.isFinite(contentLength) || contentLength >= this.threshold) && this.isCompressibleContentType(flattenStandardHeader(request.headers["content-type"]), interceptorOptions)) {
|
|
543
|
-
const compressedStream = request.body.pipeThrough(new CompressionStream(this.encoding));
|
|
544
|
-
return next({
|
|
545
|
-
...interceptorOptions,
|
|
546
|
-
request: {
|
|
547
|
-
...interceptorOptions.request,
|
|
548
|
-
body: compressedStream,
|
|
549
|
-
headers: {
|
|
550
|
-
...request.headers,
|
|
551
|
-
"content-length": [],
|
|
552
|
-
"content-encoding": this.encoding
|
|
553
|
-
}
|
|
554
|
-
}
|
|
555
|
-
});
|
|
556
|
-
}
|
|
557
|
-
} else if (request.body instanceof Blob) {
|
|
558
|
-
const contentType = request.headers["content-type"] ?? request.body.type;
|
|
559
|
-
if ((!Number.isFinite(request.body.size) || request.body.size >= this.threshold) && this.isCompressibleContentType(flattenStandardHeader(contentType), interceptorOptions)) {
|
|
560
|
-
const compressedStream = request.body.stream().pipeThrough(new CompressionStream(this.encoding));
|
|
561
|
-
const contentDisposition = request.headers["content-disposition"] ?? generateContentDisposition(
|
|
562
|
-
request.body instanceof File ? request.body.name : "blob"
|
|
563
|
-
);
|
|
564
|
-
return next({
|
|
565
|
-
...interceptorOptions,
|
|
566
|
-
request: {
|
|
567
|
-
...interceptorOptions.request,
|
|
568
|
-
body: compressedStream,
|
|
569
|
-
headers: {
|
|
570
|
-
...request.headers,
|
|
571
|
-
"standard-server": request.headers["standard-server"] ?? "file",
|
|
572
|
-
"content-type": contentType,
|
|
573
|
-
"content-length": [],
|
|
574
|
-
"content-disposition": contentDisposition,
|
|
575
|
-
"content-encoding": this.encoding
|
|
576
|
-
}
|
|
577
|
-
}
|
|
578
|
-
});
|
|
579
|
-
}
|
|
580
|
-
} else if (request.body instanceof FormData) {
|
|
581
|
-
const PART_OVERHEAD = 64;
|
|
582
|
-
let contentLength = 0;
|
|
583
|
-
for (const [key, value] of request.body) {
|
|
584
|
-
contentLength += PART_OVERHEAD + key.length;
|
|
585
|
-
if (value instanceof Blob) {
|
|
586
|
-
if (!Number.isFinite(value.size)) {
|
|
587
|
-
if (!this.isCompressibleContentType(value.type, interceptorOptions)) {
|
|
588
|
-
contentLength = -Infinity;
|
|
589
|
-
break;
|
|
590
|
-
}
|
|
591
|
-
contentLength = Infinity;
|
|
592
|
-
} else {
|
|
593
|
-
contentLength += this.isCompressibleContentType(value.type, interceptorOptions) ? value.size : -value.size;
|
|
594
|
-
}
|
|
595
|
-
} else {
|
|
596
|
-
contentLength += value.length * AVG_BYTES_PER_CHAR;
|
|
597
|
-
}
|
|
598
|
-
}
|
|
599
|
-
if (contentLength >= this.threshold) {
|
|
600
|
-
const res = new Response(request.body);
|
|
601
|
-
const compressedStream = res.body.pipeThrough(new CompressionStream(this.encoding));
|
|
602
|
-
return next({
|
|
603
|
-
...interceptorOptions,
|
|
604
|
-
request: {
|
|
605
|
-
...interceptorOptions.request,
|
|
606
|
-
body: compressedStream,
|
|
607
|
-
headers: {
|
|
608
|
-
...request.headers,
|
|
609
|
-
"standard-server": [],
|
|
610
|
-
"content-type": res.headers.get("content-type"),
|
|
611
|
-
"content-length": [],
|
|
612
|
-
"content-encoding": this.encoding
|
|
613
|
-
}
|
|
614
|
-
}
|
|
615
|
-
});
|
|
616
|
-
}
|
|
617
|
-
} else if (request.body instanceof URLSearchParams) {
|
|
618
|
-
const string = request.body.toString();
|
|
619
|
-
if (string.length * AVG_BYTES_PER_CHAR >= this.threshold) {
|
|
620
|
-
const compressedStream = new Blob([string]).stream().pipeThrough(new CompressionStream(this.encoding));
|
|
621
|
-
const [, bodyHeaders] = toFetchBody(request.body, request.headers);
|
|
622
|
-
return next({
|
|
623
|
-
...interceptorOptions,
|
|
624
|
-
request: {
|
|
625
|
-
...interceptorOptions.request,
|
|
626
|
-
body: compressedStream,
|
|
627
|
-
headers: {
|
|
628
|
-
...bodyHeaders,
|
|
629
|
-
// An empty hint rather than none, so the adapter does not hint the compressed stream as `octet-stream`
|
|
630
|
-
"standard-server": bodyHeaders["standard-server"] ?? [],
|
|
631
|
-
"content-length": [],
|
|
632
|
-
"content-encoding": this.encoding
|
|
633
|
-
}
|
|
634
|
-
}
|
|
635
|
-
});
|
|
636
|
-
}
|
|
637
|
-
} else if (request.body !== void 0 && !isAsyncIteratorObject(request.body)) {
|
|
638
|
-
const [string, bodyHeaders] = toFetchBody(request.body, request.headers);
|
|
639
|
-
if (string.length * AVG_BYTES_PER_CHAR >= this.threshold) {
|
|
640
|
-
const compressedStream = new Blob([string]).stream().pipeThrough(new CompressionStream(this.encoding));
|
|
641
|
-
return next({
|
|
642
|
-
...interceptorOptions,
|
|
643
|
-
request: {
|
|
644
|
-
...interceptorOptions.request,
|
|
645
|
-
body: compressedStream,
|
|
646
|
-
headers: {
|
|
647
|
-
...bodyHeaders,
|
|
648
|
-
"standard-server": bodyHeaders["standard-server"] ?? [],
|
|
649
|
-
"content-length": [],
|
|
650
|
-
"content-encoding": this.encoding
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
});
|
|
654
|
-
}
|
|
655
|
-
}
|
|
656
|
-
return next();
|
|
657
|
-
};
|
|
658
|
-
return {
|
|
659
|
-
...options,
|
|
660
|
-
transportInterceptors: [
|
|
661
|
-
...toArray(options.transportInterceptors),
|
|
662
|
-
transportInterceptor
|
|
663
|
-
]
|
|
664
|
-
};
|
|
665
|
-
}
|
|
666
|
-
}
|
|
667
|
-
|
|
668
|
-
const MAX_CONTENT_ENCODINGS = 5;
|
|
669
|
-
class ResponseCompressionLinkPlugin {
|
|
670
|
-
name = "~response-compression";
|
|
671
|
-
/**
|
|
672
|
-
* Decompression should wrap the final batch response instead of sub-responses.
|
|
673
|
-
*/
|
|
674
|
-
after = ["~batch"];
|
|
675
|
-
encodings;
|
|
676
|
-
constructor(options = {}) {
|
|
677
|
-
this.encodings = options.encodings ?? ["gzip", "deflate"];
|
|
678
|
-
}
|
|
679
|
-
init(options) {
|
|
680
|
-
const acceptEncodingHeader = this.encodings.join(", ");
|
|
681
|
-
const transportInterceptor = async ({ next, ...interceptorOptions }) => {
|
|
682
|
-
const response = await next({
|
|
683
|
-
...interceptorOptions,
|
|
684
|
-
request: {
|
|
685
|
-
...interceptorOptions.request,
|
|
686
|
-
headers: {
|
|
687
|
-
...interceptorOptions.request.headers,
|
|
688
|
-
"accept-encoding": acceptEncodingHeader
|
|
689
|
-
}
|
|
690
|
-
}
|
|
691
|
-
});
|
|
692
|
-
const encodings = parseContentEncodings(
|
|
693
|
-
flattenStandardHeader(response.headers["content-encoding"])
|
|
694
|
-
);
|
|
695
|
-
if (encodings.length === 0 || !encodings.every(isSupportedEncoding)) {
|
|
696
|
-
return response;
|
|
697
|
-
}
|
|
698
|
-
const decompressedHeaders = {
|
|
699
|
-
...response.headers,
|
|
700
|
-
"content-length": void 0,
|
|
701
|
-
"content-encoding": void 0
|
|
702
|
-
};
|
|
703
|
-
return {
|
|
704
|
-
...response,
|
|
705
|
-
headers: decompressedHeaders,
|
|
706
|
-
async resolveBody(hint) {
|
|
707
|
-
const stream = await response.resolveBody("octet-stream");
|
|
708
|
-
if (!(stream instanceof ReadableStream)) {
|
|
709
|
-
return stream;
|
|
710
|
-
}
|
|
711
|
-
if (encodings.length > MAX_CONTENT_ENCODINGS) {
|
|
712
|
-
throw new TypeError("Too many content encodings.");
|
|
713
|
-
}
|
|
714
|
-
let decompressedStream = stream;
|
|
715
|
-
for (let i = encodings.length - 1; i >= 0; i--) {
|
|
716
|
-
decompressedStream = decompressedStream.pipeThrough(
|
|
717
|
-
new DecompressionStream(encodings[i])
|
|
718
|
-
);
|
|
719
|
-
}
|
|
720
|
-
const fetchResponse = new Response(decompressedStream, {
|
|
721
|
-
headers: toFetchHeaders(decompressedHeaders)
|
|
722
|
-
});
|
|
723
|
-
return toStandardBody(fetchResponse, { hint });
|
|
724
|
-
}
|
|
725
|
-
};
|
|
726
|
-
};
|
|
727
|
-
return {
|
|
728
|
-
...options,
|
|
729
|
-
transportInterceptors: [
|
|
730
|
-
...toArray(options.transportInterceptors),
|
|
731
|
-
transportInterceptor
|
|
732
|
-
]
|
|
733
|
-
};
|
|
734
|
-
}
|
|
735
|
-
}
|
|
736
|
-
const SUPPORTED_ENCODINGS = ["gzip", "deflate", "deflate-raw"];
|
|
737
|
-
function isSupportedEncoding(encoding) {
|
|
738
|
-
return SUPPORTED_ENCODINGS.includes(encoding);
|
|
739
|
-
}
|
|
740
|
-
function parseContentEncodings(header) {
|
|
741
|
-
if (header === void 0) {
|
|
742
|
-
return [];
|
|
743
|
-
}
|
|
744
|
-
return header.split(",").map((part) => part.trim().toLowerCase());
|
|
745
|
-
}
|
|
746
|
-
|
|
747
|
-
function isRetryableError(error) {
|
|
748
|
-
const responseError = error instanceof ORPCError ? error.cause : error;
|
|
749
|
-
if (!(responseError instanceof ResponseError)) {
|
|
750
|
-
return true;
|
|
751
|
-
}
|
|
752
|
-
const { status } = responseError.response;
|
|
753
|
-
return status < 400 || status >= 500 || status === COMMON_ERROR_STATUS_MAP.TIMEOUT || status === COMMON_ERROR_STATUS_MAP.TOO_MANY_REQUESTS;
|
|
754
|
-
}
|
|
755
|
-
class RetryLinkPlugin {
|
|
756
|
-
defaultRetry;
|
|
757
|
-
defaultRetryDelay;
|
|
758
|
-
defaultShouldRetry;
|
|
759
|
-
defaultOnRetry;
|
|
760
|
-
name = "~retry";
|
|
761
|
-
constructor(options = {}) {
|
|
762
|
-
this.defaultRetry = options.default?.retry ?? 0;
|
|
763
|
-
this.defaultRetryDelay = options.default?.retryDelay ?? ((o) => o.lastEventRetry ?? 2e3);
|
|
764
|
-
this.defaultShouldRetry = options.default?.shouldRetry ?? ((o) => isRetryableError(o.error));
|
|
765
|
-
this.defaultOnRetry = options.default?.onRetry;
|
|
766
|
-
}
|
|
767
|
-
init(options) {
|
|
768
|
-
const interceptor = async (interceptorOptions) => {
|
|
769
|
-
const { next, ...callOptions } = interceptorOptions;
|
|
770
|
-
const maxAttempts = await value(
|
|
771
|
-
callOptions.context.retry ?? this.defaultRetry,
|
|
772
|
-
callOptions
|
|
773
|
-
);
|
|
774
|
-
const retryDelay = callOptions.context.retryDelay ?? this.defaultRetryDelay;
|
|
775
|
-
const shouldRetry = callOptions.context.shouldRetry ?? this.defaultShouldRetry;
|
|
776
|
-
const onRetry = callOptions.context.onRetry ?? this.defaultOnRetry;
|
|
777
|
-
if (maxAttempts <= 0) {
|
|
778
|
-
return next(callOptions);
|
|
779
|
-
}
|
|
780
|
-
let lastEventId = callOptions.lastEventId;
|
|
781
|
-
let lastEventRetry;
|
|
782
|
-
let callback;
|
|
783
|
-
let attempt = 1;
|
|
784
|
-
let isIteratorAborted = false;
|
|
785
|
-
const callNext = async (initialError) => {
|
|
786
|
-
let currentError = initialError;
|
|
787
|
-
while (true) {
|
|
788
|
-
const updatedCallOptions = { ...callOptions, lastEventId };
|
|
789
|
-
let retryDelayMs = 0;
|
|
790
|
-
if (currentError) {
|
|
791
|
-
if (isIteratorAborted || attempt > maxAttempts) {
|
|
792
|
-
throw currentError.error;
|
|
793
|
-
}
|
|
794
|
-
const attemptOptions = {
|
|
795
|
-
...updatedCallOptions,
|
|
796
|
-
attempt,
|
|
797
|
-
error: currentError.error,
|
|
798
|
-
lastEventRetry
|
|
799
|
-
};
|
|
800
|
-
const shouldRetryBool = await value(
|
|
801
|
-
shouldRetry,
|
|
802
|
-
attemptOptions
|
|
803
|
-
);
|
|
804
|
-
if (!shouldRetryBool) {
|
|
805
|
-
throw currentError.error;
|
|
806
|
-
}
|
|
807
|
-
retryDelayMs = await value(retryDelay, attemptOptions);
|
|
808
|
-
callback = onRetry?.(attemptOptions);
|
|
809
|
-
}
|
|
810
|
-
try {
|
|
811
|
-
if (currentError) {
|
|
812
|
-
await sleep(retryDelayMs, { signal: updatedCallOptions.signal });
|
|
813
|
-
if (isIteratorAborted) {
|
|
814
|
-
throw currentError.error;
|
|
815
|
-
}
|
|
816
|
-
attempt++;
|
|
817
|
-
}
|
|
818
|
-
currentError = void 0;
|
|
819
|
-
return await next(updatedCallOptions);
|
|
820
|
-
} catch (error) {
|
|
821
|
-
currentError = { error };
|
|
822
|
-
if (updatedCallOptions.signal?.aborted) {
|
|
823
|
-
throw error;
|
|
824
|
-
}
|
|
825
|
-
} finally {
|
|
826
|
-
callback?.(!currentError);
|
|
827
|
-
callback = void 0;
|
|
828
|
-
}
|
|
829
|
-
}
|
|
830
|
-
};
|
|
831
|
-
const output = await callNext();
|
|
832
|
-
if (!isAsyncIteratorObject(output)) {
|
|
833
|
-
return output;
|
|
834
|
-
}
|
|
835
|
-
let current = output;
|
|
836
|
-
return override(() => current, new AsyncIteratorClass(
|
|
837
|
-
async () => {
|
|
838
|
-
while (true) {
|
|
839
|
-
try {
|
|
840
|
-
const item = await current.next();
|
|
841
|
-
const meta = getEventMeta(item.value);
|
|
842
|
-
lastEventId = meta?.id ?? lastEventId;
|
|
843
|
-
lastEventRetry = meta?.retry ?? lastEventRetry;
|
|
844
|
-
return item;
|
|
845
|
-
} catch (error) {
|
|
846
|
-
const meta = getEventMeta(error);
|
|
847
|
-
lastEventId = meta?.id ?? lastEventId;
|
|
848
|
-
lastEventRetry = meta?.retry ?? lastEventRetry;
|
|
849
|
-
const asyncIteratorObject = await callNext({ error });
|
|
850
|
-
if (!isAsyncIteratorObject(asyncIteratorObject)) {
|
|
851
|
-
throw new TypeError(
|
|
852
|
-
"RetryLinkPlugin: Expected an AsyncIteratorObject, got a different type."
|
|
853
|
-
);
|
|
854
|
-
}
|
|
855
|
-
current = asyncIteratorObject;
|
|
856
|
-
if (isIteratorAborted) {
|
|
857
|
-
await current.return?.();
|
|
858
|
-
throw error;
|
|
859
|
-
}
|
|
860
|
-
}
|
|
861
|
-
}
|
|
862
|
-
},
|
|
863
|
-
async ({ kind }) => {
|
|
864
|
-
isIteratorAborted = true;
|
|
865
|
-
if (kind === "cancelled") {
|
|
866
|
-
await current.return?.();
|
|
867
|
-
}
|
|
868
|
-
}
|
|
869
|
-
));
|
|
870
|
-
};
|
|
871
|
-
return { ...options, interceptors: [interceptor, ...toArray(options.interceptors)] };
|
|
872
|
-
}
|
|
873
|
-
}
|
|
874
|
-
|
|
875
|
-
class RetryAfterLinkPlugin {
|
|
876
|
-
condition;
|
|
877
|
-
maxAttempts;
|
|
878
|
-
timeout;
|
|
879
|
-
name = "~retry-after";
|
|
880
|
-
constructor(options = {}) {
|
|
881
|
-
this.condition = options.condition ?? ((response) => response.status === COMMON_ERROR_STATUS_MAP.TOO_MANY_REQUESTS || response.status === COMMON_ERROR_STATUS_MAP.SERVICE_UNAVAILABLE);
|
|
882
|
-
this.maxAttempts = options.maxAttempts ?? 3;
|
|
883
|
-
this.timeout = options.timeout ?? 5 * 60 * 1e3;
|
|
884
|
-
}
|
|
885
|
-
init(options) {
|
|
886
|
-
const interceptor = async (interceptorOptions) => {
|
|
887
|
-
const { body } = interceptorOptions.request;
|
|
888
|
-
if (body instanceof ReadableStream || isAsyncIteratorObject(body)) {
|
|
889
|
-
return interceptorOptions.next();
|
|
890
|
-
}
|
|
891
|
-
const startTime = Date.now();
|
|
892
|
-
let attemptCount = 0;
|
|
893
|
-
while (true) {
|
|
894
|
-
attemptCount++;
|
|
895
|
-
const response = await interceptorOptions.next();
|
|
896
|
-
if (!value(this.condition, response, interceptorOptions)) {
|
|
897
|
-
return response;
|
|
898
|
-
}
|
|
899
|
-
const retryAfterHeader = flattenStandardHeader(response.headers["retry-after"]);
|
|
900
|
-
const retryAfterMs = parseRetryAfterHeader(retryAfterHeader);
|
|
901
|
-
if (retryAfterMs === void 0) {
|
|
902
|
-
return response;
|
|
903
|
-
}
|
|
904
|
-
if (attemptCount >= value(this.maxAttempts, response, interceptorOptions)) {
|
|
905
|
-
return response;
|
|
906
|
-
}
|
|
907
|
-
const timeoutMs = value(this.timeout, response, interceptorOptions);
|
|
908
|
-
const elapsedTime = Date.now() - startTime;
|
|
909
|
-
if (elapsedTime + retryAfterMs > timeoutMs) {
|
|
910
|
-
return response;
|
|
911
|
-
}
|
|
912
|
-
try {
|
|
913
|
-
await sleep(retryAfterMs, { signal: interceptorOptions.signal });
|
|
914
|
-
} catch {
|
|
915
|
-
}
|
|
916
|
-
if (interceptorOptions.signal?.aborted) {
|
|
917
|
-
return response;
|
|
918
|
-
}
|
|
919
|
-
}
|
|
920
|
-
};
|
|
921
|
-
return { ...options, transportInterceptors: [interceptor, ...toArray(options.transportInterceptors)] };
|
|
922
|
-
}
|
|
923
|
-
}
|
|
924
|
-
function parseRetryAfterHeader(value2) {
|
|
925
|
-
value2 = value2?.trim();
|
|
926
|
-
if (!value2) {
|
|
927
|
-
return void 0;
|
|
928
|
-
}
|
|
929
|
-
const seconds = Number(value2);
|
|
930
|
-
if (Number.isFinite(seconds)) {
|
|
931
|
-
return Math.max(0, seconds * 1e3);
|
|
932
|
-
}
|
|
933
|
-
const retryDate = Date.parse(value2);
|
|
934
|
-
if (!Number.isNaN(retryDate)) {
|
|
935
|
-
return Math.max(0, retryDate - Date.now());
|
|
936
|
-
}
|
|
937
|
-
return void 0;
|
|
938
|
-
}
|
|
939
|
-
|
|
940
|
-
class TimeoutLinkPlugin {
|
|
941
|
-
timeout;
|
|
942
|
-
name = "~timeout";
|
|
943
|
-
/**
|
|
944
|
-
* Should abort if the total retry time exceeds the configured timeout
|
|
945
|
-
*/
|
|
946
|
-
after = ["~retry"];
|
|
947
|
-
constructor(options) {
|
|
948
|
-
this.timeout = options.timeout;
|
|
949
|
-
}
|
|
950
|
-
init(options) {
|
|
951
|
-
const interceptor = async (interceptorOptions) => {
|
|
952
|
-
const timeoutMs = value(this.timeout, interceptorOptions);
|
|
953
|
-
if (timeoutMs === null || timeoutMs === void 0) {
|
|
954
|
-
return interceptorOptions.next();
|
|
955
|
-
}
|
|
956
|
-
const controller = new AbortController();
|
|
957
|
-
const timeoutId = setTimeout(() => {
|
|
958
|
-
controller.abort(new AbortError(`Request timed out after ${timeoutMs}ms`));
|
|
959
|
-
}, timeoutMs);
|
|
960
|
-
const signal = anyAbortSignal([interceptorOptions.signal, controller.signal]);
|
|
961
|
-
try {
|
|
962
|
-
return await interceptorOptions.next({ ...interceptorOptions, signal });
|
|
963
|
-
} finally {
|
|
964
|
-
clearTimeout(timeoutId);
|
|
965
|
-
}
|
|
966
|
-
};
|
|
967
|
-
return { ...options, interceptors: [interceptor, ...toArray(options.interceptors)] };
|
|
968
|
-
}
|
|
969
|
-
}
|
|
970
|
-
|
|
971
|
-
export { BATCH_HEADER, BatchLinkPlugin, RetryLinkPlugin as ClientRetryPlugin, DEFAULT_BATCH_MAX_SIZE, DedupeLinkPlugin, DedupeLinkPlugin as DedupeRequestsPlugin, RequestCompressionLinkPlugin, ResponseCompressionLinkPlugin, RetryAfterLinkPlugin, RetryAfterLinkPlugin as RetryAfterPlugin, RetryLinkPlugin, TimeoutLinkPlugin, isRetryableError };
|
|
1
|
+
export * from "./batch.mjs";
|
|
2
|
+
export * from "./cookie-jar.mjs";
|
|
3
|
+
export * from "./dedupe.mjs";
|
|
4
|
+
export {
|
|
5
|
+
|
|
6
|
+
DedupeLinkPlugin as DedupeRequestsPlugin } from "./dedupe.mjs";
|
|
7
|
+
export * from "./request-compression.mjs";
|
|
8
|
+
export * from "./response-compression.mjs";
|
|
9
|
+
export * from "./retry.mjs";
|
|
10
|
+
export {
|
|
11
|
+
|
|
12
|
+
RetryLinkPlugin as ClientRetryPlugin } from "./retry.mjs";
|
|
13
|
+
export * from "./retry-after.mjs";
|
|
14
|
+
export {
|
|
15
|
+
|
|
16
|
+
RetryAfterLinkPlugin as RetryAfterPlugin } from "./retry-after.mjs";
|
|
17
|
+
export * from "./timeout.mjs";
|