@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,347 @@
1
+ import { DEFAULT_MAX_BIGINT_DIGITS, NullProtoObj, copyOnWrite, isPlainObject, isPlainObjectOrArray, parseBigIntString } from "@orpc/shared";
2
+ // src/rpc-json-serializer.ts
3
+ function invalidSerializedData(detail) {
4
+ return /* @__PURE__ */ new TypeError(`Invalid RPC serialized data: ${detail}`);
5
+ }
6
+ function assertSerializedType(ok, type, expected) {
7
+ if (!ok) throw invalidSerializedData(`type "${type}" expects ${expected}.`);
8
+ }
9
+ function walkInto(parent, key, original, restored) {
10
+ const value = parent[key];
11
+ if (!isPlainObjectOrArray(value) || restored?.has(value)) throw invalidSerializedData(`segment "${key}" cannot be walked into.`);
12
+ return value === original ? copyOnWrite(parent, key, original) : value;
13
+ }
14
+ const DEFAULT_RPC_JSON_SERIALIZER_HANDLERS = {
15
+ undefined: {
16
+ condition(data) {
17
+ return data === void 0;
18
+ },
19
+ serialize() {
20
+ return null;
21
+ },
22
+ deserialize(serialized) {
23
+ assertSerializedType(serialized === null, "undefined", "null");
24
+ },
25
+ isTerminal: true
26
+ },
27
+ bigint: {
28
+ condition(data) {
29
+ return typeof data === "bigint";
30
+ },
31
+ serialize(data) {
32
+ return data.toString();
33
+ },
34
+ deserialize(serialized) {
35
+ assertSerializedType(typeof serialized === "string", "bigint", "a string");
36
+ const value = parseBigIntString(serialized, DEFAULT_MAX_BIGINT_DIGITS);
37
+ if (value === void 0) throw invalidSerializedData(`type "bigint" expects a decimal integer string of at most ${DEFAULT_MAX_BIGINT_DIGITS} digits.`);
38
+ return value;
39
+ },
40
+ isTerminal: true
41
+ },
42
+ date: {
43
+ condition(data) {
44
+ return data instanceof Date;
45
+ },
46
+ serialize(data) {
47
+ if (Number.isNaN(data.getTime())) return null;
48
+ return data.toISOString();
49
+ },
50
+ deserialize(serialized) {
51
+ assertSerializedType(typeof serialized === "string" || serialized === null, "date", "a string or null");
52
+ return new Date(serialized ?? NaN);
53
+ },
54
+ isTerminal: true
55
+ },
56
+ nan: {
57
+ condition(data) {
58
+ return typeof data === "number" && Number.isNaN(data);
59
+ },
60
+ serialize() {
61
+ return null;
62
+ },
63
+ deserialize(serialized) {
64
+ assertSerializedType(serialized === null, "nan", "null");
65
+ return NaN;
66
+ },
67
+ isTerminal: true
68
+ },
69
+ infinity: {
70
+ condition(data) {
71
+ return data === Number.POSITIVE_INFINITY || data === Number.NEGATIVE_INFINITY;
72
+ },
73
+ serialize(data) {
74
+ return data > 0 ? "Infinity" : "-Infinity";
75
+ },
76
+ deserialize(serialized) {
77
+ assertSerializedType(serialized === "Infinity" || serialized === "-Infinity", "infinity", "\"Infinity\" or \"-Infinity\"");
78
+ return serialized === "Infinity" ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
79
+ },
80
+ isTerminal: true
81
+ },
82
+ url: {
83
+ condition(data) {
84
+ return data instanceof URL;
85
+ },
86
+ serialize(data) {
87
+ return data.toString();
88
+ },
89
+ deserialize(serialized) {
90
+ assertSerializedType(typeof serialized === "string", "url", "a string");
91
+ return new URL(serialized);
92
+ },
93
+ isTerminal: true
94
+ },
95
+ set: {
96
+ condition(data) {
97
+ return data instanceof Set;
98
+ },
99
+ serialize(data) {
100
+ return Array.from(data);
101
+ },
102
+ deserialize(serialized) {
103
+ assertSerializedType(Array.isArray(serialized), "set", "an array");
104
+ return new Set(serialized);
105
+ }
106
+ },
107
+ map: {
108
+ condition(data) {
109
+ return data instanceof Map;
110
+ },
111
+ serialize(data) {
112
+ return Array.from(data.entries());
113
+ },
114
+ deserialize(serialized) {
115
+ assertSerializedType(Array.isArray(serialized), "map", "an array");
116
+ return new Map(serialized);
117
+ }
118
+ }
119
+ };
120
+ /**
121
+ * Serializes and deserializes native types like Date, BigInt, Set, and Map
122
+ * into a JSON value plus separate metadata describing how to restore them.
123
+ *
124
+ * @see {@link https://orpc.dev/docs/rpc/serializer#rpc-json-serializer | RPC Serializer - RPC JSON Serializer}
125
+ */
126
+ var RPCJsonSerializer = class {
127
+ handlers;
128
+ inlineBuiltInHandlers;
129
+ handlerEntries;
130
+ omitUndefinedProperties;
131
+ constructor(options = {}) {
132
+ this.omitUndefinedProperties = options.omitUndefinedProperties !== false;
133
+ this.handlers = Object.assign(new NullProtoObj(), DEFAULT_RPC_JSON_SERIALIZER_HANDLERS);
134
+ const customHandlers = options.handlers;
135
+ if (customHandlers === void 0) {
136
+ this.inlineBuiltInHandlers = true;
137
+ return;
138
+ }
139
+ let inlineBuiltInHandlers = true;
140
+ let handlerEntries = [];
141
+ for (const key of Object.keys(customHandlers)) {
142
+ const handler = customHandlers[key];
143
+ this.handlers[key] = handler;
144
+ if (inlineBuiltInHandlers && key in DEFAULT_RPC_JSON_SERIALIZER_HANDLERS) inlineBuiltInHandlers = false;
145
+ if (inlineBuiltInHandlers && handler !== void 0) handlerEntries.push([key, handler]);
146
+ }
147
+ if (!inlineBuiltInHandlers) {
148
+ handlerEntries = [];
149
+ for (const key of Object.keys(this.handlers)) {
150
+ const handler = this.handlers[key];
151
+ if (handler !== void 0) handlerEntries.push([key, handler]);
152
+ }
153
+ }
154
+ this.inlineBuiltInHandlers = inlineBuiltInHandlers;
155
+ this.handlerEntries = handlerEntries.length === 0 ? void 0 : handlerEntries;
156
+ }
157
+ serializeJson(data) {
158
+ let meta = [];
159
+ const maps = [];
160
+ const blobs = [];
161
+ const json = this.serializeValue(data, [], meta, maps, blobs);
162
+ meta = meta.length === 0 ? void 0 : meta;
163
+ if (maps.length === 0) return {
164
+ json,
165
+ meta
166
+ };
167
+ return {
168
+ json,
169
+ meta,
170
+ maps,
171
+ blobs
172
+ };
173
+ }
174
+ /**
175
+ * `segments` is a shared mutable stack (push/pop while walking),
176
+ * so it must be copied before being stored in `meta` or `maps`.
177
+ */
178
+ serializeValue(data, segments, meta, maps, blobs) {
179
+ const handlerEntries = this.handlerEntries;
180
+ /**
181
+ * Inlined version of DEFAULT_RPC_JSON_SERIALIZER_HANDLERS: primitives are
182
+ * dispatched on typeof and skip every handler condition check.
183
+ * Must match the built-in handlers exactly.
184
+ * Primitives without a built-in handler return early unless custom handlers must see them.
185
+ */
186
+ if (this.inlineBuiltInHandlers) switch (typeof data) {
187
+ case "string":
188
+ case "boolean":
189
+ if (handlerEntries === void 0) return data;
190
+ break;
191
+ case "number":
192
+ if (Number.isFinite(data)) {
193
+ if (handlerEntries === void 0) return data;
194
+ break;
195
+ }
196
+ if (Number.isNaN(data)) {
197
+ meta.push(["nan", ...segments]);
198
+ return null;
199
+ }
200
+ meta.push(["infinity", ...segments]);
201
+ return data > 0 ? "Infinity" : "-Infinity";
202
+ case "undefined":
203
+ meta.push(["undefined", ...segments]);
204
+ return null;
205
+ case "bigint":
206
+ meta.push(["bigint", ...segments]);
207
+ return data.toString();
208
+ case "object":
209
+ if (data === null) {
210
+ if (handlerEntries === void 0) return data;
211
+ break;
212
+ }
213
+ if (data instanceof Date) {
214
+ meta.push(["date", ...segments]);
215
+ return Number.isNaN(data.getTime()) ? null : data.toISOString();
216
+ }
217
+ if (data instanceof URL) {
218
+ meta.push(["url", ...segments]);
219
+ return data.toString();
220
+ }
221
+ if (data instanceof Set) {
222
+ const result = this.serializeValue(Array.from(data), segments, meta, maps, blobs);
223
+ meta.push(["set", ...segments]);
224
+ return result;
225
+ }
226
+ if (data instanceof Map) {
227
+ const result = this.serializeValue(Array.from(data.entries()), segments, meta, maps, blobs);
228
+ meta.push(["map", ...segments]);
229
+ return result;
230
+ }
231
+ }
232
+ if (handlerEntries) for (let i = 0; i < handlerEntries.length; i++) {
233
+ const entry = handlerEntries[i];
234
+ const handler = entry[1];
235
+ if (handler.condition(data)) {
236
+ const serialized = handler.serialize(data);
237
+ if (handler.isTerminal) {
238
+ meta.push([entry[0], ...segments]);
239
+ if (serialized instanceof Blob) {
240
+ maps.push(segments.slice());
241
+ blobs.push(serialized);
242
+ }
243
+ return serialized;
244
+ }
245
+ const result = this.serializeValue(serialized, segments, meta, maps, blobs);
246
+ meta.push([entry[0], ...segments]);
247
+ return result;
248
+ }
249
+ }
250
+ if (typeof data !== "object" || data === null) return data;
251
+ if (data instanceof Blob) {
252
+ maps.push(segments.slice());
253
+ blobs.push(data);
254
+ return data;
255
+ }
256
+ if (Array.isArray(data)) {
257
+ const json = [];
258
+ for (let i = 0; i < data.length; i++) {
259
+ segments.push(i);
260
+ json.push(this.serializeValue(data[i], segments, meta, maps, blobs));
261
+ segments.pop();
262
+ }
263
+ return json;
264
+ }
265
+ if (isPlainObject(data)) {
266
+ const json = new NullProtoObj();
267
+ for (const k of Object.keys(data)) {
268
+ const v = data[k];
269
+ /**
270
+ * Skip custom toJSON methods to avoid JSON.stringify invoking them,
271
+ * which could cause meta and serialized data mismatches during deserialization.
272
+ * Instead, rely on custom handlers.
273
+ */
274
+ if (k === "toJSON" && typeof v === "function") continue;
275
+ if (v === void 0 && this.omitUndefinedProperties) continue;
276
+ segments.push(k);
277
+ json[k] = this.serializeValue(v, segments, meta, maps, blobs);
278
+ segments.pop();
279
+ }
280
+ return json;
281
+ }
282
+ return data;
283
+ }
284
+ deserializeJson(serialized) {
285
+ const ref = { json: serialized.json };
286
+ if (serialized.blobs?.length) for (let i = 0; i < serialized.maps.length; i++) {
287
+ const blob = serialized.blobs[i];
288
+ if (!(blob instanceof Blob)) throw invalidSerializedData(`blob ${i} is not a Blob.`);
289
+ const segments = serialized.maps[i];
290
+ let original = serialized;
291
+ let currentRef = ref;
292
+ let preSegment = "json";
293
+ for (let j = 0; j < segments.length; j++) {
294
+ original = original[preSegment];
295
+ currentRef = walkInto(currentRef, preSegment, original);
296
+ preSegment = segments[j];
297
+ if (!Object.hasOwn(currentRef, preSegment)) throw invalidSerializedData(`segment "${preSegment}" does not exist.`);
298
+ }
299
+ currentRef[preSegment] = blob;
300
+ }
301
+ const meta = serialized.meta;
302
+ if (meta) {
303
+ let restored;
304
+ /**
305
+ * `[segment, container, original]` per step of the previous entry's walk, reused for the shared path prefix.
306
+ * Only containers above its target are kept, so none can be a value a handler restored.
307
+ */
308
+ const chain = meta.length === 1 ? void 0 : [];
309
+ let chainDepth = 0;
310
+ for (const item of meta) {
311
+ const handler = this.handlers[item[0]];
312
+ if (handler === void 0) continue;
313
+ const depth = item.length - 1;
314
+ const shared = Math.min(depth, chainDepth);
315
+ let d = 0;
316
+ let original = serialized;
317
+ let currentRef = ref;
318
+ let preSegment = "json";
319
+ if (chain !== void 0 && shared > 0) {
320
+ d = 1;
321
+ while (d < shared && chain[3 * d] === item[d]) d++;
322
+ currentRef = chain[3 * d - 2];
323
+ original = chain[3 * d - 1];
324
+ preSegment = item[d];
325
+ if (!Object.hasOwn(currentRef, preSegment)) throw invalidSerializedData(`segment "${preSegment}" does not exist.`);
326
+ }
327
+ while (d < depth) {
328
+ original = original[preSegment];
329
+ currentRef = walkInto(currentRef, preSegment, original, restored);
330
+ if (chain !== void 0) {
331
+ chain[3 * d] = preSegment;
332
+ chain[3 * d + 1] = currentRef;
333
+ chain[3 * d + 2] = original;
334
+ }
335
+ preSegment = item[++d];
336
+ if (!Object.hasOwn(currentRef, preSegment)) throw invalidSerializedData(`segment "${preSegment}" does not exist.`);
337
+ }
338
+ chainDepth = depth;
339
+ const value = handler.deserialize(currentRef[preSegment]);
340
+ currentRef[preSegment] = value;
341
+ if (isPlainObjectOrArray(value)) (restored ??= /* @__PURE__ */ new Set()).add(value);
342
+ }
343
+ }
344
+ return ref.json;
345
+ }
346
+ };
347
+ export { RPCJsonSerializer };
@@ -0,0 +1,31 @@
1
+ import { RPCJsonSerializer, RPCJsonSerializerOptions } from "./rpc-json-serializer.js";
2
+ import { StandardBody } from "@standard-server/core";
3
+ export interface RPCSerializerSerializeOptions {
4
+ /**
5
+ * Use FormData for serialization when nested blobs are present.
6
+ * Does not apply to root-level Blob values.
7
+ *
8
+ * @default true
9
+ */
10
+ useFormDataForBlobFields?: boolean | undefined;
11
+ }
12
+ export interface RPCSerializerOptions extends RPCJsonSerializerOptions {
13
+ /**
14
+ * Default options for serialize method
15
+ */
16
+ serialize?: RPCSerializerSerializeOptions | undefined;
17
+ }
18
+ /**
19
+ * Serializes and deserializes data for the RPC protocol,
20
+ * preserving native types like Date, BigInt, Set, and Map that plain JSON cannot represent.
21
+ *
22
+ * @see {@link https://orpc.dev/docs/rpc/serializer | RPC Serializer}
23
+ */
24
+ export declare class RPCSerializer extends RPCJsonSerializer {
25
+ private readonly defaultSerializeOptions;
26
+ constructor(options?: RPCSerializerOptions);
27
+ serialize(data: unknown, options?: RPCSerializerSerializeOptions): StandardBody;
28
+ private serializePayload;
29
+ deserialize(data: StandardBody): unknown;
30
+ private deserializePayload;
31
+ }
@@ -0,0 +1,102 @@
1
+ import { wrapAsyncIteratorPreservingEventMeta } from "./async-iterator-object.js";
2
+ import { createORPCErrorFromJson, isORPCErrorJson, toORPCError } from "./error-utils.js";
3
+ import { RPCJsonSerializer } from "./rpc-json-serializer.js";
4
+ import { NON_NEGATIVE_INTEGER_REGEX, isAsyncIteratorObject, isPlainObject, stringifyJSON } from "@orpc/shared";
5
+ import { EventStreamErrorEvent } from "@standard-server/core";
6
+ // src/rpc-serializer.ts
7
+ /**
8
+ * Serializes and deserializes data for the RPC protocol,
9
+ * preserving native types like Date, BigInt, Set, and Map that plain JSON cannot represent.
10
+ *
11
+ * @see {@link https://orpc.dev/docs/rpc/serializer | RPC Serializer}
12
+ */
13
+ var RPCSerializer = class extends RPCJsonSerializer {
14
+ defaultSerializeOptions;
15
+ constructor(options = {}) {
16
+ super(options);
17
+ this.defaultSerializeOptions = options.serialize;
18
+ }
19
+ serialize(data, options = {}) {
20
+ if (data === void 0 || data instanceof ReadableStream || data instanceof Blob) return data;
21
+ if (isAsyncIteratorObject(data)) return wrapAsyncIteratorPreservingEventMeta(data, {
22
+ mapResult: (result) => {
23
+ if (result.value === void 0) return result;
24
+ return {
25
+ done: result.done,
26
+ value: this.serializePayload(result.value, false)
27
+ };
28
+ },
29
+ mapError: (e) => new EventStreamErrorEvent(this.serializePayload(toORPCError(e).toJSON(), false), { cause: e })
30
+ });
31
+ const useFormDataForBlobs = options.useFormDataForBlobFields ?? this.defaultSerializeOptions?.useFormDataForBlobFields ?? true;
32
+ return this.serializePayload(data, useFormDataForBlobs);
33
+ }
34
+ serializePayload(data, useFormDataForBlobs) {
35
+ const { json, meta, maps, blobs } = this.serializeJson(data);
36
+ if (!useFormDataForBlobs || !blobs?.length) return {
37
+ json,
38
+ meta
39
+ };
40
+ const form = new FormData();
41
+ form.set("data", stringifyJSON({
42
+ json,
43
+ meta,
44
+ maps
45
+ }));
46
+ blobs.forEach((blob, i) => {
47
+ form.set(i.toString(), blob);
48
+ });
49
+ return form;
50
+ }
51
+ deserialize(data) {
52
+ if (data === void 0 || data instanceof ReadableStream || data instanceof Blob) return data;
53
+ if (isAsyncIteratorObject(data)) return wrapAsyncIteratorPreservingEventMeta(data, {
54
+ mapResult: (result) => {
55
+ if (result.value === void 0) return result;
56
+ return {
57
+ done: result.done,
58
+ value: this.deserializePayload(result.value)
59
+ };
60
+ },
61
+ mapError: (e) => {
62
+ if (!(e instanceof EventStreamErrorEvent) || e.data === void 0) return e;
63
+ let deserialized;
64
+ try {
65
+ deserialized = this.deserializePayload(e.data);
66
+ } catch {
67
+ return e;
68
+ }
69
+ if (isORPCErrorJson(deserialized)) return createORPCErrorFromJson(deserialized, { cause: e });
70
+ return new EventStreamErrorEvent(deserialized, { cause: e });
71
+ }
72
+ });
73
+ return this.deserializePayload(data);
74
+ }
75
+ deserializePayload(data) {
76
+ if (!(data instanceof FormData)) return this.deserializeJson(assertEnvelope(data, false));
77
+ let raw;
78
+ let hasBlobs = false;
79
+ const blobs = [];
80
+ for (const [key, value] of data) if (key === "data" && raw === void 0 && typeof value === "string") raw = value;
81
+ else if (value instanceof Blob && NON_NEGATIVE_INTEGER_REGEX.test(key)) {
82
+ blobs[Number(key)] = value;
83
+ hasBlobs = true;
84
+ } else throw invalidFormat();
85
+ const serialized = raw === void 0 ? { json: void 0 } : assertEnvelope(JSON.parse(raw), true);
86
+ if (hasBlobs && serialized.maps === void 0) throw invalidFormat();
87
+ return this.deserializeJson({
88
+ ...serialized,
89
+ blobs
90
+ });
91
+ }
92
+ };
93
+ function invalidFormat() {
94
+ return /* @__PURE__ */ new TypeError("Invalid RPC serialized data format.");
95
+ }
96
+ function assertEnvelope(value, allowMaps) {
97
+ if (!isPlainObject(value)) throw invalidFormat();
98
+ for (const key of Object.keys(value)) if (key !== "json" && key !== "meta" && (!allowMaps || key !== "maps")) throw invalidFormat();
99
+ if (value.meta !== void 0 && !Array.isArray(value.meta) || value.maps !== void 0 && !Array.isArray(value.maps)) throw invalidFormat();
100
+ return value;
101
+ }
102
+ export { RPCSerializer };
@@ -0,0 +1,85 @@
1
+ import { PromiseWithError } from "@orpc/shared";
2
+ export interface ClientContext {
3
+ [key: PropertyKey]: any;
4
+ }
5
+ export interface ClientOptions<T extends ClientContext> {
6
+ signal?: AbortSignal | undefined;
7
+ lastEventId?: string | undefined;
8
+ context: T;
9
+ }
10
+ export type FriendlyClientOptions<T extends ClientContext> = Omit<ClientOptions<T>, "context"> & (object extends T ? {
11
+ context?: T | undefined;
12
+ } : {
13
+ context: T;
14
+ });
15
+ export type ClientRest<TClientContext extends ClientContext, TInput> = object extends TClientContext ? undefined extends TInput ? [input?: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options?: FriendlyClientOptions<TClientContext>] : [input: TInput, options: FriendlyClientOptions<TClientContext>];
16
+ export interface Client<TClientContext extends ClientContext, TInput, TOutput, TError> {
17
+ (...rest: ClientRest<TClientContext, TInput>): PromiseWithError<TOutput, TError>;
18
+ }
19
+ export type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | {
20
+ [k: string]: NestedClient<TClientContext>;
21
+ };
22
+ export type AnyNestedClient = NestedClient<any>;
23
+ /**
24
+ * Infers the **client context type** required by a client.
25
+ *
26
+ * @see {@link https://orpc.dev/docs/client/client-side#infer-client-context | Client-Side Clients - Infer Client Context}
27
+ */
28
+ export type InferClientContext<T extends AnyNestedClient> = T extends NestedClient<infer U> ? U : never;
29
+ export interface ClientLink<TClientContext extends ClientContext> {
30
+ call: (path: string[], input: unknown, options: ClientOptions<TClientContext>) => Promise<unknown>;
31
+ }
32
+ /**
33
+ * Recursively infers the **input types** from a client.
34
+ *
35
+ * Produces a nested map where each endpoint's input type is preserved.
36
+ *
37
+ * @see {@link https://orpc.dev/docs/client/client-side#infer-client-inputs | Client-Side Clients - Infer Client Inputs}
38
+ */
39
+ export type InferClientInputs<T extends AnyNestedClient> = T extends Client<any, infer U, any, any> ? U : { [K in keyof T]: T[K] extends AnyNestedClient ? InferClientInputs<T[K]> : never; };
40
+ /**
41
+ * Recursively infers the **body input types** from a client.
42
+ *
43
+ * If an endpoint's input includes `{ body: ... }`, only the `body` portion is extracted.
44
+ * Produces a nested map of body input types.
45
+ *
46
+ * @see {@link https://orpc.dev/docs/client/client-side#infer-client-body-inputs | Client-Side Clients - Infer Client Body Inputs}
47
+ */
48
+ export type InferClientBodyInputs<T extends AnyNestedClient> = T extends Client<any, infer U, any, any> ? U extends {
49
+ body: infer UBody;
50
+ } ? UBody : U : { [K in keyof T]: T[K] extends AnyNestedClient ? InferClientBodyInputs<T[K]> : never; };
51
+ /**
52
+ * Recursively infers the **output types** from a client.
53
+ *
54
+ * Produces a nested map where each endpoint's output type is preserved.
55
+ *
56
+ * @see {@link https://orpc.dev/docs/client/client-side#infer-client-outputs | Client-Side Clients - Infer Client Outputs}
57
+ */
58
+ export type InferClientOutputs<T extends AnyNestedClient> = T extends Client<any, any, infer U, any> ? U : { [K in keyof T]: T[K] extends AnyNestedClient ? InferClientOutputs<T[K]> : never; };
59
+ /**
60
+ * Recursively infers the **body output types** from a client.
61
+ *
62
+ * If an endpoint's output includes `{ body: ... }`, only the `body` portion is extracted.
63
+ * Produces a nested map of body output types.
64
+ *
65
+ * @see {@link https://orpc.dev/docs/client/client-side#infer-client-body-outputs | Client-Side Clients - Infer Client Body Outputs}
66
+ */
67
+ export type InferClientBodyOutputs<T extends AnyNestedClient> = T extends Client<any, any, infer U, any> ? U extends {
68
+ body: infer UBody;
69
+ } ? UBody : U : { [K in keyof T]: T[K] extends AnyNestedClient ? InferClientBodyOutputs<T[K]> : never; };
70
+ /**
71
+ * Recursively infers the **error types** from a client when you use [type-safe errors](https://orpc.dev/docs/error-handling#typesafe-errors).
72
+ *
73
+ * Produces a nested map where each endpoint's error type is preserved.
74
+ *
75
+ * @see {@link https://orpc.dev/docs/client/client-side#infer-client-errors | Client-Side Clients - Infer Client Errors}
76
+ */
77
+ export type InferClientErrors<T extends AnyNestedClient> = T extends Client<any, any, any, infer U> ? U : { [K in keyof T]: T[K] extends AnyNestedClient ? InferClientErrors<T[K]> : never; };
78
+ /**
79
+ * Recursively infers a **union of all error types** from a client when you use [type-safe errors](https://orpc.dev/docs/error-handling#typesafe-errors).
80
+ *
81
+ * Useful when you want to handle all possible errors from any endpoint at once.
82
+ *
83
+ * @see {@link https://orpc.dev/docs/client/client-side#infer-client-error | Client-Side Clients - Infer Client Error}
84
+ */
85
+ export type InferClientError<T extends AnyNestedClient> = T extends Client<any, any, any, infer U> ? U : { [K in keyof T]: T[K] extends AnyNestedClient ? InferClientError<T[K]> : never; }[keyof T];
@@ -0,0 +1,36 @@
1
+ import { AnyORPCError } from "./error.js";
2
+ import { ClientContext, ClientOptions, ClientRest } from "./types.js";
3
+ import { PromiseWithError, ThrowableError } from "@orpc/shared";
4
+ export declare function resolveClientRest<TClientContext extends ClientContext, TInput>(rest: ClientRest<TClientContext, TInput>): [input: TInput, options: ClientOptions<TClientContext>];
5
+ export type SafeResult<TOutput, TError> = ([error: null, data: TOutput, definedError: null, isSuccess: true] & {
6
+ error: null;
7
+ data: TOutput;
8
+ definedError: null;
9
+ isSuccess: true;
10
+ }) | ([error: Exclude<TError, AnyORPCError>, data: undefined, definedError: null, isSuccess: false] & {
11
+ error: Exclude<TError, AnyORPCError>;
12
+ data: undefined;
13
+ definedError: null;
14
+ isSuccess: false;
15
+ }) | ([error: Extract<TError, AnyORPCError>, data: undefined, definedError: Extract<TError, AnyORPCError>, isSuccess: false] & {
16
+ error: Extract<TError, AnyORPCError>;
17
+ data: undefined;
18
+ definedError: Extract<TError, AnyORPCError>;
19
+ isSuccess: false;
20
+ });
21
+ /**
22
+ * Works like try/catch, but help you infer the error type if it is a defined ORPCError.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * const [error, data, definedError, isSuccess] = await safe(client(...))
27
+ * // or const { error, data, definedError, isSuccess } = await safe(client(...))
28
+ *
29
+ * if (definedError) {
30
+ * console.log(definedError) // or error, both are well typed
31
+ * }
32
+ * ```
33
+ *
34
+ * @see {@link https://orpc.dev/docs/client/error-handling#using-safe-and-isdefinederror | Client Error Handling - Using safe and isDefinedError}
35
+ */
36
+ export declare function safe<TOutput, TError = ThrowableError>(promise: PromiseWithError<TOutput, TError>): Promise<SafeResult<TOutput, TError>>;
package/dist/utils.js ADDED
@@ -0,0 +1,67 @@
1
+ import { isDefinedError } from "./error-utils.js";
2
+ // src/utils.ts
3
+ function resolveFriendlyClientOptions(options) {
4
+ return {
5
+ ...options,
6
+ context: options.context ?? {}
7
+ };
8
+ }
9
+ function resolveClientRest(rest) {
10
+ return [rest[0], resolveFriendlyClientOptions(rest[1] ?? {})];
11
+ }
12
+ /**
13
+ * Works like try/catch, but help you infer the error type if it is a defined ORPCError.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * const [error, data, definedError, isSuccess] = await safe(client(...))
18
+ * // or const { error, data, definedError, isSuccess } = await safe(client(...))
19
+ *
20
+ * if (definedError) {
21
+ * console.log(definedError) // or error, both are well typed
22
+ * }
23
+ * ```
24
+ *
25
+ * @see {@link https://orpc.dev/docs/client/error-handling#using-safe-and-isdefinederror | Client Error Handling - Using safe and isDefinedError}
26
+ */
27
+ async function safe(promise) {
28
+ try {
29
+ const output = await promise;
30
+ return Object.assign([
31
+ null,
32
+ output,
33
+ null,
34
+ true
35
+ ], {
36
+ error: null,
37
+ data: output,
38
+ definedError: null,
39
+ isSuccess: true
40
+ });
41
+ } catch (e) {
42
+ const error = e;
43
+ if (isDefinedError(error)) return Object.assign([
44
+ error,
45
+ void 0,
46
+ error,
47
+ false
48
+ ], {
49
+ error,
50
+ data: void 0,
51
+ definedError: error,
52
+ isSuccess: false
53
+ });
54
+ return Object.assign([
55
+ error,
56
+ void 0,
57
+ null,
58
+ false
59
+ ], {
60
+ error,
61
+ data: void 0,
62
+ definedError: null,
63
+ isSuccess: false
64
+ });
65
+ }
66
+ }
67
+ export { resolveClientRest, resolveFriendlyClientOptions, safe };