@orpc/client 0.0.0-next.8f9385e → 0.0.0-next.8fedfb3
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 +101 -0
- package/dist/adapters/fetch/index.d.mts +46 -0
- package/dist/adapters/fetch/index.d.ts +46 -0
- package/dist/adapters/fetch/index.mjs +45 -0
- package/dist/adapters/message-port/index.d.mts +59 -0
- package/dist/adapters/message-port/index.d.ts +59 -0
- package/dist/adapters/message-port/index.mjs +72 -0
- package/dist/adapters/standard/index.d.mts +11 -0
- package/dist/adapters/standard/index.d.ts +11 -0
- package/dist/adapters/standard/index.mjs +5 -0
- package/dist/adapters/websocket/index.d.mts +29 -0
- package/dist/adapters/websocket/index.d.ts +29 -0
- package/dist/adapters/websocket/index.mjs +46 -0
- package/dist/index.d.mts +230 -0
- package/dist/index.d.ts +230 -0
- package/dist/index.mjs +111 -0
- package/dist/plugins/index.d.mts +203 -0
- package/dist/plugins/index.d.ts +203 -0
- package/dist/plugins/index.mjs +407 -0
- package/dist/shared/client.B7q5G18o.mjs +208 -0
- package/dist/shared/client.BH1AYT_p.d.mts +83 -0
- package/dist/shared/client.BH1AYT_p.d.ts +83 -0
- package/dist/shared/client.BxV-mzeR.d.ts +91 -0
- package/dist/shared/client.CPgZaUox.d.mts +45 -0
- package/dist/shared/client.CsmvLSHL.mjs +397 -0
- package/dist/shared/client.D8lMmWVC.d.mts +91 -0
- package/dist/shared/client.De8SW4Kw.d.ts +45 -0
- package/package.json +34 -17
- package/dist/index.js +0 -83
- package/dist/src/index.d.ts +0 -7
- package/dist/src/procedure.d.ts +0 -27
- package/dist/src/router.d.ts +0 -34
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
import { isAsyncIteratorObject, defer, value, splitInHalf, toArray, stringifyJSON, overlayProxy, AsyncIteratorClass } from '@orpc/shared';
|
|
2
|
+
import { toBatchRequest, parseBatchResponse, toBatchAbortSignal } from '@orpc/standard-server/batch';
|
|
3
|
+
import { replicateStandardLazyResponse, getEventMeta } from '@orpc/standard-server';
|
|
4
|
+
|
|
5
|
+
class BatchLinkPlugin {
|
|
6
|
+
groups;
|
|
7
|
+
maxSize;
|
|
8
|
+
batchUrl;
|
|
9
|
+
maxUrlLength;
|
|
10
|
+
batchHeaders;
|
|
11
|
+
mapRequestItem;
|
|
12
|
+
exclude;
|
|
13
|
+
mode;
|
|
14
|
+
pending;
|
|
15
|
+
order = 5e6;
|
|
16
|
+
constructor(options) {
|
|
17
|
+
this.groups = options.groups;
|
|
18
|
+
this.pending = /* @__PURE__ */ new Map();
|
|
19
|
+
this.maxSize = options.maxSize ?? 10;
|
|
20
|
+
this.maxUrlLength = options.maxUrlLength ?? 2083;
|
|
21
|
+
this.mode = options.mode ?? "streaming";
|
|
22
|
+
this.batchUrl = options.url ?? (([options2]) => `${options2.request.url.origin}${options2.request.url.pathname}/__batch__`);
|
|
23
|
+
this.batchHeaders = options.headers ?? (([options2, ...rest]) => {
|
|
24
|
+
const headers = {};
|
|
25
|
+
for (const [key, value2] of Object.entries(options2.request.headers)) {
|
|
26
|
+
if (rest.every((item) => item.request.headers[key] === value2)) {
|
|
27
|
+
headers[key] = value2;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return headers;
|
|
31
|
+
});
|
|
32
|
+
this.mapRequestItem = options.mapRequestItem ?? (({ request, batchHeaders }) => {
|
|
33
|
+
const headers = {};
|
|
34
|
+
for (const [key, value2] of Object.entries(request.headers)) {
|
|
35
|
+
if (batchHeaders[key] !== value2) {
|
|
36
|
+
headers[key] = value2;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
method: request.method,
|
|
41
|
+
url: request.url,
|
|
42
|
+
headers,
|
|
43
|
+
body: request.body,
|
|
44
|
+
signal: request.signal
|
|
45
|
+
};
|
|
46
|
+
});
|
|
47
|
+
this.exclude = options.exclude ?? (() => false);
|
|
48
|
+
}
|
|
49
|
+
init(options) {
|
|
50
|
+
options.clientInterceptors ??= [];
|
|
51
|
+
options.clientInterceptors.push((options2) => {
|
|
52
|
+
if (options2.request.headers["x-orpc-batch"] !== "1") {
|
|
53
|
+
return options2.next();
|
|
54
|
+
}
|
|
55
|
+
return options2.next({
|
|
56
|
+
...options2,
|
|
57
|
+
request: {
|
|
58
|
+
...options2.request,
|
|
59
|
+
headers: {
|
|
60
|
+
...options2.request.headers,
|
|
61
|
+
"x-orpc-batch": void 0
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
options.clientInterceptors.push((options2) => {
|
|
67
|
+
if (this.exclude(options2) || options2.request.body instanceof Blob || options2.request.body instanceof FormData || isAsyncIteratorObject(options2.request.body) || options2.request.signal?.aborted) {
|
|
68
|
+
return options2.next();
|
|
69
|
+
}
|
|
70
|
+
const group = this.groups.find((group2) => group2.condition(options2));
|
|
71
|
+
if (!group) {
|
|
72
|
+
return options2.next();
|
|
73
|
+
}
|
|
74
|
+
return new Promise((resolve, reject) => {
|
|
75
|
+
this.#enqueueRequest(group, options2, resolve, reject);
|
|
76
|
+
defer(() => this.#processPendingBatches());
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
#enqueueRequest(group, options, resolve, reject) {
|
|
81
|
+
const items = this.pending.get(group);
|
|
82
|
+
if (items) {
|
|
83
|
+
items.push([options, resolve, reject]);
|
|
84
|
+
} else {
|
|
85
|
+
this.pending.set(group, [[options, resolve, reject]]);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async #processPendingBatches() {
|
|
89
|
+
const pending = this.pending;
|
|
90
|
+
this.pending = /* @__PURE__ */ new Map();
|
|
91
|
+
for (const [group, items] of pending) {
|
|
92
|
+
const getItems = items.filter(([options]) => options.request.method === "GET");
|
|
93
|
+
const restItems = items.filter(([options]) => options.request.method !== "GET");
|
|
94
|
+
this.#executeBatch("GET", group, getItems);
|
|
95
|
+
this.#executeBatch("POST", group, restItems);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async #executeBatch(method, group, groupItems) {
|
|
99
|
+
if (!groupItems.length) {
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const batchItems = groupItems;
|
|
103
|
+
if (batchItems.length === 1) {
|
|
104
|
+
batchItems[0][0].next().then(batchItems[0][1]).catch(batchItems[0][2]);
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
try {
|
|
108
|
+
const options = batchItems.map(([options2]) => options2);
|
|
109
|
+
const maxSize = await value(this.maxSize, options);
|
|
110
|
+
if (batchItems.length > maxSize) {
|
|
111
|
+
const [first, second] = splitInHalf(batchItems);
|
|
112
|
+
this.#executeBatch(method, group, first);
|
|
113
|
+
this.#executeBatch(method, group, second);
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
const batchUrl = new URL(await value(this.batchUrl, options));
|
|
117
|
+
const batchHeaders = await value(this.batchHeaders, options);
|
|
118
|
+
const mappedItems = batchItems.map(([options2]) => this.mapRequestItem({ ...options2, batchUrl, batchHeaders }));
|
|
119
|
+
const batchRequest = toBatchRequest({
|
|
120
|
+
method,
|
|
121
|
+
url: batchUrl,
|
|
122
|
+
headers: batchHeaders,
|
|
123
|
+
requests: mappedItems
|
|
124
|
+
});
|
|
125
|
+
const maxUrlLength = await value(this.maxUrlLength, options);
|
|
126
|
+
if (batchRequest.url.toString().length > maxUrlLength) {
|
|
127
|
+
const [first, second] = splitInHalf(batchItems);
|
|
128
|
+
this.#executeBatch(method, group, first);
|
|
129
|
+
this.#executeBatch(method, group, second);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
const mode = value(this.mode, options);
|
|
133
|
+
try {
|
|
134
|
+
const lazyResponse = await options[0].next({
|
|
135
|
+
request: { ...batchRequest, headers: { ...batchRequest.headers, "x-orpc-batch": mode } },
|
|
136
|
+
signal: batchRequest.signal,
|
|
137
|
+
context: group.context,
|
|
138
|
+
input: group.input,
|
|
139
|
+
path: toArray(group.path)
|
|
140
|
+
});
|
|
141
|
+
const parsed = parseBatchResponse({ ...lazyResponse, body: await lazyResponse.body() });
|
|
142
|
+
for await (const item of parsed) {
|
|
143
|
+
batchItems[item.index]?.[1]({ ...item, body: () => Promise.resolve(item.body) });
|
|
144
|
+
}
|
|
145
|
+
} catch (err) {
|
|
146
|
+
if (batchRequest.signal?.aborted && batchRequest.signal.reason === err) {
|
|
147
|
+
for (const [{ signal }, , reject] of batchItems) {
|
|
148
|
+
if (signal?.aborted) {
|
|
149
|
+
reject(signal.reason);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
throw err;
|
|
154
|
+
}
|
|
155
|
+
throw new Error("Something went wrong make batch response not contains enough responses. This can be a bug please report it.");
|
|
156
|
+
} catch (error) {
|
|
157
|
+
for (const [, , reject] of batchItems) {
|
|
158
|
+
reject(error);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
class DedupeRequestsPlugin {
|
|
165
|
+
#groups;
|
|
166
|
+
#filter;
|
|
167
|
+
order = 4e6;
|
|
168
|
+
// make sure execute before batch plugin
|
|
169
|
+
#queue = /* @__PURE__ */ new Map();
|
|
170
|
+
constructor(options) {
|
|
171
|
+
this.#groups = options.groups;
|
|
172
|
+
this.#filter = options.filter ?? (({ request }) => request.method === "GET");
|
|
173
|
+
}
|
|
174
|
+
init(options) {
|
|
175
|
+
options.clientInterceptors ??= [];
|
|
176
|
+
options.clientInterceptors.push((options2) => {
|
|
177
|
+
if (options2.request.body instanceof Blob || options2.request.body instanceof FormData || options2.request.body instanceof URLSearchParams || isAsyncIteratorObject(options2.request.body) || !this.#filter(options2)) {
|
|
178
|
+
return options2.next();
|
|
179
|
+
}
|
|
180
|
+
const group = this.#groups.find((group2) => group2.condition(options2));
|
|
181
|
+
if (!group) {
|
|
182
|
+
return options2.next();
|
|
183
|
+
}
|
|
184
|
+
return new Promise((resolve, reject) => {
|
|
185
|
+
this.#enqueue(group, options2, resolve, reject);
|
|
186
|
+
defer(() => this.#dequeue());
|
|
187
|
+
});
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
#enqueue(group, options, resolve, reject) {
|
|
191
|
+
let queue = this.#queue.get(group);
|
|
192
|
+
if (!queue) {
|
|
193
|
+
this.#queue.set(group, queue = []);
|
|
194
|
+
}
|
|
195
|
+
const matched = queue.find((item) => {
|
|
196
|
+
const requestString1 = stringifyJSON({
|
|
197
|
+
body: item.options.request.body,
|
|
198
|
+
headers: item.options.request.headers,
|
|
199
|
+
method: item.options.request.method,
|
|
200
|
+
url: item.options.request.url
|
|
201
|
+
});
|
|
202
|
+
const requestString2 = stringifyJSON({
|
|
203
|
+
body: options.request.body,
|
|
204
|
+
headers: options.request.headers,
|
|
205
|
+
method: options.request.method,
|
|
206
|
+
url: options.request.url
|
|
207
|
+
});
|
|
208
|
+
return requestString1 === requestString2;
|
|
209
|
+
});
|
|
210
|
+
if (matched) {
|
|
211
|
+
matched.signals.push(options.request.signal);
|
|
212
|
+
matched.resolves.push(resolve);
|
|
213
|
+
matched.rejects.push(reject);
|
|
214
|
+
} else {
|
|
215
|
+
queue.push({
|
|
216
|
+
options,
|
|
217
|
+
signals: [options.request.signal],
|
|
218
|
+
resolves: [resolve],
|
|
219
|
+
rejects: [reject]
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
async #dequeue() {
|
|
224
|
+
const promises = [];
|
|
225
|
+
for (const [group, items] of this.#queue) {
|
|
226
|
+
for (const { options, signals, resolves, rejects } of items) {
|
|
227
|
+
promises.push(
|
|
228
|
+
this.#execute(group, options, signals, resolves, rejects)
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
this.#queue.clear();
|
|
233
|
+
await Promise.all(promises);
|
|
234
|
+
}
|
|
235
|
+
async #execute(group, options, signals, resolves, rejects) {
|
|
236
|
+
try {
|
|
237
|
+
const dedupedRequest = {
|
|
238
|
+
...options.request,
|
|
239
|
+
signal: toBatchAbortSignal(signals)
|
|
240
|
+
};
|
|
241
|
+
const response = await options.next({
|
|
242
|
+
...options,
|
|
243
|
+
request: dedupedRequest,
|
|
244
|
+
signal: dedupedRequest.signal,
|
|
245
|
+
context: group.context
|
|
246
|
+
});
|
|
247
|
+
const replicatedResponses = replicateStandardLazyResponse(response, resolves.length);
|
|
248
|
+
for (const resolve of resolves) {
|
|
249
|
+
resolve(replicatedResponses.shift());
|
|
250
|
+
}
|
|
251
|
+
} catch (error) {
|
|
252
|
+
for (const reject of rejects) {
|
|
253
|
+
reject(error);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
class ClientRetryPluginInvalidEventIteratorRetryResponse extends Error {
|
|
260
|
+
}
|
|
261
|
+
class ClientRetryPlugin {
|
|
262
|
+
defaultRetry;
|
|
263
|
+
defaultRetryDelay;
|
|
264
|
+
defaultShouldRetry;
|
|
265
|
+
defaultOnRetry;
|
|
266
|
+
order = 18e5;
|
|
267
|
+
constructor(options = {}) {
|
|
268
|
+
this.defaultRetry = options.default?.retry ?? 0;
|
|
269
|
+
this.defaultRetryDelay = options.default?.retryDelay ?? ((o) => o.lastEventRetry ?? 2e3);
|
|
270
|
+
this.defaultShouldRetry = options.default?.shouldRetry ?? true;
|
|
271
|
+
this.defaultOnRetry = options.default?.onRetry;
|
|
272
|
+
}
|
|
273
|
+
init(options) {
|
|
274
|
+
options.interceptors ??= [];
|
|
275
|
+
options.interceptors.push(async (interceptorOptions) => {
|
|
276
|
+
const maxAttempts = await value(
|
|
277
|
+
interceptorOptions.context.retry ?? this.defaultRetry,
|
|
278
|
+
interceptorOptions
|
|
279
|
+
);
|
|
280
|
+
const retryDelay = interceptorOptions.context.retryDelay ?? this.defaultRetryDelay;
|
|
281
|
+
const shouldRetry = interceptorOptions.context.shouldRetry ?? this.defaultShouldRetry;
|
|
282
|
+
const onRetry = interceptorOptions.context.onRetry ?? this.defaultOnRetry;
|
|
283
|
+
if (maxAttempts <= 0) {
|
|
284
|
+
return interceptorOptions.next();
|
|
285
|
+
}
|
|
286
|
+
let lastEventId = interceptorOptions.lastEventId;
|
|
287
|
+
let lastEventRetry;
|
|
288
|
+
let callback;
|
|
289
|
+
let attemptIndex = 0;
|
|
290
|
+
const next = async (initialError) => {
|
|
291
|
+
let currentError = initialError;
|
|
292
|
+
while (true) {
|
|
293
|
+
const updatedInterceptorOptions = { ...interceptorOptions, lastEventId };
|
|
294
|
+
if (currentError) {
|
|
295
|
+
if (attemptIndex >= maxAttempts) {
|
|
296
|
+
throw currentError.error;
|
|
297
|
+
}
|
|
298
|
+
const attemptOptions = {
|
|
299
|
+
...updatedInterceptorOptions,
|
|
300
|
+
attemptIndex,
|
|
301
|
+
error: currentError.error,
|
|
302
|
+
lastEventRetry
|
|
303
|
+
};
|
|
304
|
+
const shouldRetryBool = await value(
|
|
305
|
+
shouldRetry,
|
|
306
|
+
attemptOptions
|
|
307
|
+
);
|
|
308
|
+
if (!shouldRetryBool) {
|
|
309
|
+
throw currentError.error;
|
|
310
|
+
}
|
|
311
|
+
callback = onRetry?.(attemptOptions);
|
|
312
|
+
const retryDelayMs = await value(retryDelay, attemptOptions);
|
|
313
|
+
await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
|
|
314
|
+
attemptIndex++;
|
|
315
|
+
}
|
|
316
|
+
try {
|
|
317
|
+
currentError = void 0;
|
|
318
|
+
return await interceptorOptions.next(updatedInterceptorOptions);
|
|
319
|
+
} catch (error) {
|
|
320
|
+
currentError = { error };
|
|
321
|
+
if (updatedInterceptorOptions.signal?.aborted) {
|
|
322
|
+
throw error;
|
|
323
|
+
}
|
|
324
|
+
} finally {
|
|
325
|
+
callback?.(!currentError);
|
|
326
|
+
callback = void 0;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
const output = await next();
|
|
331
|
+
if (!isAsyncIteratorObject(output)) {
|
|
332
|
+
return output;
|
|
333
|
+
}
|
|
334
|
+
let current = output;
|
|
335
|
+
let isIteratorAborted = false;
|
|
336
|
+
return overlayProxy(() => current, new AsyncIteratorClass(
|
|
337
|
+
async () => {
|
|
338
|
+
while (true) {
|
|
339
|
+
try {
|
|
340
|
+
const item = await current.next();
|
|
341
|
+
const meta = getEventMeta(item.value);
|
|
342
|
+
lastEventId = meta?.id ?? lastEventId;
|
|
343
|
+
lastEventRetry = meta?.retry ?? lastEventRetry;
|
|
344
|
+
return item;
|
|
345
|
+
} catch (error) {
|
|
346
|
+
const meta = getEventMeta(error);
|
|
347
|
+
lastEventId = meta?.id ?? lastEventId;
|
|
348
|
+
lastEventRetry = meta?.retry ?? lastEventRetry;
|
|
349
|
+
const maybeEventIterator = await next({ error });
|
|
350
|
+
if (!isAsyncIteratorObject(maybeEventIterator)) {
|
|
351
|
+
throw new ClientRetryPluginInvalidEventIteratorRetryResponse(
|
|
352
|
+
"RetryPlugin: Expected an Event Iterator, got a non-Event Iterator"
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
current = maybeEventIterator;
|
|
356
|
+
if (isIteratorAborted) {
|
|
357
|
+
await current.return?.();
|
|
358
|
+
throw error;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
},
|
|
363
|
+
async (reason) => {
|
|
364
|
+
isIteratorAborted = true;
|
|
365
|
+
if (reason !== "next") {
|
|
366
|
+
await current.return?.();
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
));
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
class SimpleCsrfProtectionLinkPlugin {
|
|
375
|
+
headerName;
|
|
376
|
+
headerValue;
|
|
377
|
+
exclude;
|
|
378
|
+
constructor(options = {}) {
|
|
379
|
+
this.headerName = options.headerName ?? "x-csrf-token";
|
|
380
|
+
this.headerValue = options.headerValue ?? "orpc";
|
|
381
|
+
this.exclude = options.exclude ?? false;
|
|
382
|
+
}
|
|
383
|
+
order = 8e6;
|
|
384
|
+
init(options) {
|
|
385
|
+
options.clientInterceptors ??= [];
|
|
386
|
+
options.clientInterceptors.push(async (options2) => {
|
|
387
|
+
const excluded = await value(this.exclude, options2);
|
|
388
|
+
if (excluded) {
|
|
389
|
+
return options2.next();
|
|
390
|
+
}
|
|
391
|
+
const headerName = await value(this.headerName, options2);
|
|
392
|
+
const headerValue = await value(this.headerValue, options2);
|
|
393
|
+
return options2.next({
|
|
394
|
+
...options2,
|
|
395
|
+
request: {
|
|
396
|
+
...options2.request,
|
|
397
|
+
headers: {
|
|
398
|
+
...options2.request.headers,
|
|
399
|
+
[headerName]: headerValue
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
});
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
export { BatchLinkPlugin, ClientRetryPlugin, ClientRetryPluginInvalidEventIteratorRetryResponse, DedupeRequestsPlugin, SimpleCsrfProtectionLinkPlugin };
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { resolveMaybeOptionalOptions, getConstructor, isObject, AsyncIteratorClass, isTypescriptObject } from '@orpc/shared';
|
|
2
|
+
import { getEventMeta, withEventMeta } from '@orpc/standard-server';
|
|
3
|
+
|
|
4
|
+
const ORPC_CLIENT_PACKAGE_NAME = "@orpc/client";
|
|
5
|
+
const ORPC_CLIENT_PACKAGE_VERSION = "0.0.0-next.8fedfb3";
|
|
6
|
+
|
|
7
|
+
const COMMON_ORPC_ERROR_DEFS = {
|
|
8
|
+
BAD_REQUEST: {
|
|
9
|
+
status: 400,
|
|
10
|
+
message: "Bad Request"
|
|
11
|
+
},
|
|
12
|
+
UNAUTHORIZED: {
|
|
13
|
+
status: 401,
|
|
14
|
+
message: "Unauthorized"
|
|
15
|
+
},
|
|
16
|
+
FORBIDDEN: {
|
|
17
|
+
status: 403,
|
|
18
|
+
message: "Forbidden"
|
|
19
|
+
},
|
|
20
|
+
NOT_FOUND: {
|
|
21
|
+
status: 404,
|
|
22
|
+
message: "Not Found"
|
|
23
|
+
},
|
|
24
|
+
METHOD_NOT_SUPPORTED: {
|
|
25
|
+
status: 405,
|
|
26
|
+
message: "Method Not Supported"
|
|
27
|
+
},
|
|
28
|
+
NOT_ACCEPTABLE: {
|
|
29
|
+
status: 406,
|
|
30
|
+
message: "Not Acceptable"
|
|
31
|
+
},
|
|
32
|
+
TIMEOUT: {
|
|
33
|
+
status: 408,
|
|
34
|
+
message: "Request Timeout"
|
|
35
|
+
},
|
|
36
|
+
CONFLICT: {
|
|
37
|
+
status: 409,
|
|
38
|
+
message: "Conflict"
|
|
39
|
+
},
|
|
40
|
+
PRECONDITION_FAILED: {
|
|
41
|
+
status: 412,
|
|
42
|
+
message: "Precondition Failed"
|
|
43
|
+
},
|
|
44
|
+
PAYLOAD_TOO_LARGE: {
|
|
45
|
+
status: 413,
|
|
46
|
+
message: "Payload Too Large"
|
|
47
|
+
},
|
|
48
|
+
UNSUPPORTED_MEDIA_TYPE: {
|
|
49
|
+
status: 415,
|
|
50
|
+
message: "Unsupported Media Type"
|
|
51
|
+
},
|
|
52
|
+
UNPROCESSABLE_CONTENT: {
|
|
53
|
+
status: 422,
|
|
54
|
+
message: "Unprocessable Content"
|
|
55
|
+
},
|
|
56
|
+
TOO_MANY_REQUESTS: {
|
|
57
|
+
status: 429,
|
|
58
|
+
message: "Too Many Requests"
|
|
59
|
+
},
|
|
60
|
+
CLIENT_CLOSED_REQUEST: {
|
|
61
|
+
status: 499,
|
|
62
|
+
message: "Client Closed Request"
|
|
63
|
+
},
|
|
64
|
+
INTERNAL_SERVER_ERROR: {
|
|
65
|
+
status: 500,
|
|
66
|
+
message: "Internal Server Error"
|
|
67
|
+
},
|
|
68
|
+
NOT_IMPLEMENTED: {
|
|
69
|
+
status: 501,
|
|
70
|
+
message: "Not Implemented"
|
|
71
|
+
},
|
|
72
|
+
BAD_GATEWAY: {
|
|
73
|
+
status: 502,
|
|
74
|
+
message: "Bad Gateway"
|
|
75
|
+
},
|
|
76
|
+
SERVICE_UNAVAILABLE: {
|
|
77
|
+
status: 503,
|
|
78
|
+
message: "Service Unavailable"
|
|
79
|
+
},
|
|
80
|
+
GATEWAY_TIMEOUT: {
|
|
81
|
+
status: 504,
|
|
82
|
+
message: "Gateway Timeout"
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
function fallbackORPCErrorStatus(code, status) {
|
|
86
|
+
return status ?? COMMON_ORPC_ERROR_DEFS[code]?.status ?? 500;
|
|
87
|
+
}
|
|
88
|
+
function fallbackORPCErrorMessage(code, message) {
|
|
89
|
+
return message || COMMON_ORPC_ERROR_DEFS[code]?.message || code;
|
|
90
|
+
}
|
|
91
|
+
const GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL = Symbol.for(`__${ORPC_CLIENT_PACKAGE_NAME}@${ORPC_CLIENT_PACKAGE_VERSION}/error/ORPC_ERROR_CONSTRUCTORS__`);
|
|
92
|
+
void (globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL] ??= /* @__PURE__ */ new WeakSet());
|
|
93
|
+
const globalORPCErrorConstructors = globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL];
|
|
94
|
+
class ORPCError extends Error {
|
|
95
|
+
defined;
|
|
96
|
+
code;
|
|
97
|
+
status;
|
|
98
|
+
data;
|
|
99
|
+
constructor(code, ...rest) {
|
|
100
|
+
const options = resolveMaybeOptionalOptions(rest);
|
|
101
|
+
if (options.status !== void 0 && !isORPCErrorStatus(options.status)) {
|
|
102
|
+
throw new Error("[ORPCError] Invalid error status code.");
|
|
103
|
+
}
|
|
104
|
+
const message = fallbackORPCErrorMessage(code, options.message);
|
|
105
|
+
super(message, options);
|
|
106
|
+
this.code = code;
|
|
107
|
+
this.status = fallbackORPCErrorStatus(code, options.status);
|
|
108
|
+
this.defined = options.defined ?? false;
|
|
109
|
+
this.data = options.data;
|
|
110
|
+
}
|
|
111
|
+
toJSON() {
|
|
112
|
+
return {
|
|
113
|
+
defined: this.defined,
|
|
114
|
+
code: this.code,
|
|
115
|
+
status: this.status,
|
|
116
|
+
message: this.message,
|
|
117
|
+
data: this.data
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Workaround for Next.js where different contexts use separate
|
|
122
|
+
* dependency graphs, causing multiple ORPCError constructors existing and breaking
|
|
123
|
+
* `instanceof` checks across contexts.
|
|
124
|
+
*
|
|
125
|
+
* This is particularly problematic with "Optimized SSR", where orpc-client
|
|
126
|
+
* executes in one context but is invoked from another. When an error is thrown
|
|
127
|
+
* in the execution context, `instanceof ORPCError` checks fail in the
|
|
128
|
+
* invocation context due to separate class constructors.
|
|
129
|
+
*
|
|
130
|
+
* @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.
|
|
131
|
+
*/
|
|
132
|
+
static [Symbol.hasInstance](instance) {
|
|
133
|
+
if (globalORPCErrorConstructors.has(this)) {
|
|
134
|
+
const constructor = getConstructor(instance);
|
|
135
|
+
if (constructor && globalORPCErrorConstructors.has(constructor)) {
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return super[Symbol.hasInstance](instance);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
globalORPCErrorConstructors.add(ORPCError);
|
|
143
|
+
function isDefinedError(error) {
|
|
144
|
+
return error instanceof ORPCError && error.defined;
|
|
145
|
+
}
|
|
146
|
+
function toORPCError(error) {
|
|
147
|
+
return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", {
|
|
148
|
+
message: "Internal server error",
|
|
149
|
+
cause: error
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
function isORPCErrorStatus(status) {
|
|
153
|
+
return status < 200 || status >= 400;
|
|
154
|
+
}
|
|
155
|
+
function isORPCErrorJson(json) {
|
|
156
|
+
if (!isObject(json)) {
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
const validKeys = ["defined", "code", "status", "message", "data"];
|
|
160
|
+
if (Object.keys(json).some((k) => !validKeys.includes(k))) {
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
return "defined" in json && typeof json.defined === "boolean" && "code" in json && typeof json.code === "string" && "status" in json && typeof json.status === "number" && isORPCErrorStatus(json.status) && "message" in json && typeof json.message === "string";
|
|
164
|
+
}
|
|
165
|
+
function createORPCErrorFromJson(json, options = {}) {
|
|
166
|
+
return new ORPCError(json.code, {
|
|
167
|
+
...options,
|
|
168
|
+
...json
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function mapEventIterator(iterator, maps) {
|
|
173
|
+
const mapError = async (error) => {
|
|
174
|
+
let mappedError = await maps.error(error);
|
|
175
|
+
if (mappedError !== error) {
|
|
176
|
+
const meta = getEventMeta(error);
|
|
177
|
+
if (meta && isTypescriptObject(mappedError)) {
|
|
178
|
+
mappedError = withEventMeta(mappedError, meta);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return mappedError;
|
|
182
|
+
};
|
|
183
|
+
return new AsyncIteratorClass(async () => {
|
|
184
|
+
const { done, value } = await (async () => {
|
|
185
|
+
try {
|
|
186
|
+
return await iterator.next();
|
|
187
|
+
} catch (error) {
|
|
188
|
+
throw await mapError(error);
|
|
189
|
+
}
|
|
190
|
+
})();
|
|
191
|
+
let mappedValue = await maps.value(value, done);
|
|
192
|
+
if (mappedValue !== value) {
|
|
193
|
+
const meta = getEventMeta(value);
|
|
194
|
+
if (meta && isTypescriptObject(mappedValue)) {
|
|
195
|
+
mappedValue = withEventMeta(mappedValue, meta);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return { done, value: mappedValue };
|
|
199
|
+
}, async () => {
|
|
200
|
+
try {
|
|
201
|
+
await iterator.return?.();
|
|
202
|
+
} catch (error) {
|
|
203
|
+
throw await mapError(error);
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export { COMMON_ORPC_ERROR_DEFS as C, ORPC_CLIENT_PACKAGE_NAME as O, ORPC_CLIENT_PACKAGE_VERSION as a, fallbackORPCErrorMessage as b, ORPCError as c, isORPCErrorStatus as d, isORPCErrorJson as e, fallbackORPCErrorStatus as f, createORPCErrorFromJson as g, isDefinedError as i, mapEventIterator as m, toORPCError as t };
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { PromiseWithError } from '@orpc/shared';
|
|
2
|
+
|
|
3
|
+
type HTTPPath = `/${string}`;
|
|
4
|
+
type HTTPMethod = 'HEAD' | 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
|
5
|
+
type ClientContext = Record<PropertyKey, any>;
|
|
6
|
+
interface ClientOptions<T extends ClientContext> {
|
|
7
|
+
signal?: AbortSignal;
|
|
8
|
+
lastEventId?: string | undefined;
|
|
9
|
+
context: T;
|
|
10
|
+
}
|
|
11
|
+
type FriendlyClientOptions<T extends ClientContext> = Omit<ClientOptions<T>, 'context'> & (Record<never, never> extends T ? {
|
|
12
|
+
context?: T;
|
|
13
|
+
} : {
|
|
14
|
+
context: T;
|
|
15
|
+
});
|
|
16
|
+
type ClientRest<TClientContext extends ClientContext, TInput> = Record<never, never> extends TClientContext ? undefined extends TInput ? [input?: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options: FriendlyClientOptions<TClientContext>];
|
|
17
|
+
type ClientPromiseResult<TOutput, TError> = PromiseWithError<TOutput, TError>;
|
|
18
|
+
interface Client<TClientContext extends ClientContext, TInput, TOutput, TError> {
|
|
19
|
+
(...rest: ClientRest<TClientContext, TInput>): ClientPromiseResult<TOutput, TError>;
|
|
20
|
+
}
|
|
21
|
+
type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | {
|
|
22
|
+
[k: string]: NestedClient<TClientContext>;
|
|
23
|
+
};
|
|
24
|
+
type InferClientContext<T extends NestedClient<any>> = T extends NestedClient<infer U> ? U : never;
|
|
25
|
+
interface ClientLink<TClientContext extends ClientContext> {
|
|
26
|
+
call: (path: readonly string[], input: unknown, options: ClientOptions<TClientContext>) => Promise<unknown>;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Recursively infers the **input types** from a client.
|
|
30
|
+
*
|
|
31
|
+
* Produces a nested map where each endpoint's input type is preserved.
|
|
32
|
+
*/
|
|
33
|
+
type InferClientInputs<T extends NestedClient<any>> = T extends Client<any, infer U, any, any> ? U : {
|
|
34
|
+
[K in keyof T]: T[K] extends NestedClient<any> ? InferClientInputs<T[K]> : never;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Recursively infers the **body input types** from a client.
|
|
38
|
+
*
|
|
39
|
+
* If an endpoint's input includes `{ body: ... }`, only the `body` portion is extracted.
|
|
40
|
+
* Produces a nested map of body input types.
|
|
41
|
+
*/
|
|
42
|
+
type InferClientBodyInputs<T extends NestedClient<any>> = T extends Client<any, infer U, any, any> ? U extends {
|
|
43
|
+
body: infer UBody;
|
|
44
|
+
} ? UBody : U : {
|
|
45
|
+
[K in keyof T]: T[K] extends NestedClient<any> ? InferClientBodyInputs<T[K]> : never;
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Recursively infers the **output types** from a client.
|
|
49
|
+
*
|
|
50
|
+
* Produces a nested map where each endpoint's output type is preserved.
|
|
51
|
+
*/
|
|
52
|
+
type InferClientOutputs<T extends NestedClient<any>> = T extends Client<any, any, infer U, any> ? U : {
|
|
53
|
+
[K in keyof T]: T[K] extends NestedClient<any> ? InferClientOutputs<T[K]> : never;
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Recursively infers the **body output types** from a client.
|
|
57
|
+
*
|
|
58
|
+
* If an endpoint's output includes `{ body: ... }`, only the `body` portion is extracted.
|
|
59
|
+
* Produces a nested map of body output types.
|
|
60
|
+
*/
|
|
61
|
+
type InferClientBodyOutputs<T extends NestedClient<any>> = T extends Client<any, any, infer U, any> ? U extends {
|
|
62
|
+
body: infer UBody;
|
|
63
|
+
} ? UBody : U : {
|
|
64
|
+
[K in keyof T]: T[K] extends NestedClient<any> ? InferClientBodyOutputs<T[K]> : never;
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Recursively infers the **error types** from a client when you use [type-safe errors](https://orpc.unnoq.com/docs/error-handling#type‐safe-error-handling).
|
|
68
|
+
*
|
|
69
|
+
* Produces a nested map where each endpoint's error type is preserved.
|
|
70
|
+
*/
|
|
71
|
+
type InferClientErrors<T extends NestedClient<any>> = T extends Client<any, any, any, infer U> ? U : {
|
|
72
|
+
[K in keyof T]: T[K] extends NestedClient<any> ? InferClientErrors<T[K]> : never;
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* Recursively infers a **union of all error types** from a client when you use [type-safe errors](https://orpc.unnoq.com/docs/error-handling#type‐safe-error-handling).
|
|
76
|
+
*
|
|
77
|
+
* Useful when you want to handle all possible errors from any endpoint at once.
|
|
78
|
+
*/
|
|
79
|
+
type InferClientErrorUnion<T extends NestedClient<any>> = T extends Client<any, any, any, infer U> ? U : {
|
|
80
|
+
[K in keyof T]: T[K] extends NestedClient<any> ? InferClientErrorUnion<T[K]> : never;
|
|
81
|
+
}[keyof T];
|
|
82
|
+
|
|
83
|
+
export type { ClientLink as C, FriendlyClientOptions as F, HTTPPath as H, InferClientContext as I, NestedClient as N, ClientPromiseResult as a, ClientContext as b, ClientOptions as c, Client as d, ClientRest as e, HTTPMethod as f, InferClientInputs as g, InferClientBodyInputs as h, InferClientOutputs as i, InferClientBodyOutputs as j, InferClientErrors as k, InferClientErrorUnion as l };
|