@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.
- package/README.md +4 -4
- package/dist/adapters/fetch/index.d.ts +2 -0
- package/dist/adapters/fetch/index.js +2 -0
- package/dist/adapters/fetch/rpc-link.d.ts +14 -0
- package/dist/adapters/fetch/rpc-link.js +14 -0
- package/dist/adapters/fetch/transport.d.ts +34 -0
- package/dist/adapters/fetch/transport.js +65 -0
- package/dist/adapters/message-port/index.d.ts +3 -0
- package/dist/adapters/message-port/index.js +3 -0
- package/dist/adapters/message-port/message-port.d.ts +29 -0
- package/dist/adapters/message-port/message-port.js +56 -0
- package/dist/adapters/message-port/rpc-link.d.ts +15 -0
- package/dist/adapters/message-port/rpc-link.js +15 -0
- package/dist/adapters/message-port/transport.d.ts +38 -0
- package/dist/adapters/message-port/transport.js +52 -0
- package/dist/adapters/standard/codec.d.ts +14 -0
- package/dist/adapters/standard/index.d.ts +5 -0
- package/dist/adapters/standard/index.js +4 -0
- package/dist/adapters/standard/link.d.ts +40 -0
- package/dist/adapters/standard/link.js +85 -0
- package/dist/adapters/standard/plugin.d.ts +32 -0
- package/dist/adapters/standard/plugin.js +16 -0
- package/dist/adapters/standard/rpc-link-codec.d.ts +63 -0
- package/dist/adapters/standard/rpc-link-codec.js +104 -0
- package/dist/adapters/standard/transport.d.ts +14 -0
- package/dist/adapters/websocket/index.d.ts +2 -0
- package/dist/adapters/websocket/index.js +2 -0
- package/dist/adapters/websocket/rpc-link.d.ts +14 -0
- package/dist/adapters/websocket/rpc-link.js +14 -0
- package/dist/adapters/websocket/transport.d.ts +115 -0
- package/dist/adapters/websocket/transport.js +133 -0
- package/dist/async-iterator-object.d.ts +2 -0
- package/dist/async-iterator-object.js +29 -0
- package/dist/client-safe.d.ts +18 -0
- package/dist/client-safe.js +36 -0
- package/dist/client.d.ts +40 -0
- package/dist/client.js +39 -0
- package/dist/consts.d.ts +10 -0
- package/dist/consts.js +43 -0
- package/dist/dynamic-link.d.ts +13 -0
- package/dist/dynamic-link.js +17 -0
- package/dist/error-utils.d.ts +21 -0
- package/dist/error-utils.js +58 -0
- package/dist/error.d.ts +132 -0
- package/dist/error.js +178 -0
- package/dist/index.d.ts +53 -0
- package/dist/index.js +40 -0
- package/dist/plugins/batch.d.ts +185 -0
- package/dist/plugins/batch.js +401 -0
- package/dist/plugins/cookie-jar.d.ts +82 -0
- package/dist/plugins/cookie-jar.js +268 -0
- package/dist/plugins/dedupe.d.ts +64 -0
- package/dist/plugins/dedupe.js +226 -0
- package/dist/plugins/index.d.ts +28 -0
- package/dist/plugins/index.js +23 -0
- package/dist/plugins/request-compression.d.ts +44 -0
- package/dist/plugins/request-compression.js +178 -0
- package/dist/plugins/response-compression.d.ts +28 -0
- package/dist/plugins/response-compression.js +91 -0
- package/dist/plugins/retry-after.d.ts +50 -0
- package/dist/plugins/retry-after.js +88 -0
- package/dist/plugins/retry.d.ts +84 -0
- package/dist/plugins/retry.js +140 -0
- package/dist/plugins/timeout.d.ts +25 -0
- package/dist/plugins/timeout.js +37 -0
- package/dist/rpc-json-serializer.d.ts +99 -0
- package/dist/rpc-json-serializer.js +392 -0
- package/dist/rpc-serializer.d.ts +32 -0
- package/dist/rpc-serializer.js +130 -0
- package/dist/types.d.ts +97 -0
- package/dist/utils.d.ts +47 -0
- package/dist/utils.js +51 -0
- package/package.json +43 -45
- package/dist/adapters/fetch/index.d.mts +0 -2
- package/dist/adapters/fetch/index.mjs +0 -2
- package/dist/adapters/fetch/rpc-link.d.mts +0 -13
- package/dist/adapters/fetch/rpc-link.mjs +0 -10
- package/dist/adapters/fetch/transport.d.mts +0 -31
- package/dist/adapters/fetch/transport.mjs +0 -65
- package/dist/adapters/message-port/index.d.mts +0 -3
- package/dist/adapters/message-port/index.mjs +0 -3
- package/dist/adapters/message-port/message-port.d.mts +0 -29
- package/dist/adapters/message-port/message-port.mjs +0 -43
- package/dist/adapters/message-port/rpc-link.d.mts +0 -14
- package/dist/adapters/message-port/rpc-link.mjs +0 -10
- package/dist/adapters/message-port/transport.d.mts +0 -35
- package/dist/adapters/message-port/transport.mjs +0 -47
- package/dist/adapters/standard/codec.d.mts +0 -14
- package/dist/adapters/standard/index.d.mts +0 -5
- package/dist/adapters/standard/index.mjs +0 -4
- package/dist/adapters/standard/link.d.mts +0 -40
- package/dist/adapters/standard/link.mjs +0 -79
- package/dist/adapters/standard/plugin.d.mts +0 -32
- package/dist/adapters/standard/plugin.mjs +0 -16
- package/dist/adapters/standard/rpc-link-codec.d.mts +0 -55
- package/dist/adapters/standard/rpc-link-codec.mjs +0 -104
- package/dist/adapters/standard/transport.d.mts +0 -14
- package/dist/adapters/websocket/index.d.mts +0 -2
- package/dist/adapters/websocket/index.mjs +0 -2
- package/dist/adapters/websocket/rpc-link.d.mts +0 -13
- package/dist/adapters/websocket/rpc-link.mjs +0 -10
- package/dist/adapters/websocket/transport.d.mts +0 -119
- package/dist/adapters/websocket/transport.mjs +0 -123
- package/dist/async-iterator-object.d.mts +0 -7
- package/dist/async-iterator-object.mjs +0 -30
- package/dist/client-safe.d.mts +0 -16
- package/dist/client-safe.mjs +0 -23
- package/dist/client.d.mts +0 -51
- package/dist/client.mjs +0 -32
- package/dist/consts.d.mts +0 -10
- package/dist/consts.mjs +0 -10
- package/dist/dynamic-link.d.mts +0 -13
- package/dist/dynamic-link.mjs +0 -12
- package/dist/error-utils.d.mts +0 -24
- package/dist/error-utils.mjs +0 -44
- package/dist/error.d.mts +0 -138
- package/dist/error.mjs +0 -105
- package/dist/index.d.mts +0 -49
- package/dist/index.mjs +0 -23
- package/dist/plugins/batch.d.mts +0 -150
- package/dist/plugins/batch.mjs +0 -339
- package/dist/plugins/cookie-jar.d.mts +0 -82
- package/dist/plugins/cookie-jar.mjs +0 -229
- package/dist/plugins/dedupe.d.mts +0 -58
- package/dist/plugins/dedupe.mjs +0 -199
- package/dist/plugins/index.d.mts +0 -28
- package/dist/plugins/index.mjs +0 -17
- package/dist/plugins/request-compression.d.mts +0 -44
- package/dist/plugins/request-compression.mjs +0 -150
- package/dist/plugins/response-compression.d.mts +0 -28
- package/dist/plugins/response-compression.mjs +0 -78
- package/dist/plugins/retry-after.d.mts +0 -41
- package/dist/plugins/retry-after.mjs +0 -71
- package/dist/plugins/retry.d.mts +0 -82
- package/dist/plugins/retry.mjs +0 -127
- package/dist/plugins/timeout.d.mts +0 -25
- package/dist/plugins/timeout.mjs +0 -36
- package/dist/rpc-json-serializer.d.mts +0 -99
- package/dist/rpc-json-serializer.mjs +0 -365
- package/dist/rpc-serializer.d.mts +0 -32
- package/dist/rpc-serializer.mjs +0 -100
- package/dist/types.d.mts +0 -93
- package/dist/utils.d.mts +0 -46
- package/dist/utils.mjs +0 -53
- /package/dist/adapters/standard/{codec.mjs → codec.js} +0 -0
- /package/dist/adapters/standard/{transport.mjs → transport.js} +0 -0
- /package/dist/{types.mjs → types.js} +0 -0
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { matchesHttpPathPrefix, toArray, value } from '@orpc/shared';
|
|
2
|
+
/**
|
|
3
|
+
* Stores the cookies servers set and sends them back on later requests, like a browser,
|
|
4
|
+
* for server-side rendering, scripts, and tests.
|
|
5
|
+
*
|
|
6
|
+
* @remarks
|
|
7
|
+
* **Warning**: On a server, do not share one link between users: create a client per request, or pick a jar per request.
|
|
8
|
+
*
|
|
9
|
+
* @see {@link https://orpc.dev/docs/plugins/cookie-jar | Cookie Jar Plugin}
|
|
10
|
+
*/
|
|
11
|
+
export class CookieJarLinkPlugin {
|
|
12
|
+
origin;
|
|
13
|
+
jar;
|
|
14
|
+
name = '~cookie-jar';
|
|
15
|
+
/**
|
|
16
|
+
* Runs per call, before batching, so each call gets the cookies it would get on its own.
|
|
17
|
+
*/
|
|
18
|
+
before = ['~batch'];
|
|
19
|
+
constructor(options) {
|
|
20
|
+
this.origin = options.origin;
|
|
21
|
+
this.jar = options.jar ?? new CookieJar();
|
|
22
|
+
}
|
|
23
|
+
init(options) {
|
|
24
|
+
const transportInterceptor = async ({ next, ...interceptorOptions }) => {
|
|
25
|
+
const { path, request } = interceptorOptions;
|
|
26
|
+
const origin = await value(this.origin, interceptorOptions, path);
|
|
27
|
+
// No absolute origin, as in a browser
|
|
28
|
+
if (origin === undefined || !/^[a-z][\d+\-.a-z]*:/i.test(origin)) {
|
|
29
|
+
return next();
|
|
30
|
+
}
|
|
31
|
+
const jar = value(this.jar, interceptorOptions);
|
|
32
|
+
const url = `${origin.replace(/\/$/, '')}${request.url}`;
|
|
33
|
+
const cookie = mergeCookieHeader(request.headers.cookie, jar.getCookies(url));
|
|
34
|
+
const response = await next(cookie === undefined
|
|
35
|
+
? interceptorOptions
|
|
36
|
+
: {
|
|
37
|
+
...interceptorOptions,
|
|
38
|
+
request: { ...request, headers: { ...request.headers, cookie } },
|
|
39
|
+
});
|
|
40
|
+
for (const setCookie of toArray(response.headers['set-cookie'])) {
|
|
41
|
+
jar.setCookie(setCookie, url);
|
|
42
|
+
}
|
|
43
|
+
return response;
|
|
44
|
+
};
|
|
45
|
+
return {
|
|
46
|
+
...options,
|
|
47
|
+
transportInterceptors: [...toArray(options.transportInterceptors), transportInterceptor],
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* An in-memory cookie store that follows the browser rules of [RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265).
|
|
53
|
+
*
|
|
54
|
+
* @see {@link https://orpc.dev/docs/plugins/cookie-jar#custom-jar | Cookie Jar Plugin - Custom Jar}
|
|
55
|
+
*/
|
|
56
|
+
export class CookieJar {
|
|
57
|
+
/**
|
|
58
|
+
* Keyed by domain, path, and name. Map order is creation order: replacing a cookie keeps its position.
|
|
59
|
+
*/
|
|
60
|
+
cookies = new Map();
|
|
61
|
+
/**
|
|
62
|
+
* Stores a `Set-Cookie` header value received from `url`.
|
|
63
|
+
* Cookies a browser would reject are ignored, and an expired cookie deletes the one it replaces.
|
|
64
|
+
*/
|
|
65
|
+
setCookie(setCookie, url) {
|
|
66
|
+
const parsed = parseSetCookie(setCookie);
|
|
67
|
+
if (!parsed) {
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
const target = new URL(url);
|
|
71
|
+
const secureUrl = isSecureUrl(target);
|
|
72
|
+
const hostOnly = parsed.domain === undefined;
|
|
73
|
+
const domain = parsed.domain ?? target.hostname;
|
|
74
|
+
const path = parsed.path ?? defaultPath(target.pathname);
|
|
75
|
+
if (!domainMatch(target.hostname, domain) ||
|
|
76
|
+
(/^__(?:secure|host)-/i.test(parsed.name) && !parsed.secure) ||
|
|
77
|
+
(/^__host-/i.test(parsed.name) && (!hostOnly || parsed.path !== '/')) ||
|
|
78
|
+
// Insecure origins can neither set nor overwrite secure cookies, see "leave secure cookies alone" in RFC 6265bis
|
|
79
|
+
(!secureUrl &&
|
|
80
|
+
(parsed.secure ||
|
|
81
|
+
[...this.cookies.values()].some((cookie) => cookie.secure &&
|
|
82
|
+
cookie.name === parsed.name &&
|
|
83
|
+
(domainMatch(domain, cookie.domain) || domainMatch(cookie.domain, domain)) &&
|
|
84
|
+
matchesHttpPathPrefix(path, cookie.path))))) {
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const key = `${domain};${path};${parsed.name}`;
|
|
88
|
+
if ((parsed.expires ?? Number.POSITIVE_INFINITY) <= Date.now()) {
|
|
89
|
+
this.cookies.delete(key);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
this.cookies.set(key, { ...parsed, domain, hostOnly, path });
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Returns the cookies a browser would send to `url`, longer paths first, then oldest first.
|
|
96
|
+
* Without `url`, returns every stored cookie that has not expired.
|
|
97
|
+
*/
|
|
98
|
+
getCookies(url) {
|
|
99
|
+
const now = Date.now();
|
|
100
|
+
for (const [key, cookie] of this.cookies) {
|
|
101
|
+
if ((cookie.expires ?? Number.POSITIVE_INFINITY) <= now) {
|
|
102
|
+
this.cookies.delete(key);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const cookies = [...this.cookies.values()].map((cookie) => ({ ...cookie }));
|
|
106
|
+
if (url === undefined) {
|
|
107
|
+
return cookies;
|
|
108
|
+
}
|
|
109
|
+
const target = new URL(url);
|
|
110
|
+
const secureUrl = isSecureUrl(target);
|
|
111
|
+
return (cookies
|
|
112
|
+
.filter((cookie) => (cookie.hostOnly
|
|
113
|
+
? target.hostname === cookie.domain
|
|
114
|
+
: domainMatch(target.hostname, cookie.domain)) &&
|
|
115
|
+
matchesHttpPathPrefix(target.pathname, cookie.path) &&
|
|
116
|
+
(!cookie.secure || secureUrl))
|
|
117
|
+
// oxlint-disable-next-line unicorn/no-array-sort
|
|
118
|
+
.sort((a, b) => b.path.length - a.path.length));
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Removes every stored cookie.
|
|
122
|
+
*/
|
|
123
|
+
clear() {
|
|
124
|
+
this.cookies.clear();
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Appends jar cookies to an existing `cookie` header, skipping names it already has.
|
|
129
|
+
* Returns `undefined` when the jar adds nothing.
|
|
130
|
+
*/
|
|
131
|
+
function mergeCookieHeader(header, cookies) {
|
|
132
|
+
const explicit = toArray(header)
|
|
133
|
+
.flatMap((value) => value.split(';'))
|
|
134
|
+
.map((pair) => pair.trim())
|
|
135
|
+
.filter(Boolean);
|
|
136
|
+
const explicitNames = new Set(explicit.map((pair) => splitCookiePair(pair)[0]));
|
|
137
|
+
const pairs = cookies
|
|
138
|
+
.filter((cookie) => !explicitNames.has(cookie.name))
|
|
139
|
+
.map((cookie) => (cookie.name ? `${cookie.name}=${cookie.value}` : cookie.value));
|
|
140
|
+
return pairs.length ? [...explicit, ...pairs].join('; ') : undefined;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Splits a cookie pair at the first `=`. A pair without `=` has an empty name, as in browsers and RFC 6265bis.
|
|
144
|
+
*/
|
|
145
|
+
function splitCookiePair(pair) {
|
|
146
|
+
const index = pair.indexOf('=');
|
|
147
|
+
return [index === -1 ? '' : pair.slice(0, index).trim(), pair.slice(index + 1).trim()];
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Parses a `Set-Cookie` header value following [RFC 6265 Section 5.2](https://datatracker.ietf.org/doc/html/rfc6265#section-5.2),
|
|
151
|
+
* with the [RFC 6265bis](https://datatracker.ietf.org/doc/draft-ietf-httpbis-rfc6265bis/) changes browsers use, noted inline.
|
|
152
|
+
*/
|
|
153
|
+
function parseSetCookie(setCookie) {
|
|
154
|
+
// Control characters other than tab make the whole cookie invalid
|
|
155
|
+
// oxlint-disable-next-line no-control-regex
|
|
156
|
+
if (/[\x00-\x08\x0A-\x1F\x7F]/.test(setCookie)) {
|
|
157
|
+
return undefined;
|
|
158
|
+
}
|
|
159
|
+
const [pair = '', ...attributes] = setCookie.split(';');
|
|
160
|
+
const [name, value] = splitCookiePair(pair);
|
|
161
|
+
if (!name && !value) {
|
|
162
|
+
return undefined;
|
|
163
|
+
}
|
|
164
|
+
let domain;
|
|
165
|
+
let path;
|
|
166
|
+
let secure = false;
|
|
167
|
+
let expires;
|
|
168
|
+
let maxAgeExpires;
|
|
169
|
+
// A repeated attribute overrides the earlier ones
|
|
170
|
+
for (const attribute of attributes) {
|
|
171
|
+
const index = attribute.indexOf('=');
|
|
172
|
+
const attributeName = (index === -1 ? attribute : attribute.slice(0, index))
|
|
173
|
+
.trim()
|
|
174
|
+
.toLowerCase();
|
|
175
|
+
const attributeValue = index === -1 ? '' : attribute.slice(index + 1).trim();
|
|
176
|
+
switch (attributeName) {
|
|
177
|
+
case 'expires': {
|
|
178
|
+
expires = parseCookieDate(attributeValue) ?? expires;
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
case 'max-age': {
|
|
182
|
+
if (/^-?\d+$/.test(attributeValue)) {
|
|
183
|
+
maxAgeExpires = Date.now() + Number(attributeValue) * 1000;
|
|
184
|
+
}
|
|
185
|
+
break;
|
|
186
|
+
}
|
|
187
|
+
case 'domain': {
|
|
188
|
+
domain = attributeValue.replace(/^\./, '').toLowerCase() || undefined;
|
|
189
|
+
break;
|
|
190
|
+
}
|
|
191
|
+
case 'path': {
|
|
192
|
+
path = attributeValue.startsWith('/') ? attributeValue : undefined;
|
|
193
|
+
break;
|
|
194
|
+
}
|
|
195
|
+
case 'secure': {
|
|
196
|
+
secure = true;
|
|
197
|
+
break;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
// Max-Age takes precedence over Expires
|
|
202
|
+
return { name, value, domain, path, secure, expires: maxAgeExpires ?? expires };
|
|
203
|
+
}
|
|
204
|
+
const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
|
|
205
|
+
/**
|
|
206
|
+
* Parses a cookie date following [RFC 6265 Section 5.1.1](https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.1),
|
|
207
|
+
* always in UTC. Returns `undefined` when a part is missing or out of range, so the attribute is ignored.
|
|
208
|
+
*/
|
|
209
|
+
function parseCookieDate(value) {
|
|
210
|
+
let time;
|
|
211
|
+
let day;
|
|
212
|
+
let month;
|
|
213
|
+
let year;
|
|
214
|
+
for (const token of value.split(/[\t\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]+/)) {
|
|
215
|
+
const digits = /^\d*/.exec(token)[0];
|
|
216
|
+
const timeMatch = /^(\d{1,2}):(\d{1,2}):(\d{1,2})(?:\D|$)/.exec(token);
|
|
217
|
+
const monthIndex = MONTHS.indexOf(token.slice(0, 3).toLowerCase());
|
|
218
|
+
if (time === undefined && timeMatch) {
|
|
219
|
+
time = [Number(timeMatch[1]), Number(timeMatch[2]), Number(timeMatch[3])];
|
|
220
|
+
}
|
|
221
|
+
else if (day === undefined && digits.length >= 1 && digits.length <= 2) {
|
|
222
|
+
day = Number(digits);
|
|
223
|
+
}
|
|
224
|
+
else if (month === undefined && monthIndex !== -1) {
|
|
225
|
+
month = monthIndex;
|
|
226
|
+
}
|
|
227
|
+
else if (year === undefined && digits.length >= 2 && digits.length <= 4) {
|
|
228
|
+
year = Number(digits);
|
|
229
|
+
year += year < 70 ? 2000 : year < 100 ? 1900 : 0;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (time === undefined || day === undefined || month === undefined || year === undefined) {
|
|
233
|
+
return undefined;
|
|
234
|
+
}
|
|
235
|
+
const [hour, minute, second] = time;
|
|
236
|
+
if (year < 1601 || hour > 23 || minute > 59 || second > 59) {
|
|
237
|
+
return undefined;
|
|
238
|
+
}
|
|
239
|
+
const date = Date.UTC(year, month, day, hour, minute, second);
|
|
240
|
+
// Rejects days the month does not have, such as 0 or 31 Feb
|
|
241
|
+
return new Date(date).getUTCDate() === day ? date : undefined;
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Browsers also treat loopback hosts as secure, so `Secure` cookies work against a local server.
|
|
245
|
+
*/
|
|
246
|
+
function isSecureUrl(url) {
|
|
247
|
+
const host = url.hostname;
|
|
248
|
+
return (url.protocol === 'https:' ||
|
|
249
|
+
url.protocol === 'wss:' ||
|
|
250
|
+
host === 'localhost' ||
|
|
251
|
+
host.endsWith('.localhost') ||
|
|
252
|
+
host === '[::1]' ||
|
|
253
|
+
/^127(?:\.\d{1,3}){3}$/.test(host));
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* [RFC 6265 Section 5.1.3](https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.3)
|
|
257
|
+
*/
|
|
258
|
+
function domainMatch(host, domain) {
|
|
259
|
+
// IPv6 hosts have no dots, so only IPv4 addresses need excluding
|
|
260
|
+
return host === domain || (host.endsWith(`.${domain}`) && !/^\d{1,3}(?:\.\d{1,3}){3}$/.test(host));
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* [RFC 6265 Section 5.1.4](https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4)
|
|
264
|
+
*/
|
|
265
|
+
function defaultPath(path) {
|
|
266
|
+
const index = path.lastIndexOf('/');
|
|
267
|
+
return index <= 0 ? '/' : path.slice(0, index);
|
|
268
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { Value } from '@orpc/shared';
|
|
2
|
+
import type { StandardLinkOptions, StandardLinkPlugin, StandardLinkTransportInterceptorOptions } from '../adapters/standard/index.ts';
|
|
3
|
+
import type { ClientContext } from '../types.ts';
|
|
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, [
|
|
10
|
+
items: [
|
|
11
|
+
StandardLinkTransportInterceptorOptions<T>,
|
|
12
|
+
StandardLinkTransportInterceptorOptions<T>,
|
|
13
|
+
...StandardLinkTransportInterceptorOptions<T>[]
|
|
14
|
+
]
|
|
15
|
+
]>;
|
|
16
|
+
}
|
|
17
|
+
export interface DedupeLinkPluginOptions<T extends ClientContext> {
|
|
18
|
+
/**
|
|
19
|
+
* To enable deduplication, a request must match at least one defined group.
|
|
20
|
+
* Requests that fall into the same group are considered for deduplication together.
|
|
21
|
+
*/
|
|
22
|
+
groups: [DedupeLinkPluginGroup<T>, ...DedupeLinkPluginGroup<T>[]];
|
|
23
|
+
/**
|
|
24
|
+
* Filters requests to dedupe.
|
|
25
|
+
*
|
|
26
|
+
* @default ({ request }) => request.method === 'GET' || request.method === 'QUERY'
|
|
27
|
+
*/
|
|
28
|
+
filter?: Value<boolean, [options: StandardLinkTransportInterceptorOptions<T>]> | undefined;
|
|
29
|
+
/**
|
|
30
|
+
* Only requests with the same scope are deduplicated together.
|
|
31
|
+
* On the server, return a value unique to the incoming request so different users never share a response.
|
|
32
|
+
*
|
|
33
|
+
* @default () => undefined
|
|
34
|
+
*/
|
|
35
|
+
scope?: ((options: StandardLinkTransportInterceptorOptions<T>) => unknown) | undefined;
|
|
36
|
+
/**
|
|
37
|
+
* How long (in ms) to wait for more identical requests before sending,
|
|
38
|
+
* counted from the first queued request.
|
|
39
|
+
* With `0`, only requests made in the same event loop tick are deduplicated.
|
|
40
|
+
*
|
|
41
|
+
* @default 0
|
|
42
|
+
*/
|
|
43
|
+
wait?: number | undefined;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Prevents redundant requests by deduplicating similar in-flight requests,
|
|
47
|
+
* reducing the number of requests sent to the server.
|
|
48
|
+
*
|
|
49
|
+
* @see {@link https://orpc.dev/docs/plugins/dedupe | Dedupe Plugin}
|
|
50
|
+
*/
|
|
51
|
+
export declare class DedupeLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
|
|
52
|
+
name: string;
|
|
53
|
+
before: string[];
|
|
54
|
+
private readonly groups;
|
|
55
|
+
private readonly filter;
|
|
56
|
+
private readonly scope;
|
|
57
|
+
private readonly wait;
|
|
58
|
+
private readonly queue;
|
|
59
|
+
constructor(options: NoInfer<DedupeLinkPluginOptions<T>>);
|
|
60
|
+
init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
|
|
61
|
+
private enqueue;
|
|
62
|
+
private processPendingRequests;
|
|
63
|
+
private execute;
|
|
64
|
+
}
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { captureAsyncContext, defer, disposableAllAbortSignal, isAsyncIteratorObject, replicateAsyncIterator, replicateReadableStream, runWithSignal, stringifyJSON, throwIfAborted, toArray, value, wrapAsyncIterator, } from '@orpc/shared';
|
|
2
|
+
/**
|
|
3
|
+
* Prevents redundant requests by deduplicating similar in-flight requests,
|
|
4
|
+
* reducing the number of requests sent to the server.
|
|
5
|
+
*
|
|
6
|
+
* @see {@link https://orpc.dev/docs/plugins/dedupe | Dedupe Plugin}
|
|
7
|
+
*/
|
|
8
|
+
export class DedupeLinkPlugin {
|
|
9
|
+
name = '~dedupe';
|
|
10
|
+
before = ['~batch'];
|
|
11
|
+
groups;
|
|
12
|
+
filter;
|
|
13
|
+
scope;
|
|
14
|
+
wait;
|
|
15
|
+
queue = new Map();
|
|
16
|
+
constructor(options) {
|
|
17
|
+
this.groups = options.groups;
|
|
18
|
+
this.filter =
|
|
19
|
+
options.filter ?? (({ request }) => request.method === 'GET' || request.method === 'QUERY');
|
|
20
|
+
this.scope = options.scope ?? (() => undefined);
|
|
21
|
+
this.wait = options.wait ?? 0;
|
|
22
|
+
}
|
|
23
|
+
init(options) {
|
|
24
|
+
const transportInterceptor = (interceptorOptions) => {
|
|
25
|
+
if (!canDedupeRequest(interceptorOptions.request) ||
|
|
26
|
+
!value(this.filter, interceptorOptions)) {
|
|
27
|
+
return interceptorOptions.next();
|
|
28
|
+
}
|
|
29
|
+
const group = this.groups.find((group) => value(group.condition, interceptorOptions));
|
|
30
|
+
if (!group) {
|
|
31
|
+
return interceptorOptions.next();
|
|
32
|
+
}
|
|
33
|
+
const scope = this.scope(interceptorOptions);
|
|
34
|
+
return runWithSignal(interceptorOptions.request.signal, () => new Promise((resolve, reject) => {
|
|
35
|
+
// Schedule only for the first queued request, so later ones cannot extend or split the wait.
|
|
36
|
+
if (!this.queue.size) {
|
|
37
|
+
defer(() => this.processPendingRequests(), this.wait);
|
|
38
|
+
}
|
|
39
|
+
this.enqueue(scope, group, {
|
|
40
|
+
options: interceptorOptions,
|
|
41
|
+
resolve,
|
|
42
|
+
reject,
|
|
43
|
+
runInOwnContext: captureAsyncContext(),
|
|
44
|
+
});
|
|
45
|
+
}));
|
|
46
|
+
};
|
|
47
|
+
return {
|
|
48
|
+
...options,
|
|
49
|
+
transportInterceptors: [...toArray(options.transportInterceptors), transportInterceptor],
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
enqueue(scope, group, caller) {
|
|
53
|
+
let groups = this.queue.get(scope);
|
|
54
|
+
if (!groups) {
|
|
55
|
+
groups = new Map();
|
|
56
|
+
this.queue.set(scope, groups);
|
|
57
|
+
}
|
|
58
|
+
let queue = groups.get(group);
|
|
59
|
+
if (!queue) {
|
|
60
|
+
queue = new Map();
|
|
61
|
+
groups.set(group, queue);
|
|
62
|
+
}
|
|
63
|
+
const requestKey = createRequestKey(caller.options.path, caller.options.request);
|
|
64
|
+
const matched = queue.get(requestKey);
|
|
65
|
+
if (matched) {
|
|
66
|
+
matched.push(caller);
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
queue.set(requestKey, [caller]);
|
|
70
|
+
}
|
|
71
|
+
async processPendingRequests() {
|
|
72
|
+
const pending = [...this.queue.values()];
|
|
73
|
+
this.queue.clear();
|
|
74
|
+
const executions = [];
|
|
75
|
+
for (const groups of pending) {
|
|
76
|
+
for (const [group, items] of groups) {
|
|
77
|
+
for (const callers of items.values()) {
|
|
78
|
+
const activeCallers = callers.filter((caller) => !caller.options.request.signal?.aborted);
|
|
79
|
+
const [first] = activeCallers;
|
|
80
|
+
if (first) {
|
|
81
|
+
// Send in the first active caller's async context instead of the timer's, so the transport sees its request state.
|
|
82
|
+
executions.push(first.runInOwnContext(() => this.execute(group, activeCallers)));
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
await Promise.all(executions);
|
|
88
|
+
}
|
|
89
|
+
async execute(group, activeCallers) {
|
|
90
|
+
const first = activeCallers[0];
|
|
91
|
+
const matchedOptions = activeCallers.map((caller) => caller.options);
|
|
92
|
+
let sharedSignal;
|
|
93
|
+
try {
|
|
94
|
+
if (!shouldDedupe(matchedOptions)) {
|
|
95
|
+
const response = await first.options.next(first.options);
|
|
96
|
+
first.resolve(response);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
const context = value(group.context, matchedOptions);
|
|
100
|
+
const signals = matchedOptions.map((options) => options.request.signal);
|
|
101
|
+
sharedSignal = disposableAllAbortSignal(signals);
|
|
102
|
+
const request = {
|
|
103
|
+
...first.options.request,
|
|
104
|
+
signal: sharedSignal.signal,
|
|
105
|
+
};
|
|
106
|
+
const response = await first.options.next({
|
|
107
|
+
...first.options,
|
|
108
|
+
request,
|
|
109
|
+
signal: request.signal,
|
|
110
|
+
context,
|
|
111
|
+
});
|
|
112
|
+
const { dispose } = sharedSignal;
|
|
113
|
+
const replicatedResponses = replicateLazyResponse({ ...response, resolveBody: (hint) => response.resolveBody(hint).finally(dispose) }, signals);
|
|
114
|
+
activeCallers.forEach((caller, index) => caller.resolve(replicatedResponses[index]));
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
sharedSignal?.dispose();
|
|
118
|
+
for (const caller of activeCallers) {
|
|
119
|
+
caller.reject(error);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function canDedupeRequest(request) {
|
|
125
|
+
return !(request.body instanceof Blob ||
|
|
126
|
+
request.body instanceof FormData ||
|
|
127
|
+
request.body instanceof URLSearchParams ||
|
|
128
|
+
request.body instanceof ReadableStream ||
|
|
129
|
+
isAsyncIteratorObject(request.body) ||
|
|
130
|
+
request.signal?.aborted);
|
|
131
|
+
}
|
|
132
|
+
function createRequestKey(path, request) {
|
|
133
|
+
return stringifyJSON({
|
|
134
|
+
path,
|
|
135
|
+
body: request.body,
|
|
136
|
+
headers: request.headers,
|
|
137
|
+
method: request.method,
|
|
138
|
+
url: request.url,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Replicates the response once per signal. Like an unshared response, each replica's body
|
|
143
|
+
* fails and stops streaming once its own signal aborts, without affecting the other replicas.
|
|
144
|
+
*/
|
|
145
|
+
function replicateLazyResponse(response, signals) {
|
|
146
|
+
let bodiesPromise;
|
|
147
|
+
return signals.map((signal, i) => ({
|
|
148
|
+
...response,
|
|
149
|
+
resolveBody: (hint) => runWithSignal(signal, async () => {
|
|
150
|
+
bodiesPromise ??= response.resolveBody(hint).then((body) => {
|
|
151
|
+
if (isAsyncIteratorObject(body)) {
|
|
152
|
+
return replicateAsyncIterator(body, signals.length).map((replica, index) => closeAsyncIteratorOnAbort(replica, signals[index]));
|
|
153
|
+
}
|
|
154
|
+
if (body instanceof ReadableStream) {
|
|
155
|
+
return replicateReadableStream(body, signals.length).map((replica, index) => closeReadableStreamOnAbort(replica, signals[index]));
|
|
156
|
+
}
|
|
157
|
+
return signals.map(() => body);
|
|
158
|
+
});
|
|
159
|
+
return (await bodiesPromise)[i];
|
|
160
|
+
}),
|
|
161
|
+
}));
|
|
162
|
+
}
|
|
163
|
+
function closeAsyncIteratorOnAbort(replica, signal) {
|
|
164
|
+
if (!signal) {
|
|
165
|
+
return replica;
|
|
166
|
+
}
|
|
167
|
+
const abort = () => replica.return().catch(() => { });
|
|
168
|
+
if (signal.aborted) {
|
|
169
|
+
void abort();
|
|
170
|
+
}
|
|
171
|
+
else {
|
|
172
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
173
|
+
}
|
|
174
|
+
return wrapAsyncIterator(replica, {
|
|
175
|
+
mapResult(result) {
|
|
176
|
+
// Ending the replica reports its reads as done rather than failed.
|
|
177
|
+
throwIfAborted(signal);
|
|
178
|
+
return result;
|
|
179
|
+
},
|
|
180
|
+
onFinish: () => signal.removeEventListener('abort', abort),
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Cancels the replica on abort even when nothing is reading it, which an aborted
|
|
185
|
+
* `pipeThrough` would not do until the in-flight chunk is read.
|
|
186
|
+
*/
|
|
187
|
+
function closeReadableStreamOnAbort(replica, signal) {
|
|
188
|
+
if (!signal) {
|
|
189
|
+
return replica;
|
|
190
|
+
}
|
|
191
|
+
const reader = replica.getReader();
|
|
192
|
+
const abort = () => reader.cancel(signal.reason).catch(() => { });
|
|
193
|
+
if (signal.aborted) {
|
|
194
|
+
void abort();
|
|
195
|
+
}
|
|
196
|
+
else {
|
|
197
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
198
|
+
}
|
|
199
|
+
return new ReadableStream({
|
|
200
|
+
async pull(controller) {
|
|
201
|
+
try {
|
|
202
|
+
const result = await reader.read();
|
|
203
|
+
// Cancelling the replica reports its reads as done rather than failed.
|
|
204
|
+
throwIfAborted(signal);
|
|
205
|
+
if (result.done) {
|
|
206
|
+
signal.removeEventListener('abort', abort);
|
|
207
|
+
controller.close();
|
|
208
|
+
}
|
|
209
|
+
else {
|
|
210
|
+
controller.enqueue(result.value);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
catch (error) {
|
|
214
|
+
signal.removeEventListener('abort', abort);
|
|
215
|
+
throw error;
|
|
216
|
+
}
|
|
217
|
+
},
|
|
218
|
+
async cancel(reason) {
|
|
219
|
+
signal.removeEventListener('abort', abort);
|
|
220
|
+
await reader.cancel(reason);
|
|
221
|
+
},
|
|
222
|
+
}, { highWaterMark: 0 });
|
|
223
|
+
}
|
|
224
|
+
function shouldDedupe(items) {
|
|
225
|
+
return items.length >= 2;
|
|
226
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export * from './batch.ts';
|
|
2
|
+
export * from './cookie-jar.ts';
|
|
3
|
+
export * from './dedupe.ts';
|
|
4
|
+
export {
|
|
5
|
+
/**
|
|
6
|
+
* @deprecated Use `DedupeLinkPlugin` instead.
|
|
7
|
+
*/
|
|
8
|
+
DedupeLinkPlugin as DedupeRequestsPlugin, } from './dedupe.ts';
|
|
9
|
+
export * from './request-compression.ts';
|
|
10
|
+
export * from './response-compression.ts';
|
|
11
|
+
export * from './retry.ts';
|
|
12
|
+
export {
|
|
13
|
+
/**
|
|
14
|
+
* @deprecated Use `RetryLinkPlugin` instead.
|
|
15
|
+
*/
|
|
16
|
+
RetryLinkPlugin as ClientRetryPlugin, } from './retry.ts';
|
|
17
|
+
export type {
|
|
18
|
+
/**
|
|
19
|
+
* @deprecated Use `RetryLinkPluginContext` instead.
|
|
20
|
+
*/
|
|
21
|
+
RetryLinkPluginContext as ClientRetryPluginContext, } from './retry.ts';
|
|
22
|
+
export * from './retry-after.ts';
|
|
23
|
+
export {
|
|
24
|
+
/**
|
|
25
|
+
* @deprecated Use `RetryAfterLinkPlugin` instead.
|
|
26
|
+
*/
|
|
27
|
+
RetryAfterLinkPlugin as RetryAfterPlugin, } from './retry-after.ts';
|
|
28
|
+
export * from './timeout.ts';
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export * from './batch.js';
|
|
2
|
+
export * from './cookie-jar.js';
|
|
3
|
+
export * from './dedupe.js';
|
|
4
|
+
export {
|
|
5
|
+
/**
|
|
6
|
+
* @deprecated Use `DedupeLinkPlugin` instead.
|
|
7
|
+
*/
|
|
8
|
+
DedupeLinkPlugin as DedupeRequestsPlugin, } from './dedupe.js';
|
|
9
|
+
export * from './request-compression.js';
|
|
10
|
+
export * from './response-compression.js';
|
|
11
|
+
export * from './retry.js';
|
|
12
|
+
export {
|
|
13
|
+
/**
|
|
14
|
+
* @deprecated Use `RetryLinkPlugin` instead.
|
|
15
|
+
*/
|
|
16
|
+
RetryLinkPlugin as ClientRetryPlugin, } from './retry.js';
|
|
17
|
+
export * from './retry-after.js';
|
|
18
|
+
export {
|
|
19
|
+
/**
|
|
20
|
+
* @deprecated Use `RetryAfterLinkPlugin` instead.
|
|
21
|
+
*/
|
|
22
|
+
RetryAfterLinkPlugin as RetryAfterPlugin, } from './retry-after.js';
|
|
23
|
+
export * from './timeout.js';
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { StandardLinkOptions, StandardLinkPlugin, StandardLinkTransportInterceptorOptions } from '../adapters/standard/index.ts';
|
|
2
|
+
import type { ClientContext } from '../types.ts';
|
|
3
|
+
export interface RequestCompressionLinkPluginOptions<T extends ClientContext> {
|
|
4
|
+
/**
|
|
5
|
+
* The compression scheme to use for request compression.
|
|
6
|
+
*
|
|
7
|
+
* @default 'gzip'
|
|
8
|
+
*/
|
|
9
|
+
encoding?: 'gzip' | 'deflate' | 'deflate-raw' | undefined;
|
|
10
|
+
/**
|
|
11
|
+
* The minimum request size in bytes required to trigger compression.
|
|
12
|
+
* Requests smaller than this threshold will not be compressed to avoid overhead.
|
|
13
|
+
* If the request size cannot be determined, compression will still be applied.
|
|
14
|
+
*
|
|
15
|
+
* @default 1024 (1KB)
|
|
16
|
+
*/
|
|
17
|
+
threshold?: number | undefined;
|
|
18
|
+
/**
|
|
19
|
+
* Determines whether a request with the given Content-Type should be compressed.
|
|
20
|
+
* Only consulted for binary transfers (streams, files, and file form-data parts).
|
|
21
|
+
* Also receives the transport interceptor options for per-request decisions.
|
|
22
|
+
*
|
|
23
|
+
* @default isCompressibleContentType (covers common text-based formats)
|
|
24
|
+
*/
|
|
25
|
+
isCompressibleContentType?: ((contentType: string | null | undefined, options: StandardLinkTransportInterceptorOptions<T>) => boolean) | undefined;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Compresses request bodies before sending them to the server,
|
|
29
|
+
* reducing bandwidth usage for large payloads.
|
|
30
|
+
*
|
|
31
|
+
* @see {@link https://orpc.dev/docs/plugins/request-compression | Request Compression Plugin}
|
|
32
|
+
*/
|
|
33
|
+
export declare class RequestCompressionLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
|
|
34
|
+
name: string;
|
|
35
|
+
/**
|
|
36
|
+
* Compression should be done after batching, to compress the final request
|
|
37
|
+
*/
|
|
38
|
+
after: string[];
|
|
39
|
+
private readonly encoding;
|
|
40
|
+
private readonly threshold;
|
|
41
|
+
private readonly isCompressibleContentType;
|
|
42
|
+
constructor(options?: RequestCompressionLinkPluginOptions<T>);
|
|
43
|
+
init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
|
|
44
|
+
}
|