@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
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import type { Promisable, Value } from "@orpc/shared";
|
|
2
|
+
import type { StandardHeaders, StandardLazyResponse, StandardRequest, StandardUrl } from "@standard-server/core";
|
|
3
|
+
import type { StandardLinkOptions, StandardLinkPlugin, StandardLinkTransportInterceptorOptions } from "../adapters/standard/index.mjs";
|
|
4
|
+
import type { ClientContext } from "../types.mjs";
|
|
5
|
+
/**
|
|
6
|
+
* Header that marks a request as a batch, set by the Batch Link Plugin and detected by the Batch Handler Plugin.
|
|
7
|
+
* Nothing between the client and server, such as a CORS policy or proxy, should block or strip it.
|
|
8
|
+
*
|
|
9
|
+
* @see {@link https://orpc.dev/docs/plugins/batch#setup | Batch Plugin - Setup}
|
|
10
|
+
*/
|
|
11
|
+
export declare const BATCH_HEADER = "orpc-batch";
|
|
12
|
+
/**
|
|
13
|
+
* Default `maxSize` of both the Batch Link Plugin and the Batch Handler Plugin.
|
|
14
|
+
*
|
|
15
|
+
* @see {@link https://orpc.dev/docs/plugins/batch#max-size | Batch Plugin - Max Size}
|
|
16
|
+
*/
|
|
17
|
+
export declare const DEFAULT_BATCH_MAX_SIZE = 10;
|
|
18
|
+
/**
|
|
19
|
+
* @see {@link https://orpc.dev/docs/plugins/batch#response-modes | Batch Plugin - Response Modes}
|
|
20
|
+
*/
|
|
21
|
+
export type BatchLinkPluginMode = "buffered" | "streaming";
|
|
22
|
+
export interface BatchLinkPluginGroup<T extends ClientContext> {
|
|
23
|
+
/**
|
|
24
|
+
* Determines whether a request should be included in this batch group.
|
|
25
|
+
* Requests will be evaluated against each group's condition in order,
|
|
26
|
+
* and included in the first group whose condition returns true.
|
|
27
|
+
* If no group's condition returns true, the request will not be batched.
|
|
28
|
+
*/
|
|
29
|
+
condition: Value<boolean, [options: StandardLinkTransportInterceptorOptions<T>]>;
|
|
30
|
+
/**
|
|
31
|
+
* The client context applied to requests in this batch group for the remainder of the link chain.
|
|
32
|
+
*/
|
|
33
|
+
context: Value<T, [items: [StandardLinkTransportInterceptorOptions<T>, ...StandardLinkTransportInterceptorOptions<T>[]]]>;
|
|
34
|
+
/**
|
|
35
|
+
* The path segments applied to requests in this batch group for the remainder of the link chain.
|
|
36
|
+
*
|
|
37
|
+
* @default []
|
|
38
|
+
*/
|
|
39
|
+
path?: Value<string[], [items: [StandardLinkTransportInterceptorOptions<T>, ...StandardLinkTransportInterceptorOptions<T>[]]]> | undefined;
|
|
40
|
+
}
|
|
41
|
+
export interface BatchLinkPluginOptions<T extends ClientContext> {
|
|
42
|
+
groups: [BatchLinkPluginGroup<T>, ...BatchLinkPluginGroup<T>[]];
|
|
43
|
+
/**
|
|
44
|
+
* Filters requests to batch.
|
|
45
|
+
*
|
|
46
|
+
* @default () => true
|
|
47
|
+
*/
|
|
48
|
+
filter?: Value<boolean, [options: StandardLinkTransportInterceptorOptions<T>]> | undefined;
|
|
49
|
+
/**
|
|
50
|
+
* Only requests with the same scope are batched together.
|
|
51
|
+
* On the server, return a value unique to the incoming request so different users never share a batch.
|
|
52
|
+
*
|
|
53
|
+
* @default () => undefined
|
|
54
|
+
*/
|
|
55
|
+
scope?: ((options: StandardLinkTransportInterceptorOptions<T>) => unknown) | undefined;
|
|
56
|
+
/**
|
|
57
|
+
* The maximum number of requests in the batch. Larger batches are split.
|
|
58
|
+
* Keep it at or below the server Batch Handler Plugin's `maxSize`, which rejects larger batches with a `413`.
|
|
59
|
+
*
|
|
60
|
+
* @default DEFAULT_BATCH_MAX_SIZE (10)
|
|
61
|
+
* @see {@link https://orpc.dev/docs/plugins/batch#max-size | Batch Plugin - Max Size}
|
|
62
|
+
*/
|
|
63
|
+
maxSize?: Value<Promisable<number>, [subOptionsList: [StandardLinkTransportInterceptorOptions<T>, ...StandardLinkTransportInterceptorOptions<T>[]]]> | undefined;
|
|
64
|
+
/**
|
|
65
|
+
* How long (in ms) to wait for more requests before sending the batch,
|
|
66
|
+
* counted from the first queued request.
|
|
67
|
+
* With `0`, only requests made in the same event loop tick are batched.
|
|
68
|
+
*
|
|
69
|
+
* @default 0
|
|
70
|
+
*/
|
|
71
|
+
wait?: number | undefined;
|
|
72
|
+
/**
|
|
73
|
+
* How the server sends the batch response.
|
|
74
|
+
*
|
|
75
|
+
* - `buffered`: waits for every subrequest, so the response carries their cookies and shared headers.
|
|
76
|
+
* - `streaming`: starts once the first subrequest responds and sends each other response as soon as it is
|
|
77
|
+
* ready, but carries only that first one's cookies.
|
|
78
|
+
*
|
|
79
|
+
* @default 'buffered'
|
|
80
|
+
* @see {@link https://orpc.dev/docs/plugins/batch#response-modes | Batch Plugin - Response Modes}
|
|
81
|
+
*/
|
|
82
|
+
mode?: Value<Promisable<BatchLinkPluginMode>, [subOptionsList: [StandardLinkTransportInterceptorOptions<T>, ...StandardLinkTransportInterceptorOptions<T>[]]]> | undefined;
|
|
83
|
+
/**
|
|
84
|
+
* URL for the batch request.
|
|
85
|
+
*
|
|
86
|
+
* @default URL of the first subrequest in the batch + '/__batch__'
|
|
87
|
+
*/
|
|
88
|
+
url?: Value<Promisable<StandardUrl>, [subOptionsList: [StandardLinkTransportInterceptorOptions<T>, ...StandardLinkTransportInterceptorOptions<T>[]]]> | undefined;
|
|
89
|
+
/**
|
|
90
|
+
* The maximum length of the URL that runtime supports,
|
|
91
|
+
* if exceeded, the batch will be split into smaller batches and sent sequentially.
|
|
92
|
+
*
|
|
93
|
+
* This only applies to GET batch requests where the batch data is sent via URL query parameter.
|
|
94
|
+
*
|
|
95
|
+
* @default 2083
|
|
96
|
+
*/
|
|
97
|
+
maxUrlLength?: Value<Promisable<number>, [subOptionsList: [StandardLinkTransportInterceptorOptions<T>, ...StandardLinkTransportInterceptorOptions<T>[]]]> | undefined;
|
|
98
|
+
/**
|
|
99
|
+
* Headers used for the batch request.
|
|
100
|
+
*
|
|
101
|
+
* @default Common headers among all subrequests in the batch.
|
|
102
|
+
*/
|
|
103
|
+
headers?: Value<Promisable<StandardHeaders>, [subOptionsList: [StandardLinkTransportInterceptorOptions<T>, ...StandardLinkTransportInterceptorOptions<T>[]]]> | undefined;
|
|
104
|
+
/**
|
|
105
|
+
* Map each subrequest in the batch before it is sent.
|
|
106
|
+
*
|
|
107
|
+
* @default Removes headers that are duplicated with the batch headers
|
|
108
|
+
*/
|
|
109
|
+
mapSubrequest?: ((subOptions: StandardLinkTransportInterceptorOptions<T>, partialBatchRequest: Pick<StandardRequest, "url" | "headers">) => StandardRequest) | undefined;
|
|
110
|
+
/**
|
|
111
|
+
* Maps each subresponse before returning the final response.
|
|
112
|
+
*
|
|
113
|
+
* @default Low-priority merges headers from the batch response into each subresponse.
|
|
114
|
+
*/
|
|
115
|
+
mapSubresponse?: ((subResponse: StandardLazyResponse, batchResponse: StandardLazyResponse, subOptions: StandardLinkTransportInterceptorOptions<T>) => StandardLazyResponse) | undefined;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Combines multiple client requests into a single batch request
|
|
119
|
+
* and splits the batch response back into individual responses.
|
|
120
|
+
*
|
|
121
|
+
* @remarks
|
|
122
|
+
* **Note**: HTTP/2 and later already multiplex requests over a single connection, so this plugin is often less useful than it once was.
|
|
123
|
+
*
|
|
124
|
+
* @see {@link https://orpc.dev/docs/plugins/batch | Batch Plugin}
|
|
125
|
+
*/
|
|
126
|
+
export declare class BatchLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
|
|
127
|
+
name: string;
|
|
128
|
+
private readonly groups;
|
|
129
|
+
private readonly filter;
|
|
130
|
+
private readonly scope;
|
|
131
|
+
private readonly maxSize;
|
|
132
|
+
private readonly wait;
|
|
133
|
+
private readonly mode;
|
|
134
|
+
private readonly batchUrl;
|
|
135
|
+
private readonly maxUrlLength;
|
|
136
|
+
private readonly batchHeaders;
|
|
137
|
+
private readonly mapSubrequest;
|
|
138
|
+
private readonly mapSubresponse;
|
|
139
|
+
private readonly queue;
|
|
140
|
+
constructor(options: NoInfer<BatchLinkPluginOptions<T>>);
|
|
141
|
+
init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
|
|
142
|
+
private processPendingBatches;
|
|
143
|
+
/**
|
|
144
|
+
* Runs the batch in the async context of its first request instead of the timer's,
|
|
145
|
+
* so the transport and batch options see that caller's request state.
|
|
146
|
+
* `executeBatch` always runs in the context of its first request.
|
|
147
|
+
*/
|
|
148
|
+
private executeBatchInOwnContext;
|
|
149
|
+
private executeBatch;
|
|
150
|
+
}
|
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
import { captureAsyncContext, defer, isAsyncIteratorObject, loadBytes, once, promiseWithResolvers, safeEncodeURIComponent, splitInHalf, stringifyJSON, toArray, value } from "@orpc/shared";
|
|
2
|
+
import { parseStandardUrl } from "@standard-server/core";
|
|
3
|
+
import { ClientPeer, decodePeerMessage, isPeerMessage, isServerPeerSendMessage } from "@standard-server/peer";
|
|
4
|
+
|
|
5
|
+
export const BATCH_HEADER = "orpc-batch";
|
|
6
|
+
|
|
7
|
+
export const DEFAULT_BATCH_MAX_SIZE = 10;
|
|
8
|
+
|
|
9
|
+
export class BatchLinkPlugin {
|
|
10
|
+
name = "~batch";
|
|
11
|
+
groups;
|
|
12
|
+
filter;
|
|
13
|
+
scope;
|
|
14
|
+
maxSize;
|
|
15
|
+
wait;
|
|
16
|
+
mode;
|
|
17
|
+
batchUrl;
|
|
18
|
+
maxUrlLength;
|
|
19
|
+
batchHeaders;
|
|
20
|
+
mapSubrequest;
|
|
21
|
+
mapSubresponse;
|
|
22
|
+
queue = new Map();
|
|
23
|
+
constructor(options) {
|
|
24
|
+
this.groups = options.groups;
|
|
25
|
+
this.filter = options.filter ?? (() => true);
|
|
26
|
+
this.scope = options.scope ?? (() => undefined);
|
|
27
|
+
this.maxSize = options.maxSize ?? DEFAULT_BATCH_MAX_SIZE;
|
|
28
|
+
this.wait = options.wait ?? 0;
|
|
29
|
+
this.mode = options.mode ?? "buffered";
|
|
30
|
+
this.batchUrl = options.url ?? ((options) => {
|
|
31
|
+
const [pathname] = parseStandardUrl(options[0].request.url);
|
|
32
|
+
return `${pathname}/__batch__`;
|
|
33
|
+
});
|
|
34
|
+
this.maxUrlLength = options.maxUrlLength ?? 2083;
|
|
35
|
+
this.batchHeaders = options.headers ?? (async (options) => {
|
|
36
|
+
const headersList = options.map((o) => o.request.headers);
|
|
37
|
+
const commonHeaders = {};
|
|
38
|
+
for (const headers of headersList) {
|
|
39
|
+
for (const key of Object.keys(headers)) {
|
|
40
|
+
const value = headers[key];
|
|
41
|
+
if (headersList.every((h) => h[key] === value)) {
|
|
42
|
+
commonHeaders[key] = value;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return commonHeaders;
|
|
47
|
+
});
|
|
48
|
+
this.mapSubrequest = options.mapSubrequest ?? (({ request }, { headers }) => {
|
|
49
|
+
const subHeaders = { ...request.headers };
|
|
50
|
+
for (const key of Object.keys(headers)) {
|
|
51
|
+
const value = headers[key];
|
|
52
|
+
if (subHeaders[key] === value) {
|
|
53
|
+
subHeaders[key] = undefined;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
...request,
|
|
58
|
+
headers: subHeaders
|
|
59
|
+
};
|
|
60
|
+
});
|
|
61
|
+
this.mapSubresponse = options.mapSubresponse ?? ((subResponse, batchResponse) => {
|
|
62
|
+
return {
|
|
63
|
+
...subResponse,
|
|
64
|
+
headers: {
|
|
65
|
+
...batchResponse.headers,
|
|
66
|
+
...subResponse.headers
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
init(options) {
|
|
72
|
+
const transportInterceptor = async (interceptorOptions) => {
|
|
73
|
+
const { body, signal } = interceptorOptions.request;
|
|
74
|
+
if (body instanceof Blob || body instanceof FormData || body instanceof ReadableStream || isAsyncIteratorObject(body) || signal?.aborted || !value(this.filter, interceptorOptions)) {
|
|
75
|
+
return interceptorOptions.next();
|
|
76
|
+
}
|
|
77
|
+
const group = this.groups.find((group) => value(group.condition, interceptorOptions));
|
|
78
|
+
if (!group) {
|
|
79
|
+
return interceptorOptions.next();
|
|
80
|
+
}
|
|
81
|
+
const scope = this.scope(interceptorOptions);
|
|
82
|
+
return new Promise((resolve, reject) => {
|
|
83
|
+
|
|
84
|
+
if (!this.queue.size) {
|
|
85
|
+
defer(() => this.processPendingBatches(), this.wait);
|
|
86
|
+
}
|
|
87
|
+
let groups = this.queue.get(scope);
|
|
88
|
+
if (!groups) {
|
|
89
|
+
groups = new Map();
|
|
90
|
+
this.queue.set(scope, groups);
|
|
91
|
+
}
|
|
92
|
+
let queue = groups.get(group);
|
|
93
|
+
if (!queue) {
|
|
94
|
+
queue = [];
|
|
95
|
+
groups.set(group, queue);
|
|
96
|
+
}
|
|
97
|
+
queue.push([
|
|
98
|
+
interceptorOptions,
|
|
99
|
+
resolve,
|
|
100
|
+
reject,
|
|
101
|
+
captureAsyncContext()
|
|
102
|
+
]);
|
|
103
|
+
});
|
|
104
|
+
};
|
|
105
|
+
return {
|
|
106
|
+
...options,
|
|
107
|
+
transportInterceptors: [...toArray(options.transportInterceptors), transportInterceptor]
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
processPendingBatches() {
|
|
111
|
+
const pending = [...this.queue.values()];
|
|
112
|
+
this.queue.clear();
|
|
113
|
+
for (const groups of pending) {
|
|
114
|
+
for (const [group, items] of groups) {
|
|
115
|
+
const getItems = items.filter(([options]) => options.request.method === "GET");
|
|
116
|
+
const queryItems = items.filter(([options]) => options.request.method === "QUERY");
|
|
117
|
+
const unsafeItems = items.filter(([options]) => options.request.method !== "GET" && options.request.method !== "QUERY");
|
|
118
|
+
this.executeBatchInOwnContext("GET", group, getItems);
|
|
119
|
+
this.executeBatchInOwnContext("QUERY", group, queryItems);
|
|
120
|
+
this.executeBatchInOwnContext("POST", group, unsafeItems);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async executeBatchInOwnContext(method, group, groupItems) {
|
|
126
|
+
await groupItems[0]?.[3](() => this.executeBatch(method, group, groupItems));
|
|
127
|
+
}
|
|
128
|
+
async executeBatch(method, group, groupItems) {
|
|
129
|
+
try {
|
|
130
|
+
if (groupItems.length === 1) {
|
|
131
|
+
const [options, resolve, reject] = groupItems[0];
|
|
132
|
+
options.next().then(resolve).catch(reject);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const subOptionsList = groupItems.map(([options]) => options);
|
|
136
|
+
const maxSize = await value(this.maxSize, subOptionsList);
|
|
137
|
+
if (groupItems.length > maxSize) {
|
|
138
|
+
const [first, second] = splitInHalf(groupItems);
|
|
139
|
+
await Promise.all([this.executeBatch(method, group, first), this.executeBatchInOwnContext(method, group, second)]);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
const url = await value(this.batchUrl, subOptionsList);
|
|
143
|
+
const headers = await value(this.batchHeaders, subOptionsList);
|
|
144
|
+
const mode = await value(this.mode, subOptionsList);
|
|
145
|
+
let suppressErrorFromCurrentBatch = false;
|
|
146
|
+
const controller = new AbortController();
|
|
147
|
+
const pendingMessages = [];
|
|
148
|
+
const subrequests = groupItems.map(([subOptions]) => this.mapSubrequest(subOptions, {
|
|
149
|
+
url,
|
|
150
|
+
headers
|
|
151
|
+
}));
|
|
152
|
+
let batchResponse;
|
|
153
|
+
let markRequestSent;
|
|
154
|
+
const openRequestIds = new Set();
|
|
155
|
+
const cancelledRunningRequestIds = new Set();
|
|
156
|
+
let isBatchSent = false;
|
|
157
|
+
const abortIfOnlyCancelledRemain = () => {
|
|
158
|
+
if (openRequestIds.size === 0 && cancelledRunningRequestIds.size > 0) {
|
|
159
|
+
controller.abort();
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
const peer = new ClientPeer(async (message) => {
|
|
163
|
+
pendingMessages.push(message);
|
|
164
|
+
if (message.kind === "request") {
|
|
165
|
+
openRequestIds.add(message.id);
|
|
166
|
+
markRequestSent?.();
|
|
167
|
+
} else if (message.kind === "cancel" && openRequestIds.delete(message.id) && isBatchSent) {
|
|
168
|
+
cancelledRunningRequestIds.add(message.id);
|
|
169
|
+
abortIfOnlyCancelledRemain();
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
for (const [index, [subOptions, resolve, reject]] of groupItems.entries()) {
|
|
174
|
+
const sent = promiseWithResolvers();
|
|
175
|
+
markRequestSent = sent.resolve;
|
|
176
|
+
peer.request(subrequests[index]).then((subResponse) => resolve(this.mapSubresponse(subResponse, batchResponse, subOptions))).catch((error) => {
|
|
177
|
+
if (!suppressErrorFromCurrentBatch) {
|
|
178
|
+
reject(error);
|
|
179
|
+
}
|
|
180
|
+
}).then(sent.resolve);
|
|
181
|
+
await sent.promise;
|
|
182
|
+
}
|
|
183
|
+
if (openRequestIds.size === 0) {
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
isBatchSent = true;
|
|
187
|
+
|
|
188
|
+
const outgoingMessages = pendingMessages.filter((message) => openRequestIds.has(message.id));
|
|
189
|
+
try {
|
|
190
|
+
const request = {
|
|
191
|
+
url,
|
|
192
|
+
method,
|
|
193
|
+
headers: {
|
|
194
|
+
...headers,
|
|
195
|
+
[BATCH_HEADER]: mode
|
|
196
|
+
},
|
|
197
|
+
signal: controller.signal
|
|
198
|
+
};
|
|
199
|
+
if (method === "GET") {
|
|
200
|
+
const [pathname, search, hash] = parseStandardUrl(url);
|
|
201
|
+
const dataParam = `data=${safeEncodeURIComponent(stringifyJSON(outgoingMessages))}`;
|
|
202
|
+
const newUrl = search ? `${pathname}${search}&${dataParam}${hash ?? ""}` : `${pathname}?${dataParam}${hash ?? ""}`;
|
|
203
|
+
const maxUrlLength = await value(this.maxUrlLength, subOptionsList);
|
|
204
|
+
if (newUrl.length > maxUrlLength) {
|
|
205
|
+
const [first, second] = splitInHalf(groupItems);
|
|
206
|
+
suppressErrorFromCurrentBatch = true;
|
|
207
|
+
await Promise.all([
|
|
208
|
+
this.executeBatch(method, group, first),
|
|
209
|
+
this.executeBatchInOwnContext(method, group, second),
|
|
210
|
+
peer.close()
|
|
211
|
+
]);
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
request.url = newUrl;
|
|
215
|
+
} else {
|
|
216
|
+
request.body = outgoingMessages;
|
|
217
|
+
}
|
|
218
|
+
batchResponse = await groupItems[0][0].next({
|
|
219
|
+
...subOptionsList[0],
|
|
220
|
+
context: value(group.context, subOptionsList),
|
|
221
|
+
path: value(group.path, subOptionsList) ?? [],
|
|
222
|
+
request,
|
|
223
|
+
signal: controller.signal
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
if (batchResponse.status >= 400) {
|
|
227
|
+
const resolveBody = once(() => batchResponse.resolveBody());
|
|
228
|
+
const errorResponse = {
|
|
229
|
+
...batchResponse,
|
|
230
|
+
resolveBody
|
|
231
|
+
};
|
|
232
|
+
groupItems.forEach(([subOptions, resolve]) => {
|
|
233
|
+
resolve(this.mapSubresponse(errorResponse, batchResponse, subOptions));
|
|
234
|
+
});
|
|
235
|
+
suppressErrorFromCurrentBatch = true;
|
|
236
|
+
await peer.close();
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
const body = await batchResponse.resolveBody();
|
|
240
|
+
if (Array.isArray(body) && body.every((v) => isPeerMessage(v) && isServerPeerSendMessage(v))) {
|
|
241
|
+
for (const message of body) {
|
|
242
|
+
await peer.message(message);
|
|
243
|
+
}
|
|
244
|
+
} else if (body instanceof Blob) {
|
|
245
|
+
await decodeLengthPrefixedBlob(body, peer);
|
|
246
|
+
} else if (body instanceof ReadableStream) {
|
|
247
|
+
await decodeLengthPrefixedStream(body, async (message) => {
|
|
248
|
+
await peer.message(message);
|
|
249
|
+
if (isLastServerMessage(message)) {
|
|
250
|
+
openRequestIds.delete(message.id);
|
|
251
|
+
cancelledRunningRequestIds.delete(message.id);
|
|
252
|
+
abortIfOnlyCancelledRemain();
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
} else {
|
|
256
|
+
throw new TypeError("Invalid batch response format.");
|
|
257
|
+
}
|
|
258
|
+
await peer.close(new TypeError("Batch response is incomplete."));
|
|
259
|
+
} catch (error) {
|
|
260
|
+
await peer.close(error);
|
|
261
|
+
}
|
|
262
|
+
} catch (error) {
|
|
263
|
+
groupItems.forEach(([, , reject]) => reject(error));
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function isLastServerMessage(message) {
|
|
269
|
+
switch (message.kind) {
|
|
270
|
+
case "response":
|
|
271
|
+
|
|
272
|
+
return message.json.body !== undefined || message.binary !== undefined || message.json.headers?.["content-type"] === undefined && message.json.headers?.["standard-server"] === undefined;
|
|
273
|
+
case "event-stream": return message.json.event === "close" || message.json.event === "error";
|
|
274
|
+
case "octet-stream": return message.json.close === true;
|
|
275
|
+
case "cancel": return true;
|
|
276
|
+
default: return false;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
async function decodeLengthPrefixedBlob(blob, peer) {
|
|
280
|
+
const buffer = await loadBytes(blob);
|
|
281
|
+
let offset = 0;
|
|
282
|
+
while (offset < buffer.length) {
|
|
283
|
+
if (offset + 4 > buffer.length) {
|
|
284
|
+
throw new TypeError("Invalid batch response: incomplete length header.");
|
|
285
|
+
}
|
|
286
|
+
const view = new DataView(buffer.buffer, buffer.byteOffset + offset, 4);
|
|
287
|
+
const length = view.getUint32(0, false);
|
|
288
|
+
offset += 4;
|
|
289
|
+
if (offset + length > buffer.length) {
|
|
290
|
+
throw new TypeError("Invalid batch response: incomplete message.");
|
|
291
|
+
}
|
|
292
|
+
const messageBytes = buffer.subarray(offset, offset + length);
|
|
293
|
+
offset += length;
|
|
294
|
+
const result = decodePeerMessage(messageBytes);
|
|
295
|
+
if (!result.matched || !isServerPeerSendMessage(result.message)) {
|
|
296
|
+
throw new TypeError("Invalid batch response: invalid message.");
|
|
297
|
+
}
|
|
298
|
+
await peer.message(result.message);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
async function decodeLengthPrefixedStream(stream, receive) {
|
|
302
|
+
const reader = stream.getReader();
|
|
303
|
+
let buffer = new Uint8Array(0);
|
|
304
|
+
try {
|
|
305
|
+
while (true) {
|
|
306
|
+
const { done, value: chunk } = await reader.read();
|
|
307
|
+
if (chunk) {
|
|
308
|
+
const newBuffer = new Uint8Array(buffer.length + chunk.length);
|
|
309
|
+
newBuffer.set(buffer);
|
|
310
|
+
newBuffer.set(chunk, buffer.length);
|
|
311
|
+
buffer = newBuffer;
|
|
312
|
+
}
|
|
313
|
+
while (buffer.length >= 4) {
|
|
314
|
+
const view = new DataView(buffer.buffer, buffer.byteOffset, 4);
|
|
315
|
+
const length = view.getUint32(0, false);
|
|
316
|
+
|
|
317
|
+
if (length === 0) {
|
|
318
|
+
buffer = buffer.subarray(4);
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
if (buffer.length < 4 + length) {
|
|
322
|
+
break;
|
|
323
|
+
}
|
|
324
|
+
const messageBytes = buffer.subarray(4, 4 + length);
|
|
325
|
+
buffer = buffer.subarray(4 + length);
|
|
326
|
+
const result = decodePeerMessage(messageBytes);
|
|
327
|
+
if (!result.matched || !isServerPeerSendMessage(result.message)) {
|
|
328
|
+
throw new TypeError("Invalid batch response: invalid message.");
|
|
329
|
+
}
|
|
330
|
+
await receive(result.message);
|
|
331
|
+
}
|
|
332
|
+
if (done) {
|
|
333
|
+
break;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
} finally {
|
|
337
|
+
reader.releaseLock();
|
|
338
|
+
}
|
|
339
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { Value } from "@orpc/shared";
|
|
2
|
+
import type { FetchLinkTransportOptions } from "../adapters/fetch/index.mjs";
|
|
3
|
+
import type { StandardLinkOptions, StandardLinkPlugin, StandardLinkTransportInterceptorOptions } from "../adapters/standard/index.mjs";
|
|
4
|
+
import type { ClientContext } from "../types.mjs";
|
|
5
|
+
export interface CookieJarLinkPluginOptions<T extends ClientContext> {
|
|
6
|
+
/**
|
|
7
|
+
* The link's `origin`, used to match cookies by host and scheme.
|
|
8
|
+
* The plugin does nothing when it resolves to `undefined` or a relative origin, as in a browser.
|
|
9
|
+
*
|
|
10
|
+
* @example 'https://api.example.com'
|
|
11
|
+
*/
|
|
12
|
+
origin: FetchLinkTransportOptions<T>["origin"];
|
|
13
|
+
/**
|
|
14
|
+
* Where cookies are stored. Pass a function to pick a jar per request, e.g. from the client context.
|
|
15
|
+
*
|
|
16
|
+
* @default a new `CookieJar` per plugin
|
|
17
|
+
*/
|
|
18
|
+
jar?: Value<CookieJar, [options: StandardLinkTransportInterceptorOptions<T>]> | undefined;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Stores the cookies servers set and sends them back on later requests, like a browser,
|
|
22
|
+
* for server-side rendering, scripts, and tests.
|
|
23
|
+
*
|
|
24
|
+
* @remarks
|
|
25
|
+
* **Warning**: On a server, do not share one link between users: create a client per request, or pick a jar per request.
|
|
26
|
+
*
|
|
27
|
+
* @see {@link https://orpc.dev/docs/plugins/cookie-jar | Cookie Jar Plugin}
|
|
28
|
+
*/
|
|
29
|
+
export declare class CookieJarLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
|
|
30
|
+
private readonly origin;
|
|
31
|
+
private readonly jar;
|
|
32
|
+
name: string;
|
|
33
|
+
/**
|
|
34
|
+
* Runs per call, before batching, so each call gets the cookies it would get on its own.
|
|
35
|
+
*/
|
|
36
|
+
before: string[];
|
|
37
|
+
constructor(options: NoInfer<CookieJarLinkPluginOptions<T>>);
|
|
38
|
+
init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
|
|
39
|
+
}
|
|
40
|
+
export interface StoredCookie {
|
|
41
|
+
name: string;
|
|
42
|
+
value: string;
|
|
43
|
+
/**
|
|
44
|
+
* The `Domain` attribute, or else the host that set the cookie.
|
|
45
|
+
*/
|
|
46
|
+
domain: string;
|
|
47
|
+
/**
|
|
48
|
+
* True when the cookie has no `Domain` attribute, so it is sent to `domain` only, not its subdomains.
|
|
49
|
+
*/
|
|
50
|
+
hostOnly: boolean;
|
|
51
|
+
path: string;
|
|
52
|
+
secure: boolean;
|
|
53
|
+
/**
|
|
54
|
+
* Expiry time in milliseconds since the Unix epoch, `undefined` for a session cookie that lives as long as the jar.
|
|
55
|
+
*/
|
|
56
|
+
expires: number | undefined;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* An in-memory cookie store that follows the browser rules of [RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265).
|
|
60
|
+
*
|
|
61
|
+
* @see {@link https://orpc.dev/docs/plugins/cookie-jar#custom-jar | Cookie Jar Plugin - Custom Jar}
|
|
62
|
+
*/
|
|
63
|
+
export declare class CookieJar {
|
|
64
|
+
/**
|
|
65
|
+
* Keyed by domain, path, and name. Map order is creation order: replacing a cookie keeps its position.
|
|
66
|
+
*/
|
|
67
|
+
private readonly cookies;
|
|
68
|
+
/**
|
|
69
|
+
* Stores a `Set-Cookie` header value received from `url`.
|
|
70
|
+
* Cookies a browser would reject are ignored, and an expired cookie deletes the one it replaces.
|
|
71
|
+
*/
|
|
72
|
+
setCookie(setCookie: string, url: string): void;
|
|
73
|
+
/**
|
|
74
|
+
* Returns the cookies a browser would send to `url`, longer paths first, then oldest first.
|
|
75
|
+
* Without `url`, returns every stored cookie that has not expired.
|
|
76
|
+
*/
|
|
77
|
+
getCookies(url?: string): StoredCookie[];
|
|
78
|
+
/**
|
|
79
|
+
* Removes every stored cookie.
|
|
80
|
+
*/
|
|
81
|
+
clear(): void;
|
|
82
|
+
}
|