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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +137 -102
  2. package/dist/adapters/fetch/index.d.ts +3 -65
  3. package/dist/adapters/fetch/index.js +2 -0
  4. package/dist/adapters/fetch/rpc-link.d.ts +14 -0
  5. package/dist/adapters/fetch/rpc-link.js +17 -0
  6. package/dist/adapters/fetch/transport.d.ts +32 -0
  7. package/dist/adapters/fetch/transport.js +51 -0
  8. package/dist/adapters/message-port/index.d.ts +4 -75
  9. package/dist/adapters/message-port/index.js +3 -0
  10. package/dist/adapters/message-port/message-port.d.ts +29 -0
  11. package/dist/adapters/message-port/message-port.js +38 -0
  12. package/dist/adapters/message-port/rpc-link.d.ts +15 -0
  13. package/dist/adapters/message-port/rpc-link.js +18 -0
  14. package/dist/adapters/message-port/transport.d.ts +35 -0
  15. package/dist/adapters/message-port/transport.js +38 -0
  16. package/dist/adapters/standard/codec.d.ts +14 -0
  17. package/dist/adapters/standard/index.d.ts +6 -61
  18. package/dist/adapters/standard/index.js +2 -0
  19. package/dist/adapters/standard/link.d.ts +40 -0
  20. package/dist/adapters/standard/link.js +101 -0
  21. package/dist/adapters/standard/plugin.d.ts +26 -0
  22. package/dist/adapters/standard/plugin.js +14 -0
  23. package/dist/adapters/standard/rpc-link-codec.d.ts +56 -0
  24. package/dist/adapters/standard/rpc-link-codec.js +100 -0
  25. package/dist/adapters/standard/transport.d.ts +14 -0
  26. package/dist/adapters/websocket/index.d.ts +3 -121
  27. package/dist/adapters/websocket/index.js +2 -0
  28. package/dist/adapters/websocket/rpc-link.d.ts +14 -0
  29. package/dist/adapters/websocket/rpc-link.js +17 -0
  30. package/dist/adapters/websocket/transport.d.ts +116 -0
  31. package/dist/adapters/websocket/transport.js +105 -0
  32. package/dist/async-iterator-object.d.ts +2 -0
  33. package/dist/async-iterator-object.js +28 -0
  34. package/dist/client-safe.d.ts +16 -0
  35. package/dist/client-safe.js +31 -0
  36. package/dist/client.d.ts +38 -0
  37. package/dist/client.js +37 -0
  38. package/dist/consts.d.ts +10 -0
  39. package/dist/consts.js +20 -0
  40. package/dist/dynamic-link.d.ts +13 -0
  41. package/dist/dynamic-link.js +17 -0
  42. package/dist/error-utils.d.ts +20 -0
  43. package/dist/error-utils.js +54 -0
  44. package/dist/error.d.ts +132 -0
  45. package/dist/error.js +166 -0
  46. package/dist/index.d.ts +14 -155
  47. package/dist/index.js +12 -0
  48. package/dist/plugins/batch.d.ts +152 -0
  49. package/dist/plugins/batch.js +330 -0
  50. package/dist/plugins/cookie-jar.d.ts +85 -0
  51. package/dist/plugins/cookie-jar.js +231 -0
  52. package/dist/plugins/dedupe.d.ts +60 -0
  53. package/dist/plugins/dedupe.js +183 -0
  54. package/dist/plugins/index.d.ts +9 -242
  55. package/dist/plugins/index.js +8 -0
  56. package/dist/plugins/request-compression.d.ts +47 -0
  57. package/dist/plugins/request-compression.js +132 -0
  58. package/dist/plugins/response-compression.d.ts +31 -0
  59. package/dist/plugins/response-compression.js +67 -0
  60. package/dist/plugins/retry-after.d.ts +43 -0
  61. package/dist/plugins/retry-after.js +63 -0
  62. package/dist/plugins/retry.d.ts +84 -0
  63. package/dist/plugins/retry.js +121 -0
  64. package/dist/plugins/timeout.d.ts +27 -0
  65. package/dist/plugins/timeout.js +42 -0
  66. package/dist/rpc-json-serializer.d.ts +99 -0
  67. package/dist/rpc-json-serializer.js +347 -0
  68. package/dist/rpc-serializer.d.ts +31 -0
  69. package/dist/rpc-serializer.js +102 -0
  70. package/dist/types.d.ts +85 -0
  71. package/dist/utils.d.ts +36 -0
  72. package/dist/utils.js +67 -0
  73. package/package.json +47 -35
  74. package/dist/adapters/fetch/index.d.mts +0 -65
  75. package/dist/adapters/fetch/index.mjs +0 -68
  76. package/dist/adapters/message-port/index.d.mts +0 -75
  77. package/dist/adapters/message-port/index.mjs +0 -91
  78. package/dist/adapters/standard/index.d.mts +0 -61
  79. package/dist/adapters/standard/index.mjs +0 -6
  80. package/dist/adapters/websocket/index.d.mts +0 -121
  81. package/dist/adapters/websocket/index.mjs +0 -110
  82. package/dist/index.d.mts +0 -155
  83. package/dist/index.mjs +0 -154
  84. package/dist/plugins/index.d.mts +0 -242
  85. package/dist/plugins/index.mjs +0 -574
  86. package/dist/shared/client.8ug8I-zu.d.mts +0 -167
  87. package/dist/shared/client.8ug8I-zu.d.ts +0 -167
  88. package/dist/shared/client.BdItY5DT.d.mts +0 -111
  89. package/dist/shared/client.BdItY5DT.d.ts +0 -111
  90. package/dist/shared/client.CPF3hX6O.d.ts +0 -96
  91. package/dist/shared/client.Cby_-GGh.d.mts +0 -96
  92. package/dist/shared/client.DMXKFDyV.mjs +0 -343
  93. package/dist/shared/client.DXhchJ84.mjs +0 -174
  94. package/dist/shared/client.Dnfj8jnT.mjs +0 -92
