@orpc/client 2.0.0-beta.46 → 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 +6 -4
- 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
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { matchesHttpPathPrefix, toArray, value } from "@orpc/shared";
|
|
2
|
+
|
|
3
|
+
export class CookieJarLinkPlugin {
|
|
4
|
+
origin;
|
|
5
|
+
jar;
|
|
6
|
+
name = "~cookie-jar";
|
|
7
|
+
|
|
8
|
+
before = ["~batch"];
|
|
9
|
+
constructor(options) {
|
|
10
|
+
this.origin = options.origin;
|
|
11
|
+
this.jar = options.jar ?? new CookieJar();
|
|
12
|
+
}
|
|
13
|
+
init(options) {
|
|
14
|
+
const transportInterceptor = async ({ next, ...interceptorOptions }) => {
|
|
15
|
+
const { path, request } = interceptorOptions;
|
|
16
|
+
const origin = await value(this.origin, interceptorOptions, path);
|
|
17
|
+
|
|
18
|
+
if (origin === undefined || !/^[a-z][\d+\-.a-z]*:/i.test(origin)) {
|
|
19
|
+
return next();
|
|
20
|
+
}
|
|
21
|
+
const jar = value(this.jar, interceptorOptions);
|
|
22
|
+
const url = `${origin.replace(/\/$/, "")}${request.url}`;
|
|
23
|
+
const cookie = mergeCookieHeader(request.headers.cookie, jar.getCookies(url));
|
|
24
|
+
const response = await next(cookie === undefined ? interceptorOptions : {
|
|
25
|
+
...interceptorOptions,
|
|
26
|
+
request: {
|
|
27
|
+
...request,
|
|
28
|
+
headers: {
|
|
29
|
+
...request.headers,
|
|
30
|
+
cookie
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
for (const setCookie of toArray(response.headers["set-cookie"])) {
|
|
35
|
+
jar.setCookie(setCookie, url);
|
|
36
|
+
}
|
|
37
|
+
return response;
|
|
38
|
+
};
|
|
39
|
+
return {
|
|
40
|
+
...options,
|
|
41
|
+
transportInterceptors: [...toArray(options.transportInterceptors), transportInterceptor]
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export class CookieJar {
|
|
47
|
+
|
|
48
|
+
cookies = new Map();
|
|
49
|
+
|
|
50
|
+
setCookie(setCookie, url) {
|
|
51
|
+
const parsed = parseSetCookie(setCookie);
|
|
52
|
+
if (!parsed) {
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const target = new URL(url);
|
|
56
|
+
const secureUrl = isSecureUrl(target);
|
|
57
|
+
const hostOnly = parsed.domain === undefined;
|
|
58
|
+
const domain = parsed.domain ?? target.hostname;
|
|
59
|
+
const path = parsed.path ?? defaultPath(target.pathname);
|
|
60
|
+
if (!domainMatch(target.hostname, domain) || /^__(?:secure|host)-/i.test(parsed.name) && !parsed.secure || /^__host-/i.test(parsed.name) && (!hostOnly || parsed.path !== "/") || !secureUrl && (parsed.secure || [...this.cookies.values()].some((cookie) => cookie.secure && cookie.name === parsed.name && (domainMatch(domain, cookie.domain) || domainMatch(cookie.domain, domain)) && matchesHttpPathPrefix(path, cookie.path)))) {
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const key = `${domain};${path};${parsed.name}`;
|
|
64
|
+
if ((parsed.expires ?? Number.POSITIVE_INFINITY) <= Date.now()) {
|
|
65
|
+
this.cookies.delete(key);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
this.cookies.set(key, {
|
|
69
|
+
...parsed,
|
|
70
|
+
domain,
|
|
71
|
+
hostOnly,
|
|
72
|
+
path
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
getCookies(url) {
|
|
77
|
+
const now = Date.now();
|
|
78
|
+
for (const [key, cookie] of this.cookies) {
|
|
79
|
+
if ((cookie.expires ?? Number.POSITIVE_INFINITY) <= now) {
|
|
80
|
+
this.cookies.delete(key);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const cookies = [...this.cookies.values()].map((cookie) => ({ ...cookie }));
|
|
84
|
+
if (url === undefined) {
|
|
85
|
+
return cookies;
|
|
86
|
+
}
|
|
87
|
+
const target = new URL(url);
|
|
88
|
+
const secureUrl = isSecureUrl(target);
|
|
89
|
+
return cookies.filter((cookie) => (cookie.hostOnly ? target.hostname === cookie.domain : domainMatch(target.hostname, cookie.domain)) && matchesHttpPathPrefix(target.pathname, cookie.path) && (!cookie.secure || secureUrl)).sort((a, b) => b.path.length - a.path.length);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
clear() {
|
|
93
|
+
this.cookies.clear();
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function mergeCookieHeader(header, cookies) {
|
|
98
|
+
const explicit = toArray(header).flatMap((value) => value.split(";")).map((pair) => pair.trim()).filter(Boolean);
|
|
99
|
+
const explicitNames = new Set(explicit.map((pair) => splitCookiePair(pair)[0]));
|
|
100
|
+
const pairs = cookies.filter((cookie) => !explicitNames.has(cookie.name)).map((cookie) => cookie.name ? `${cookie.name}=${cookie.value}` : cookie.value);
|
|
101
|
+
return pairs.length ? [...explicit, ...pairs].join("; ") : undefined;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function splitCookiePair(pair) {
|
|
105
|
+
const index = pair.indexOf("=");
|
|
106
|
+
return [index === -1 ? "" : pair.slice(0, index).trim(), pair.slice(index + 1).trim()];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function parseSetCookie(setCookie) {
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
if (/[\x00-\x08\x0A-\x1F\x7F]/.test(setCookie)) {
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
115
|
+
const [pair = "", ...attributes] = setCookie.split(";");
|
|
116
|
+
const [name, value] = splitCookiePair(pair);
|
|
117
|
+
if (!name && !value) {
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
120
|
+
let domain;
|
|
121
|
+
let path;
|
|
122
|
+
let secure = false;
|
|
123
|
+
let expires;
|
|
124
|
+
let maxAgeExpires;
|
|
125
|
+
|
|
126
|
+
for (const attribute of attributes) {
|
|
127
|
+
const index = attribute.indexOf("=");
|
|
128
|
+
const attributeName = (index === -1 ? attribute : attribute.slice(0, index)).trim().toLowerCase();
|
|
129
|
+
const attributeValue = index === -1 ? "" : attribute.slice(index + 1).trim();
|
|
130
|
+
switch (attributeName) {
|
|
131
|
+
case "expires": {
|
|
132
|
+
expires = parseCookieDate(attributeValue) ?? expires;
|
|
133
|
+
break;
|
|
134
|
+
}
|
|
135
|
+
case "max-age": {
|
|
136
|
+
if (/^-?\d+$/.test(attributeValue)) {
|
|
137
|
+
maxAgeExpires = Date.now() + Number(attributeValue) * 1e3;
|
|
138
|
+
}
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
case "domain": {
|
|
142
|
+
domain = attributeValue.replace(/^\./, "").toLowerCase() || undefined;
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
145
|
+
case "path": {
|
|
146
|
+
path = attributeValue.startsWith("/") ? attributeValue : undefined;
|
|
147
|
+
break;
|
|
148
|
+
}
|
|
149
|
+
case "secure": {
|
|
150
|
+
secure = true;
|
|
151
|
+
break;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return {
|
|
157
|
+
name,
|
|
158
|
+
value,
|
|
159
|
+
domain,
|
|
160
|
+
path,
|
|
161
|
+
secure,
|
|
162
|
+
expires: maxAgeExpires ?? expires
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
const MONTHS = [
|
|
166
|
+
"jan",
|
|
167
|
+
"feb",
|
|
168
|
+
"mar",
|
|
169
|
+
"apr",
|
|
170
|
+
"may",
|
|
171
|
+
"jun",
|
|
172
|
+
"jul",
|
|
173
|
+
"aug",
|
|
174
|
+
"sep",
|
|
175
|
+
"oct",
|
|
176
|
+
"nov",
|
|
177
|
+
"dec"
|
|
178
|
+
];
|
|
179
|
+
|
|
180
|
+
function parseCookieDate(value) {
|
|
181
|
+
let time;
|
|
182
|
+
let day;
|
|
183
|
+
let month;
|
|
184
|
+
let year;
|
|
185
|
+
for (const token of value.split(/[\t\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]+/)) {
|
|
186
|
+
const digits = /^\d*/.exec(token)[0];
|
|
187
|
+
const timeMatch = /^(\d{1,2}):(\d{1,2}):(\d{1,2})(?:\D|$)/.exec(token);
|
|
188
|
+
const monthIndex = MONTHS.indexOf(token.slice(0, 3).toLowerCase());
|
|
189
|
+
if (time === undefined && timeMatch) {
|
|
190
|
+
time = [
|
|
191
|
+
Number(timeMatch[1]),
|
|
192
|
+
Number(timeMatch[2]),
|
|
193
|
+
Number(timeMatch[3])
|
|
194
|
+
];
|
|
195
|
+
} else if (day === undefined && digits.length >= 1 && digits.length <= 2) {
|
|
196
|
+
day = Number(digits);
|
|
197
|
+
} else if (month === undefined && monthIndex !== -1) {
|
|
198
|
+
month = monthIndex;
|
|
199
|
+
} else if (year === undefined && digits.length >= 2 && digits.length <= 4) {
|
|
200
|
+
year = Number(digits);
|
|
201
|
+
year += year < 70 ? 2e3 : year < 100 ? 1900 : 0;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
if (time === undefined || day === undefined || month === undefined || year === undefined) {
|
|
205
|
+
return undefined;
|
|
206
|
+
}
|
|
207
|
+
const [hour, minute, second] = time;
|
|
208
|
+
if (year < 1601 || hour > 23 || minute > 59 || second > 59) {
|
|
209
|
+
return undefined;
|
|
210
|
+
}
|
|
211
|
+
const date = Date.UTC(year, month, day, hour, minute, second);
|
|
212
|
+
|
|
213
|
+
return new Date(date).getUTCDate() === day ? date : undefined;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function isSecureUrl(url) {
|
|
217
|
+
const host = url.hostname;
|
|
218
|
+
return url.protocol === "https:" || url.protocol === "wss:" || host === "localhost" || host.endsWith(".localhost") || host === "[::1]" || /^127(?:\.\d{1,3}){3}$/.test(host);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function domainMatch(host, domain) {
|
|
222
|
+
|
|
223
|
+
return host === domain || host.endsWith(`.${domain}`) && !/^\d{1,3}(?:\.\d{1,3}){3}$/.test(host);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function defaultPath(path) {
|
|
227
|
+
const index = path.lastIndexOf("/");
|
|
228
|
+
return index <= 0 ? "/" : path.slice(0, index);
|
|
229
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { Value } from "@orpc/shared";
|
|
2
|
+
import type { StandardLinkOptions, StandardLinkPlugin, StandardLinkTransportInterceptorOptions } from "../adapters/standard/index.mjs";
|
|
3
|
+
import type { ClientContext } from "../types.mjs";
|
|
4
|
+
export interface DedupeLinkPluginGroup<T extends ClientContext> {
|
|
5
|
+
condition: Value<boolean, [options: StandardLinkTransportInterceptorOptions<T>]>;
|
|
6
|
+
/**
|
|
7
|
+
* The context used for the rest of the request lifecycle.
|
|
8
|
+
*/
|
|
9
|
+
context: Value<T, [items: [StandardLinkTransportInterceptorOptions<T>, StandardLinkTransportInterceptorOptions<T>, ...StandardLinkTransportInterceptorOptions<T>[]]]>;
|
|
10
|
+
}
|
|
11
|
+
export interface DedupeLinkPluginOptions<T extends ClientContext> {
|
|
12
|
+
/**
|
|
13
|
+
* To enable deduplication, a request must match at least one defined group.
|
|
14
|
+
* Requests that fall into the same group are considered for deduplication together.
|
|
15
|
+
*/
|
|
16
|
+
groups: [DedupeLinkPluginGroup<T>, ...DedupeLinkPluginGroup<T>[]];
|
|
17
|
+
/**
|
|
18
|
+
* Filters requests to dedupe.
|
|
19
|
+
*
|
|
20
|
+
* @default ({ request }) => request.method === 'GET' || request.method === 'QUERY'
|
|
21
|
+
*/
|
|
22
|
+
filter?: Value<boolean, [options: StandardLinkTransportInterceptorOptions<T>]> | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* Only requests with the same scope are deduplicated together.
|
|
25
|
+
* On the server, return a value unique to the incoming request so different users never share a response.
|
|
26
|
+
*
|
|
27
|
+
* @default () => undefined
|
|
28
|
+
*/
|
|
29
|
+
scope?: ((options: StandardLinkTransportInterceptorOptions<T>) => unknown) | undefined;
|
|
30
|
+
/**
|
|
31
|
+
* How long (in ms) to wait for more identical requests before sending,
|
|
32
|
+
* counted from the first queued request.
|
|
33
|
+
* With `0`, only requests made in the same event loop tick are deduplicated.
|
|
34
|
+
*
|
|
35
|
+
* @default 0
|
|
36
|
+
*/
|
|
37
|
+
wait?: number | undefined;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Prevents redundant requests by deduplicating similar in-flight requests,
|
|
41
|
+
* reducing the number of requests sent to the server.
|
|
42
|
+
*
|
|
43
|
+
* @see {@link https://orpc.dev/docs/plugins/dedupe | Dedupe Plugin}
|
|
44
|
+
*/
|
|
45
|
+
export declare class DedupeLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
|
|
46
|
+
name: string;
|
|
47
|
+
before: string[];
|
|
48
|
+
private readonly groups;
|
|
49
|
+
private readonly filter;
|
|
50
|
+
private readonly scope;
|
|
51
|
+
private readonly wait;
|
|
52
|
+
private readonly queue;
|
|
53
|
+
constructor(options: NoInfer<DedupeLinkPluginOptions<T>>);
|
|
54
|
+
init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
|
|
55
|
+
private enqueue;
|
|
56
|
+
private processPendingRequests;
|
|
57
|
+
private execute;
|
|
58
|
+
}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { allAbortSignal, captureAsyncContext, defer, isAsyncIteratorObject, replicateAsyncIterator, replicateReadableStream, runWithSignal, stringifyJSON, throwIfAborted, toArray, value, wrapAsyncIterator } from "@orpc/shared";
|
|
2
|
+
|
|
3
|
+
export class DedupeLinkPlugin {
|
|
4
|
+
name = "~dedupe";
|
|
5
|
+
before = ["~batch"];
|
|
6
|
+
groups;
|
|
7
|
+
filter;
|
|
8
|
+
scope;
|
|
9
|
+
wait;
|
|
10
|
+
queue = new Map();
|
|
11
|
+
constructor(options) {
|
|
12
|
+
this.groups = options.groups;
|
|
13
|
+
this.filter = options.filter ?? (({ request }) => request.method === "GET" || request.method === "QUERY");
|
|
14
|
+
this.scope = options.scope ?? (() => undefined);
|
|
15
|
+
this.wait = options.wait ?? 0;
|
|
16
|
+
}
|
|
17
|
+
init(options) {
|
|
18
|
+
const transportInterceptor = (interceptorOptions) => {
|
|
19
|
+
if (!canDedupeRequest(interceptorOptions.request) || !value(this.filter, interceptorOptions)) {
|
|
20
|
+
return interceptorOptions.next();
|
|
21
|
+
}
|
|
22
|
+
const group = this.groups.find((group) => value(group.condition, interceptorOptions));
|
|
23
|
+
if (!group) {
|
|
24
|
+
return interceptorOptions.next();
|
|
25
|
+
}
|
|
26
|
+
const scope = this.scope(interceptorOptions);
|
|
27
|
+
return runWithSignal(interceptorOptions.request.signal, () => new Promise((resolve, reject) => {
|
|
28
|
+
|
|
29
|
+
if (!this.queue.size) {
|
|
30
|
+
defer(() => this.processPendingRequests(), this.wait);
|
|
31
|
+
}
|
|
32
|
+
this.enqueue(scope, group, {
|
|
33
|
+
options: interceptorOptions,
|
|
34
|
+
resolve,
|
|
35
|
+
reject,
|
|
36
|
+
runInOwnContext: captureAsyncContext()
|
|
37
|
+
});
|
|
38
|
+
}));
|
|
39
|
+
};
|
|
40
|
+
return {
|
|
41
|
+
...options,
|
|
42
|
+
transportInterceptors: [...toArray(options.transportInterceptors), transportInterceptor]
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
enqueue(scope, group, caller) {
|
|
46
|
+
let groups = this.queue.get(scope);
|
|
47
|
+
if (!groups) {
|
|
48
|
+
groups = new Map();
|
|
49
|
+
this.queue.set(scope, groups);
|
|
50
|
+
}
|
|
51
|
+
let queue = groups.get(group);
|
|
52
|
+
if (!queue) {
|
|
53
|
+
queue = new Map();
|
|
54
|
+
groups.set(group, queue);
|
|
55
|
+
}
|
|
56
|
+
const requestKey = createRequestKey(caller.options.path, caller.options.request);
|
|
57
|
+
const matched = queue.get(requestKey);
|
|
58
|
+
if (matched) {
|
|
59
|
+
matched.push(caller);
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
queue.set(requestKey, [caller]);
|
|
63
|
+
}
|
|
64
|
+
async processPendingRequests() {
|
|
65
|
+
const pending = [...this.queue.values()];
|
|
66
|
+
this.queue.clear();
|
|
67
|
+
const executions = [];
|
|
68
|
+
for (const groups of pending) {
|
|
69
|
+
for (const [group, items] of groups) {
|
|
70
|
+
for (const callers of items.values()) {
|
|
71
|
+
const activeCallers = callers.filter((caller) => !caller.options.request.signal?.aborted);
|
|
72
|
+
const [first] = activeCallers;
|
|
73
|
+
if (first) {
|
|
74
|
+
|
|
75
|
+
executions.push(first.runInOwnContext(() => this.execute(group, activeCallers)));
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
await Promise.all(executions);
|
|
81
|
+
}
|
|
82
|
+
async execute(group, activeCallers) {
|
|
83
|
+
const first = activeCallers[0];
|
|
84
|
+
const matchedOptions = activeCallers.map((caller) => caller.options);
|
|
85
|
+
try {
|
|
86
|
+
if (!shouldDedupe(matchedOptions)) {
|
|
87
|
+
const response = await first.options.next(first.options);
|
|
88
|
+
first.resolve(response);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
const context = value(group.context, matchedOptions);
|
|
92
|
+
const signals = matchedOptions.map((options) => options.request.signal);
|
|
93
|
+
const request = {
|
|
94
|
+
...first.options.request,
|
|
95
|
+
signal: allAbortSignal(signals)
|
|
96
|
+
};
|
|
97
|
+
const response = await first.options.next({
|
|
98
|
+
...first.options,
|
|
99
|
+
request,
|
|
100
|
+
signal: request.signal,
|
|
101
|
+
context
|
|
102
|
+
});
|
|
103
|
+
const replicatedResponses = replicateLazyResponse(response, signals);
|
|
104
|
+
activeCallers.forEach((caller, index) => caller.resolve(replicatedResponses[index]));
|
|
105
|
+
} catch (error) {
|
|
106
|
+
for (const caller of activeCallers) {
|
|
107
|
+
caller.reject(error);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function canDedupeRequest(request) {
|
|
113
|
+
return !(request.body instanceof Blob || request.body instanceof FormData || request.body instanceof URLSearchParams || request.body instanceof ReadableStream || isAsyncIteratorObject(request.body) || request.signal?.aborted);
|
|
114
|
+
}
|
|
115
|
+
function createRequestKey(path, request) {
|
|
116
|
+
return stringifyJSON({
|
|
117
|
+
path,
|
|
118
|
+
body: request.body,
|
|
119
|
+
headers: request.headers,
|
|
120
|
+
method: request.method,
|
|
121
|
+
url: request.url
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function replicateLazyResponse(response, signals) {
|
|
126
|
+
let bodiesPromise;
|
|
127
|
+
return signals.map((signal, i) => ({
|
|
128
|
+
...response,
|
|
129
|
+
resolveBody: (hint) => runWithSignal(signal, async () => {
|
|
130
|
+
bodiesPromise ??= response.resolveBody(hint).then((body) => {
|
|
131
|
+
if (isAsyncIteratorObject(body)) {
|
|
132
|
+
return replicateAsyncIterator(body, signals.length).map((replica, index) => closeAsyncIteratorOnAbort(replica, signals[index]));
|
|
133
|
+
}
|
|
134
|
+
if (body instanceof ReadableStream) {
|
|
135
|
+
return replicateReadableStream(body, signals.length).map((replica, index) => closeReadableStreamOnAbort(replica, signals[index]));
|
|
136
|
+
}
|
|
137
|
+
return signals.map(() => body);
|
|
138
|
+
});
|
|
139
|
+
return (await bodiesPromise)[i];
|
|
140
|
+
})
|
|
141
|
+
}));
|
|
142
|
+
}
|
|
143
|
+
function closeAsyncIteratorOnAbort(replica, signal) {
|
|
144
|
+
if (!signal) {
|
|
145
|
+
return replica;
|
|
146
|
+
}
|
|
147
|
+
const abort = () => replica.return().catch(() => {});
|
|
148
|
+
if (signal.aborted) {
|
|
149
|
+
void abort();
|
|
150
|
+
} else {
|
|
151
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
152
|
+
}
|
|
153
|
+
return wrapAsyncIterator(replica, {
|
|
154
|
+
mapResult(result) {
|
|
155
|
+
|
|
156
|
+
throwIfAborted(signal);
|
|
157
|
+
return result;
|
|
158
|
+
},
|
|
159
|
+
onFinish: () => signal.removeEventListener("abort", abort)
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function closeReadableStreamOnAbort(replica, signal) {
|
|
164
|
+
if (!signal) {
|
|
165
|
+
return replica;
|
|
166
|
+
}
|
|
167
|
+
const reader = replica.getReader();
|
|
168
|
+
const abort = () => reader.cancel(signal.reason).catch(() => {});
|
|
169
|
+
if (signal.aborted) {
|
|
170
|
+
void abort();
|
|
171
|
+
} else {
|
|
172
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
173
|
+
}
|
|
174
|
+
return new ReadableStream({
|
|
175
|
+
async pull(controller) {
|
|
176
|
+
try {
|
|
177
|
+
const result = await reader.read();
|
|
178
|
+
|
|
179
|
+
throwIfAborted(signal);
|
|
180
|
+
if (result.done) {
|
|
181
|
+
signal.removeEventListener("abort", abort);
|
|
182
|
+
controller.close();
|
|
183
|
+
} else {
|
|
184
|
+
controller.enqueue(result.value);
|
|
185
|
+
}
|
|
186
|
+
} catch (error) {
|
|
187
|
+
signal.removeEventListener("abort", abort);
|
|
188
|
+
throw error;
|
|
189
|
+
}
|
|
190
|
+
},
|
|
191
|
+
async cancel(reason) {
|
|
192
|
+
signal.removeEventListener("abort", abort);
|
|
193
|
+
await reader.cancel(reason);
|
|
194
|
+
}
|
|
195
|
+
}, { highWaterMark: 0 });
|
|
196
|
+
}
|
|
197
|
+
function shouldDedupe(items) {
|
|
198
|
+
return items.length >= 2;
|
|
199
|
+
}
|