@@ -0,0 +1,231 @@
1
+ import { matchesHttpPathPrefix, toArray, value } from "@orpc/shared";
2
+ // src/plugins/cookie-jar.ts
3
+ /**
4
+ * Stores the cookies servers set and sends them back on later requests, like a browser,
5
+ * for server-side rendering, scripts, and tests.
6
+ *
7
+ * @remarks
8
+ * **Warning**: On a server, do not share one link between users: create a client per request, or pick a jar per request.
9
+ *
10
+ * @see {@link https://orpc.dev/docs/plugins/cookie-jar | Cookie Jar Plugin}
11
+ */
12
+ var CookieJarLinkPlugin = class {
13
+ origin;
14
+ jar;
15
+ name = "~cookie-jar";
16
+ /**
17
+ * Runs per call, before batching, so each call gets the cookies it would get on its own.
18
+ */
19
+ before = ["~batch"];
20
+ constructor(options) {
21
+ this.origin = options.origin;
22
+ this.jar = options.jar ?? new CookieJar();
23
+ }
24
+ init(options) {
25
+ const transportInterceptor = async ({ next, ...interceptorOptions }) => {
26
+ const { path, request } = interceptorOptions;
27
+ const origin = await value(this.origin, interceptorOptions, path);
28
+ if (origin === void 0 || !/^[a-z][\d+\-.a-z]*:/i.test(origin)) return next();
29
+ const jar = value(this.jar, interceptorOptions);
30
+ const url = `${origin.replace(/\/$/, "")}${request.url}`;
31
+ const cookie = mergeCookieHeader(request.headers.cookie, jar.getCookies(url));
32
+ const response = await next(cookie === void 0 ? interceptorOptions : {
33
+ ...interceptorOptions,
34
+ request: {
35
+ ...request,
36
+ headers: {
37
+ ...request.headers,
38
+ cookie
39
+ }
40
+ }
41
+ });
42
+ for (const setCookie of toArray(response.headers["set-cookie"])) jar.setCookie(setCookie, url);
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
+ var CookieJar = class {
57
+ /**
58
+ * Keyed by domain, path, and name. Map order is creation order: replacing a cookie keeps its position.
59
+ */
60
+ cookies = /* @__PURE__ */ 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) return;
68
+ const target = new URL(url);
69
+ const secureUrl = isSecureUrl(target);
70
+ const hostOnly = parsed.domain === void 0;
71
+ const domain = parsed.domain ?? target.hostname;
72
+ const path = parsed.path ?? defaultPath(target.pathname);
73
+ 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)))) return;
74
+ const key = `${domain};${path};${parsed.name}`;
75
+ if ((parsed.expires ?? Number.POSITIVE_INFINITY) <= Date.now()) {
76
+ this.cookies.delete(key);
77
+ return;
78
+ }
79
+ this.cookies.set(key, {
80
+ ...parsed,
81
+ domain,
82
+ hostOnly,
83
+ path
84
+ });
85
+ }
86
+ /**
87
+ * Returns the cookies a browser would send to `url`, longer paths first, then oldest first.
88
+ * Without `url`, returns every stored cookie that has not expired.
89
+ */
90
+ getCookies(url) {
91
+ const now = Date.now();
92
+ for (const [key, cookie] of this.cookies) if ((cookie.expires ?? Number.POSITIVE_INFINITY) <= now) this.cookies.delete(key);
93
+ const cookies = [...this.cookies.values()].map((cookie) => ({ ...cookie }));
94
+ if (url === void 0) return cookies;
95
+ const target = new URL(url);
96
+ const secureUrl = isSecureUrl(target);
97
+ 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);
98
+ }
99
+ /**
100
+ * Removes every stored cookie.
101
+ */
102
+ clear() {
103
+ this.cookies.clear();
104
+ }
105
+ };
106
+ /**
107
+ * Appends jar cookies to an existing `cookie` header, skipping names it already has.
108
+ * Returns `undefined` when the jar adds nothing.
109
+ */
110
+ function mergeCookieHeader(header, cookies) {
111
+ const explicit = toArray(header).flatMap((value) => value.split(";")).map((pair) => pair.trim()).filter(Boolean);
112
+ const explicitNames = new Set(explicit.map((pair) => splitCookiePair(pair)[0]));
113
+ const pairs = cookies.filter((cookie) => !explicitNames.has(cookie.name)).map((cookie) => cookie.name ? `${cookie.name}=${cookie.value}` : cookie.value);
114
+ return pairs.length ? [...explicit, ...pairs].join("; ") : void 0;
115
+ }
116
+ /**
117
+ * Splits a cookie pair at the first `=`. A pair without `=` has an empty name, as in browsers and RFC 6265bis.
118
+ */
119
+ function splitCookiePair(pair) {
120
+ const index = pair.indexOf("=");
121
+ return [index === -1 ? "" : pair.slice(0, index).trim(), pair.slice(index + 1).trim()];
122
+ }
123
+ /**
124
+ * Parses a `Set-Cookie` header value following [RFC 6265 Section 5.2](https://datatracker.ietf.org/doc/html/rfc6265#section-5.2),
125
+ * with the [RFC 6265bis](https://datatracker.ietf.org/doc/draft-ietf-httpbis-rfc6265bis/) changes browsers use, noted inline.
126
+ */
127
+ function parseSetCookie(setCookie) {
128
+ if (/[\x00-\x08\x0A-\x1F\x7F]/.test(setCookie)) return;
129
+ const [pair = "", ...attributes] = setCookie.split(";");
130
+ const [name, value] = splitCookiePair(pair);
131
+ if (!name && !value) return;
132
+ let domain;
133
+ let path;
134
+ let secure = false;
135
+ let expires;
136
+ let maxAgeExpires;
137
+ for (const attribute of attributes) {
138
+ const index = attribute.indexOf("=");
139
+ const attributeName = (index === -1 ? attribute : attribute.slice(0, index)).trim().toLowerCase();
140
+ const attributeValue = index === -1 ? "" : attribute.slice(index + 1).trim();
141
+ switch (attributeName) {
142
+ case "expires":
143
+ expires = parseCookieDate(attributeValue) ?? expires;
144
+ break;
145
+ case "max-age":
146
+ if (/^-?\d+$/.test(attributeValue)) maxAgeExpires = Date.now() + Number(attributeValue) * 1e3;
147
+ break;
148
+ case "domain":
149
+ domain = attributeValue.replace(/^\./, "").toLowerCase() || void 0;
150
+ break;
151
+ case "path":
152
+ path = attributeValue.startsWith("/") ? attributeValue : void 0;
153
+ break;
154
+ case "secure": secure = true;
155
+ }
156
+ }
157
+ return {
158
+ name,
159
+ value,
160
+ domain,
161
+ path,
162
+ secure,
163
+ expires: maxAgeExpires ?? expires
164
+ };
165
+ }
166
+ const MONTHS = [
167
+ "jan",
168
+ "feb",
169
+ "mar",
170
+ "apr",
171
+ "may",
172
+ "jun",
173
+ "jul",
174
+ "aug",
175
+ "sep",
176
+ "oct",
177
+ "nov",
178
+ "dec"
179
+ ];
180
+ /**
181
+ * Parses a cookie date following [RFC 6265 Section 5.1.1](https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.1),
182
+ * always in UTC. Returns `undefined` when a part is missing or out of range, so the attribute is ignored.
183
+ */
184
+ function parseCookieDate(value) {
185
+ let time;
186
+ let day;
187
+ let month;
188
+ let year;
189
+ for (const token of value.split(/[\t\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]+/)) {
190
+ const digits = /^\d*/.exec(token)[0];
191
+ const timeMatch = /^(\d{1,2}):(\d{1,2}):(\d{1,2})(?:\D|$)/.exec(token);
192
+ const monthIndex = MONTHS.indexOf(token.slice(0, 3).toLowerCase());
193
+ if (time === void 0 && timeMatch) time = [
194
+ Number(timeMatch[1]),
195
+ Number(timeMatch[2]),
196
+ Number(timeMatch[3])
197
+ ];
198
+ else if (day === void 0 && digits.length >= 1 && digits.length <= 2) day = Number(digits);
199
+ else if (month === void 0 && monthIndex !== -1) month = monthIndex;
200
+ else if (year === void 0 && digits.length >= 2 && digits.length <= 4) {
201
+ year = Number(digits);
202
+ year += year < 70 ? 2e3 : year < 100 ? 1900 : 0;
203
+ }
204
+ }
205
+ if (time === void 0 || day === void 0 || month === void 0 || year === void 0) return;
206
+ const [hour, minute, second] = time;
207
+ if (year < 1601 || hour > 23 || minute > 59 || second > 59) return;
208
+ const date = Date.UTC(year, month, day, hour, minute, second);
209
+ return new Date(date).getUTCDate() === day ? date : void 0;
210
+ }
211
+ /**
212
+ * Browsers also treat loopback hosts as secure, so `Secure` cookies work against a local server.
213
+ */
214
+ function isSecureUrl(url) {
215
+ const host = url.hostname;
216
+ return url.protocol === "https:" || url.protocol === "wss:" || host === "localhost" || host.endsWith(".localhost") || host === "[::1]" || /^127(?:\.\d{1,3}){3}$/.test(host);
217
+ }
218
+ /**
219
+ * [RFC 6265 Section 5.1.3](https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.3)
220
+ */
221
+ function domainMatch(host, domain) {
222
+ return host === domain || host.endsWith(`.${domain}`) && !/^\d{1,3}(?:\.\d{1,3}){3}$/.test(host);
223
+ }
224
+ /**
225
+ * [RFC 6265 Section 5.1.4](https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4)
226
+ */
227
+ function defaultPath(path) {
228
+ const index = path.lastIndexOf("/");
229
+ return index <= 0 ? "/" : path.slice(0, index);
230
+ }
231
+ export { CookieJar, CookieJarLinkPlugin };
@@ -0,0 +1,60 @@
1
+ import "../adapters/standard/index.js";
2
+ import { StandardLinkPlugin } from "../adapters/standard/plugin.js";
3
+ import { StandardLinkOptions, StandardLinkTransportInterceptorOptions } from "../adapters/standard/link.js";
4
+ import { ClientContext } from "../types.js";
5
+ import { Value } from "@orpc/shared";
6
+ export interface DedupeLinkPluginGroup<T extends ClientContext> {
7
+ condition: Value<boolean, [options: StandardLinkTransportInterceptorOptions<T>]>;
8
+ /**
9
+ * The context used for the rest of the request lifecycle.
10
+ */
11
+ context: Value<T, [items: [StandardLinkTransportInterceptorOptions<T>, StandardLinkTransportInterceptorOptions<T>, ...StandardLinkTransportInterceptorOptions<T>[]]]>;
12
+ }
13
+ export interface DedupeLinkPluginOptions<T extends ClientContext> {
14
+ /**
15
+ * To enable deduplication, a request must match at least one defined group.
16
+ * Requests that fall into the same group are considered for deduplication together.
17
+ */
18
+ groups: [DedupeLinkPluginGroup<T>, ...DedupeLinkPluginGroup<T>[]];
19
+ /**
20
+ * Filters requests to dedupe.
21
+ *
22
+ * @default ({ request }) => request.method === 'GET' || request.method === 'QUERY'
23
+ */
24
+ filter?: Value<boolean, [options: StandardLinkTransportInterceptorOptions<T>]> | undefined;
25
+ /**
26
+ * Only requests with the same scope are deduplicated together.
27
+ * On the server, return a value unique to the incoming request so different users never share a response.
28
+ *
29
+ * @default () => undefined
30
+ */
31
+ scope?: ((options: StandardLinkTransportInterceptorOptions<T>) => unknown) | undefined;
32
+ /**
33
+ * How long (in ms) to wait for more identical requests before sending,
34
+ * counted from the first queued request.
35
+ * With `0`, only requests made in the same event loop tick are deduplicated.
36
+ *
37
+ * @default 0
38
+ */
39
+ wait?: number | undefined;
40
+ }
41
+ /**
42
+ * Prevents redundant requests by deduplicating similar in-flight requests,
43
+ * reducing the number of requests sent to the server.
44
+ *
45
+ * @see {@link https://orpc.dev/docs/plugins/dedupe | Dedupe Plugin}
46
+ */
47
+ export declare class DedupeLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
48
+ name: string;
49
+ before: string[];
50
+ private readonly groups;
51
+ private readonly filter;
52
+ private readonly scope;
53
+ private readonly wait;
54
+ private readonly queue;
55
+ constructor(options: NoInfer<DedupeLinkPluginOptions<T>>);
56
+ init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
57
+ private enqueue;
58
+ private processPendingRequests;
59
+ private execute;
60
+ }
@@ -0,0 +1,183 @@
1
+ import { captureAsyncContext, defer, disposableAllAbortSignal, isAsyncIteratorObject, listenAbort, replicateAsyncIterator, replicateReadableStream, runWithSignal, stringifyJSON, throwIfAborted, toArray, value, wrapAsyncIterator } from "@orpc/shared";
2
+ // src/plugins/dedupe.ts
3
+ /**
4
+ * Prevents redundant requests by deduplicating similar in-flight requests,
5
+ * reducing the number of requests sent to the server.
6
+ *
7
+ * @see {@link https://orpc.dev/docs/plugins/dedupe | Dedupe Plugin}
8
+ */
9
+ var DedupeLinkPlugin = class {
10
+ name = "~dedupe";
11
+ before = ["~batch"];
12
+ groups;
13
+ filter;
14
+ scope;
15
+ wait;
16
+ queue = /* @__PURE__ */ new Map();
17
+ constructor(options) {
18
+ this.groups = options.groups;
19
+ this.filter = options.filter ?? (({ request }) => request.method === "GET" || request.method === "QUERY");
20
+ this.scope = options.scope ?? (() => void 0);
21
+ this.wait = options.wait ?? 0;
22
+ }
23
+ init(options) {
24
+ const transportInterceptor = (interceptorOptions) => {
25
+ if (!canDedupeRequest(interceptorOptions.request) || !value(this.filter, interceptorOptions)) return interceptorOptions.next();
26
+ const group = this.groups.find((group) => value(group.condition, interceptorOptions));
27
+ if (!group) return interceptorOptions.next();
28
+ const scope = this.scope(interceptorOptions);
29
+ return runWithSignal(interceptorOptions.request.signal, () => new Promise((resolve, reject) => {
30
+ if (!this.queue.size) defer(() => this.processPendingRequests(), this.wait);
31
+ this.enqueue(scope, group, {
32
+ options: interceptorOptions,
33
+ resolve,
34
+ reject,
35
+ runInOwnContext: captureAsyncContext()
36
+ });
37
+ }));
38
+ };
39
+ return {
40
+ ...options,
41
+ transportInterceptors: [...toArray(options.transportInterceptors), transportInterceptor]
42
+ };
43
+ }
44
+ enqueue(scope, group, caller) {
45
+ let groups = this.queue.get(scope);
46
+ if (!groups) {
47
+ groups = /* @__PURE__ */ new Map();
48
+ this.queue.set(scope, groups);
49
+ }
50
+ let queue = groups.get(group);
51
+ if (!queue) {
52
+ queue = /* @__PURE__ */ new Map();
53
+ groups.set(group, queue);
54
+ }
55
+ const requestKey = createRequestKey(caller.options.path, caller.options.request);
56
+ const matched = queue.get(requestKey);
57
+ if (matched) {
58
+ matched.push(caller);
59
+ return;
60
+ }
61
+ queue.set(requestKey, [caller]);
62
+ }
63
+ async processPendingRequests() {
64
+ const pending = [...this.queue.values()];
65
+ this.queue.clear();
66
+ const executions = [];
67
+ for (const groups of pending) for (const [group, items] of groups) for (const callers of items.values()) {
68
+ const activeCallers = callers.filter((caller) => !caller.options.request.signal?.aborted);
69
+ const [first] = activeCallers;
70
+ if (first) executions.push(first.runInOwnContext(() => this.execute(group, activeCallers)));
71
+ }
72
+ await Promise.all(executions);
73
+ }
74
+ async execute(group, activeCallers) {
75
+ const first = activeCallers[0];
76
+ const matchedOptions = activeCallers.map((caller) => caller.options);
77
+ let sharedSignal;
78
+ try {
79
+ if (!shouldDedupe(matchedOptions)) {
80
+ const response = await first.options.next(first.options);
81
+ first.resolve(response);
82
+ return;
83
+ }
84
+ const context = value(group.context, matchedOptions);
85
+ const signals = matchedOptions.map((options) => options.request.signal);
86
+ sharedSignal = disposableAllAbortSignal(signals);
87
+ const request = {
88
+ ...first.options.request,
89
+ signal: sharedSignal.signal
90
+ };
91
+ const response = await first.options.next({
92
+ ...first.options,
93
+ request,
94
+ signal: request.signal,
95
+ context
96
+ });
97
+ const { dispose } = sharedSignal;
98
+ const replicatedResponses = replicateLazyResponse({
99
+ ...response,
100
+ resolveBody: (hint) => response.resolveBody(hint).finally(dispose)
101
+ }, signals);
102
+ activeCallers.forEach((caller, index) => caller.resolve(replicatedResponses[index]));
103
+ } catch (error) {
104
+ sharedSignal?.dispose();
105
+ for (const caller of activeCallers) caller.reject(error);
106
+ }
107
+ }
108
+ };
109
+ function canDedupeRequest(request) {
110
+ return !(request.body instanceof Blob || request.body instanceof FormData || request.body instanceof URLSearchParams || request.body instanceof ReadableStream || isAsyncIteratorObject(request.body) || request.signal?.aborted);
111
+ }
112
+ function createRequestKey(path, request) {
113
+ return stringifyJSON({
114
+ path,
115
+ body: request.body,
116
+ headers: request.headers,
117
+ method: request.method,
118
+ url: request.url
119
+ });
120
+ }
121
+ /**
122
+ * Replicates the response once per signal. Like an unshared response, each replica's body
123
+ * fails and stops streaming once its own signal aborts, without affecting the other replicas.
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)) return replicateAsyncIterator(body, signals.length).map((replica, index) => closeAsyncIteratorOnAbort(replica, signals[index]));
132
+ if (body instanceof ReadableStream) return replicateReadableStream(body, signals.length).map((replica, index) => closeReadableStreamOnAbort(replica, signals[index]));
133
+ return signals.map(() => body);
134
+ });
135
+ return (await bodiesPromise)[i];
136
+ })
137
+ }));
138
+ }
139
+ function closeAsyncIteratorOnAbort(replica, signal) {
140
+ if (!signal) return replica;
141
+ const removeAbortListener = listenAbort(signal, () => void replica.return().catch(() => {}));
142
+ return wrapAsyncIterator(replica, {
143
+ mapResult(result) {
144
+ throwIfAborted(signal);
145
+ return result;
146
+ },
147
+ onFinish: removeAbortListener
148
+ });
149
+ }
150
+ /**
151
+ * Cancels the replica on abort even when nothing is reading it, which an aborted
152
+ * `pipeThrough` would not do until the in-flight chunk is read.
153
+ */
154
+ function closeReadableStreamOnAbort(replica, signal) {
155
+ if (!signal) return replica;
156
+ const reader = replica.getReader();
157
+ const removeAbortListener = listenAbort(signal, (reason) => {
158
+ reader.cancel(reason).catch(() => {});
159
+ });
160
+ return new ReadableStream({
161
+ async pull(controller) {
162
+ try {
163
+ const result = await reader.read();
164
+ throwIfAborted(signal);
165
+ if (result.done) {
166
+ removeAbortListener();
167
+ controller.close();
168
+ } else controller.enqueue(result.value);
169
+ } catch (error) {
170
+ removeAbortListener();
171
+ throw error;
172
+ }
173
+ },
174
+ async cancel(reason) {
175
+ removeAbortListener();
176
+ await reader.cancel(reason);
177
+ }
178
+ }, { highWaterMark: 0 });
179
+ }
180
+ function shouldDedupe(items) {
181
+ return items.length >= 2;
182
+ }
183
+ export { DedupeLinkPlugin };