@orpc/client 0.0.0-next.c59d67c → 0.0.0-next.ca29a36
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 +88 -0
- package/dist/chunk-7F3XVLRJ.js +281 -0
- package/dist/chunk-FF5VXXNP.js +213 -0
- package/dist/fetch.js +127 -0
- package/dist/index.js +78 -71
- package/dist/openapi.js +232 -0
- package/dist/rpc.js +10 -0
- package/dist/src/adapters/fetch/index.d.ts +3 -0
- package/dist/src/adapters/fetch/rpc-link.d.ts +98 -0
- package/dist/src/adapters/fetch/types.d.ts +5 -0
- package/dist/src/client.d.ts +9 -0
- package/dist/src/dynamic-link.d.ts +12 -0
- package/dist/src/error.d.ts +106 -0
- package/dist/src/event-iterator-state.d.ts +9 -0
- package/dist/src/event-iterator.d.ts +12 -0
- package/dist/src/index.d.ts +7 -5
- package/dist/src/openapi/bracket-notation.d.ts +9 -0
- package/dist/src/openapi/index.d.ts +4 -0
- package/dist/src/openapi/json-serializer.d.ts +7 -0
- package/dist/src/openapi/serializer.d.ts +11 -0
- package/dist/src/rpc/index.d.ts +3 -0
- package/dist/src/rpc/json-serializer.d.ts +12 -0
- package/dist/src/rpc/serializer.d.ts +9 -0
- package/dist/src/types.d.ts +29 -0
- package/dist/src/utils.d.ts +17 -0
- package/package.json +21 -10
- package/dist/src/procedure.d.ts +0 -27
- package/dist/src/router.d.ts +0 -34
package/README.md
ADDED
@@ -0,0 +1,88 @@
|
|
1
|
+
<div align="center">
|
2
|
+
<image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 />
|
3
|
+
</div>
|
4
|
+
|
5
|
+
<h1></h1>
|
6
|
+
|
7
|
+
<div align="center">
|
8
|
+
<a href="https://codecov.io/gh/unnoq/orpc">
|
9
|
+
<img alt="codecov" src="https://codecov.io/gh/unnoq/orpc/branch/main/graph/badge.svg">
|
10
|
+
</a>
|
11
|
+
<a href="https://www.npmjs.com/package/@orpc/client">
|
12
|
+
<img alt="weekly downloads" src="https://img.shields.io/npm/dw/%40orpc%2Fclient?logo=npm" />
|
13
|
+
</a>
|
14
|
+
<a href="https://github.com/unnoq/orpc/blob/main/LICENSE">
|
15
|
+
<img alt="MIT License" src="https://img.shields.io/github/license/unnoq/orpc?logo=open-source-initiative" />
|
16
|
+
</a>
|
17
|
+
<a href="https://discord.gg/TXEbwRBvQn">
|
18
|
+
<img alt="Discord" src="https://img.shields.io/discord/1308966753044398161?color=7389D8&label&logo=discord&logoColor=ffffff" />
|
19
|
+
</a>
|
20
|
+
</div>
|
21
|
+
|
22
|
+
<h3 align="center">Typesafe APIs Made Simple 🪄</h3>
|
23
|
+
|
24
|
+
**oRPC is a powerful combination of RPC and OpenAPI**, makes it easy to build APIs that are end-to-end type-safe and adhere to OpenAPI standards, ensuring a smooth and enjoyable developer experience.
|
25
|
+
|
26
|
+
---
|
27
|
+
|
28
|
+
## Highlights
|
29
|
+
|
30
|
+
- **End-to-End Type Safety 🔒**: Ensure complete type safety from inputs to outputs and errors, bridging server and client seamlessly.
|
31
|
+
- **First-Class OpenAPI 📄**: Adheres to the OpenAPI standard out of the box, ensuring seamless integration and comprehensive API documentation.
|
32
|
+
- **Contract-First Development 📜**: (Optional) Define your API contract upfront and implement it with confidence.
|
33
|
+
- **Exceptional Developer Experience ✨**: Enjoy a streamlined workflow with robust typing and clear, in-code documentation.
|
34
|
+
- **Multi-Runtime Support 🌍**: Run your code seamlessly on Cloudflare, Deno, Bun, Node.js, and more.
|
35
|
+
- **Framework Integrations 🧩**: Supports Tanstack Query (React, Vue), Pinia Colada, and more.
|
36
|
+
- **Server Actions ⚡️**: Fully compatible with React Server Actions on Next.js, TanStack Start, and more.
|
37
|
+
- **Standard Schema Support 🗂️**: Effortlessly work with Zod, Valibot, ArkType, and others right out of the box.
|
38
|
+
- **Fast & Lightweight 💨**: Built on native APIs across all runtimes – optimized for speed and efficiency.
|
39
|
+
- **Native Types 📦**: Enjoy built-in support for Date, File, Blob, BigInt, URL and more with no extra setup.
|
40
|
+
- **Lazy Router ⏱️**: Improve cold start times with our lazy routing feature.
|
41
|
+
- **SSE & Streaming 📡**: Provides SSE and streaming features – perfect for real-time notifications and AI-powered streaming responses.
|
42
|
+
- **Reusability 🔄**: Write once and reuse your code across multiple purposes effortlessly.
|
43
|
+
- **Extendability 🔌**: Easily enhance oRPC with plugins, middleware, and interceptors.
|
44
|
+
- **Reliability 🛡️**: Well-tested, fully TypeScript, production-ready, and MIT licensed for peace of mind.
|
45
|
+
- **Simplicity 💡**: Enjoy straightforward, clean code with no hidden magic.
|
46
|
+
|
47
|
+
## Documentation
|
48
|
+
|
49
|
+
You can find the full documentation [here](https://orpc.unnoq.com).
|
50
|
+
|
51
|
+
## Packages
|
52
|
+
|
53
|
+
- [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
|
54
|
+
- [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
|
55
|
+
- [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
|
56
|
+
- [@orpc/react-query](https://www.npmjs.com/package/@orpc/react-query): Integration with [React Query](https://tanstack.com/query/latest/docs/framework/react/overview).
|
57
|
+
- [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
|
58
|
+
- [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
|
59
|
+
- [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
|
60
|
+
- [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
|
61
|
+
|
62
|
+
## `@orpc/client`
|
63
|
+
|
64
|
+
Consume your API on the client with type-safety. Read the [documentation](https://orpc.unnoq.com/docs/client/client-side) for more information.
|
65
|
+
|
66
|
+
```ts
|
67
|
+
import { createORPCClient } from '@orpc/client'
|
68
|
+
import { RPCLink } from '@orpc/client/fetch'
|
69
|
+
import { ContractRouterClient } from '@orpc/contract'
|
70
|
+
import { RouterClient } from '@orpc/server'
|
71
|
+
|
72
|
+
const link = new RPCLink({
|
73
|
+
url: 'http://localhost:3000/rpc',
|
74
|
+
headers: () => ({
|
75
|
+
authorization: 'Bearer token',
|
76
|
+
}),
|
77
|
+
// fetch: <-- provide fetch polyfill fetch if needed
|
78
|
+
})
|
79
|
+
|
80
|
+
// Create a client for your router
|
81
|
+
const client: RouterClient<typeof router> = createORPCClient(link)
|
82
|
+
// Or, create a client using a contract
|
83
|
+
const client: ContractRouterClient<typeof contract> = createORPCClient(link)
|
84
|
+
```
|
85
|
+
|
86
|
+
## License
|
87
|
+
|
88
|
+
Distributed under the MIT License. See [LICENSE](https://github.com/unnoq/orpc/blob/main/LICENSE) for more information.
|
@@ -0,0 +1,281 @@
|
|
1
|
+
// src/error.ts
|
2
|
+
import { isObject } from "@orpc/shared";
|
3
|
+
var COMMON_ORPC_ERROR_DEFS = {
|
4
|
+
BAD_REQUEST: {
|
5
|
+
status: 400,
|
6
|
+
message: "Bad Request"
|
7
|
+
},
|
8
|
+
UNAUTHORIZED: {
|
9
|
+
status: 401,
|
10
|
+
message: "Unauthorized"
|
11
|
+
},
|
12
|
+
FORBIDDEN: {
|
13
|
+
status: 403,
|
14
|
+
message: "Forbidden"
|
15
|
+
},
|
16
|
+
NOT_FOUND: {
|
17
|
+
status: 404,
|
18
|
+
message: "Not Found"
|
19
|
+
},
|
20
|
+
METHOD_NOT_SUPPORTED: {
|
21
|
+
status: 405,
|
22
|
+
message: "Method Not Supported"
|
23
|
+
},
|
24
|
+
NOT_ACCEPTABLE: {
|
25
|
+
status: 406,
|
26
|
+
message: "Not Acceptable"
|
27
|
+
},
|
28
|
+
TIMEOUT: {
|
29
|
+
status: 408,
|
30
|
+
message: "Request Timeout"
|
31
|
+
},
|
32
|
+
CONFLICT: {
|
33
|
+
status: 409,
|
34
|
+
message: "Conflict"
|
35
|
+
},
|
36
|
+
PRECONDITION_FAILED: {
|
37
|
+
status: 412,
|
38
|
+
message: "Precondition Failed"
|
39
|
+
},
|
40
|
+
PAYLOAD_TOO_LARGE: {
|
41
|
+
status: 413,
|
42
|
+
message: "Payload Too Large"
|
43
|
+
},
|
44
|
+
UNSUPPORTED_MEDIA_TYPE: {
|
45
|
+
status: 415,
|
46
|
+
message: "Unsupported Media Type"
|
47
|
+
},
|
48
|
+
UNPROCESSABLE_CONTENT: {
|
49
|
+
status: 422,
|
50
|
+
message: "Unprocessable Content"
|
51
|
+
},
|
52
|
+
TOO_MANY_REQUESTS: {
|
53
|
+
status: 429,
|
54
|
+
message: "Too Many Requests"
|
55
|
+
},
|
56
|
+
CLIENT_CLOSED_REQUEST: {
|
57
|
+
status: 499,
|
58
|
+
message: "Client Closed Request"
|
59
|
+
},
|
60
|
+
INTERNAL_SERVER_ERROR: {
|
61
|
+
status: 500,
|
62
|
+
message: "Internal Server Error"
|
63
|
+
},
|
64
|
+
NOT_IMPLEMENTED: {
|
65
|
+
status: 501,
|
66
|
+
message: "Not Implemented"
|
67
|
+
},
|
68
|
+
BAD_GATEWAY: {
|
69
|
+
status: 502,
|
70
|
+
message: "Bad Gateway"
|
71
|
+
},
|
72
|
+
SERVICE_UNAVAILABLE: {
|
73
|
+
status: 503,
|
74
|
+
message: "Service Unavailable"
|
75
|
+
},
|
76
|
+
GATEWAY_TIMEOUT: {
|
77
|
+
status: 504,
|
78
|
+
message: "Gateway Timeout"
|
79
|
+
}
|
80
|
+
};
|
81
|
+
function fallbackORPCErrorStatus(code, status) {
|
82
|
+
return status ?? COMMON_ORPC_ERROR_DEFS[code]?.status ?? 500;
|
83
|
+
}
|
84
|
+
function fallbackORPCErrorMessage(code, message) {
|
85
|
+
return message || COMMON_ORPC_ERROR_DEFS[code]?.message || code;
|
86
|
+
}
|
87
|
+
var ORPCError = class _ORPCError extends Error {
|
88
|
+
defined;
|
89
|
+
code;
|
90
|
+
status;
|
91
|
+
data;
|
92
|
+
constructor(code, ...[options]) {
|
93
|
+
if (options?.status && (options.status < 400 || options.status >= 600)) {
|
94
|
+
throw new Error("[ORPCError] The error status code must be in the 400-599 range.");
|
95
|
+
}
|
96
|
+
const message = fallbackORPCErrorMessage(code, options?.message);
|
97
|
+
super(message, options);
|
98
|
+
this.code = code;
|
99
|
+
this.status = fallbackORPCErrorStatus(code, options?.status);
|
100
|
+
this.defined = options?.defined ?? false;
|
101
|
+
this.data = options?.data;
|
102
|
+
}
|
103
|
+
toJSON() {
|
104
|
+
return {
|
105
|
+
defined: this.defined,
|
106
|
+
code: this.code,
|
107
|
+
status: this.status,
|
108
|
+
message: this.message,
|
109
|
+
data: this.data
|
110
|
+
};
|
111
|
+
}
|
112
|
+
static fromJSON(json, options) {
|
113
|
+
return new _ORPCError(json.code, {
|
114
|
+
...options,
|
115
|
+
...json
|
116
|
+
});
|
117
|
+
}
|
118
|
+
static isValidJSON(json) {
|
119
|
+
if (!isObject(json)) {
|
120
|
+
return false;
|
121
|
+
}
|
122
|
+
const validKeys = ["defined", "code", "status", "message", "data"];
|
123
|
+
if (Object.keys(json).some((k) => !validKeys.includes(k))) {
|
124
|
+
return false;
|
125
|
+
}
|
126
|
+
return "defined" in json && typeof json.defined === "boolean" && "code" in json && typeof json.code === "string" && "status" in json && typeof json.status === "number" && "message" in json && typeof json.message === "string";
|
127
|
+
}
|
128
|
+
};
|
129
|
+
function isDefinedError(error) {
|
130
|
+
return error instanceof ORPCError && error.defined;
|
131
|
+
}
|
132
|
+
function toORPCError(error) {
|
133
|
+
return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", {
|
134
|
+
message: "Internal server error",
|
135
|
+
cause: error
|
136
|
+
});
|
137
|
+
}
|
138
|
+
|
139
|
+
// src/event-iterator-state.ts
|
140
|
+
var iteratorStates = /* @__PURE__ */ new WeakMap();
|
141
|
+
function registerEventIteratorState(iterator, state) {
|
142
|
+
iteratorStates.set(iterator, state);
|
143
|
+
}
|
144
|
+
function updateEventIteratorStatus(state, status) {
|
145
|
+
if (state.status !== status) {
|
146
|
+
state.status = status;
|
147
|
+
state.listeners.forEach((cb) => cb(status));
|
148
|
+
}
|
149
|
+
}
|
150
|
+
function onEventIteratorStatusChange(iterator, callback, notifyImmediately = true) {
|
151
|
+
const state = iteratorStates.get(iterator);
|
152
|
+
if (!state) {
|
153
|
+
throw new Error("Iterator is not registered.");
|
154
|
+
}
|
155
|
+
if (notifyImmediately) {
|
156
|
+
callback(state.status);
|
157
|
+
}
|
158
|
+
state.listeners.push(callback);
|
159
|
+
return () => {
|
160
|
+
const index = state.listeners.indexOf(callback);
|
161
|
+
if (index !== -1) {
|
162
|
+
state.listeners.splice(index, 1);
|
163
|
+
}
|
164
|
+
};
|
165
|
+
}
|
166
|
+
|
167
|
+
// src/event-iterator.ts
|
168
|
+
import { isTypescriptObject, retry } from "@orpc/shared";
|
169
|
+
import { getEventMeta, withEventMeta } from "@orpc/standard-server";
|
170
|
+
function mapEventIterator(iterator, maps) {
|
171
|
+
return async function* () {
|
172
|
+
try {
|
173
|
+
while (true) {
|
174
|
+
const { done, value } = await iterator.next();
|
175
|
+
let mappedValue = await maps.value(value, done);
|
176
|
+
if (mappedValue !== value) {
|
177
|
+
const meta = getEventMeta(value);
|
178
|
+
if (meta && isTypescriptObject(mappedValue)) {
|
179
|
+
mappedValue = withEventMeta(mappedValue, meta);
|
180
|
+
}
|
181
|
+
}
|
182
|
+
if (done) {
|
183
|
+
return mappedValue;
|
184
|
+
}
|
185
|
+
yield mappedValue;
|
186
|
+
}
|
187
|
+
} catch (error) {
|
188
|
+
let mappedError = await maps.error(error);
|
189
|
+
if (mappedError !== error) {
|
190
|
+
const meta = getEventMeta(error);
|
191
|
+
if (meta && isTypescriptObject(mappedError)) {
|
192
|
+
mappedError = withEventMeta(mappedError, meta);
|
193
|
+
}
|
194
|
+
}
|
195
|
+
throw mappedError;
|
196
|
+
} finally {
|
197
|
+
await iterator.return?.();
|
198
|
+
}
|
199
|
+
}();
|
200
|
+
}
|
201
|
+
var MAX_ALLOWED_RETRY_TIMES = 99;
|
202
|
+
function createAutoRetryEventIterator(initial, reconnect, initialLastEventId) {
|
203
|
+
const state = {
|
204
|
+
status: "connected",
|
205
|
+
listeners: []
|
206
|
+
};
|
207
|
+
const iterator = async function* () {
|
208
|
+
let current = initial;
|
209
|
+
let lastEventId = initialLastEventId;
|
210
|
+
let lastRetry;
|
211
|
+
let retryTimes = 0;
|
212
|
+
try {
|
213
|
+
while (true) {
|
214
|
+
try {
|
215
|
+
updateEventIteratorStatus(state, "connected");
|
216
|
+
const { done, value } = await current.next();
|
217
|
+
const meta = getEventMeta(value);
|
218
|
+
lastEventId = meta?.id ?? lastEventId;
|
219
|
+
lastRetry = meta?.retry ?? lastRetry;
|
220
|
+
retryTimes = 0;
|
221
|
+
if (done) {
|
222
|
+
return value;
|
223
|
+
}
|
224
|
+
yield value;
|
225
|
+
} catch (e) {
|
226
|
+
updateEventIteratorStatus(state, "reconnecting");
|
227
|
+
const meta = getEventMeta(e);
|
228
|
+
lastEventId = meta?.id ?? lastEventId;
|
229
|
+
lastRetry = meta?.retry ?? lastRetry;
|
230
|
+
let currentError = e;
|
231
|
+
current = await retry({ times: MAX_ALLOWED_RETRY_TIMES }, async (exit) => {
|
232
|
+
retryTimes += 1;
|
233
|
+
if (retryTimes > MAX_ALLOWED_RETRY_TIMES) {
|
234
|
+
throw exit(new Error(
|
235
|
+
`Exceeded maximum retry attempts (${MAX_ALLOWED_RETRY_TIMES}) for event source. Possible infinite retry loop detected. Please review the retry logic.`,
|
236
|
+
{ cause: currentError }
|
237
|
+
));
|
238
|
+
}
|
239
|
+
const reconnected = await (async () => {
|
240
|
+
try {
|
241
|
+
return await reconnect({
|
242
|
+
lastRetry,
|
243
|
+
lastEventId,
|
244
|
+
retryTimes,
|
245
|
+
error: currentError
|
246
|
+
});
|
247
|
+
} catch (e2) {
|
248
|
+
currentError = e2;
|
249
|
+
throw e2;
|
250
|
+
}
|
251
|
+
})();
|
252
|
+
if (!reconnected) {
|
253
|
+
throw exit(currentError);
|
254
|
+
}
|
255
|
+
return reconnected;
|
256
|
+
});
|
257
|
+
}
|
258
|
+
}
|
259
|
+
} finally {
|
260
|
+
updateEventIteratorStatus(state, "closed");
|
261
|
+
await current.return?.();
|
262
|
+
}
|
263
|
+
}();
|
264
|
+
registerEventIteratorState(iterator, state);
|
265
|
+
return iterator;
|
266
|
+
}
|
267
|
+
|
268
|
+
export {
|
269
|
+
COMMON_ORPC_ERROR_DEFS,
|
270
|
+
fallbackORPCErrorStatus,
|
271
|
+
fallbackORPCErrorMessage,
|
272
|
+
ORPCError,
|
273
|
+
isDefinedError,
|
274
|
+
toORPCError,
|
275
|
+
registerEventIteratorState,
|
276
|
+
updateEventIteratorStatus,
|
277
|
+
onEventIteratorStatusChange,
|
278
|
+
mapEventIterator,
|
279
|
+
createAutoRetryEventIterator
|
280
|
+
};
|
281
|
+
//# sourceMappingURL=chunk-7F3XVLRJ.js.map
|
@@ -0,0 +1,213 @@
|
|
1
|
+
import {
|
2
|
+
ORPCError,
|
3
|
+
mapEventIterator,
|
4
|
+
toORPCError
|
5
|
+
} from "./chunk-7F3XVLRJ.js";
|
6
|
+
|
7
|
+
// src/rpc/json-serializer.ts
|
8
|
+
import { isObject } from "@orpc/shared";
|
9
|
+
var RPCJsonSerializer = class {
|
10
|
+
serialize(data, segments = [], meta = [], maps = [], blobs = []) {
|
11
|
+
if (data instanceof Blob) {
|
12
|
+
maps.push(segments);
|
13
|
+
blobs.push(data);
|
14
|
+
return [data, meta, maps, blobs];
|
15
|
+
}
|
16
|
+
if (typeof data === "bigint") {
|
17
|
+
meta.push([0, segments]);
|
18
|
+
return [data.toString(), meta, maps, blobs];
|
19
|
+
}
|
20
|
+
if (data instanceof Date) {
|
21
|
+
meta.push([1, segments]);
|
22
|
+
if (Number.isNaN(data.getTime())) {
|
23
|
+
return [null, meta, maps, blobs];
|
24
|
+
}
|
25
|
+
return [data.toISOString(), meta, maps, blobs];
|
26
|
+
}
|
27
|
+
if (Number.isNaN(data)) {
|
28
|
+
meta.push([2, segments]);
|
29
|
+
return [null, meta, maps, blobs];
|
30
|
+
}
|
31
|
+
if (data instanceof URL) {
|
32
|
+
meta.push([4, segments]);
|
33
|
+
return [data.toString(), meta, maps, blobs];
|
34
|
+
}
|
35
|
+
if (data instanceof RegExp) {
|
36
|
+
meta.push([5, segments]);
|
37
|
+
return [data.toString(), meta, maps, blobs];
|
38
|
+
}
|
39
|
+
if (data instanceof Set) {
|
40
|
+
const result = this.serialize(Array.from(data), segments, meta, maps, blobs);
|
41
|
+
meta.push([6, segments]);
|
42
|
+
return result;
|
43
|
+
}
|
44
|
+
if (data instanceof Map) {
|
45
|
+
const result = this.serialize(Array.from(data.entries()), segments, meta, maps, blobs);
|
46
|
+
meta.push([7, segments]);
|
47
|
+
return result;
|
48
|
+
}
|
49
|
+
if (Array.isArray(data)) {
|
50
|
+
const json = data.map((v, i) => {
|
51
|
+
if (v === void 0) {
|
52
|
+
meta.push([3, [...segments, i]]);
|
53
|
+
return v;
|
54
|
+
}
|
55
|
+
return this.serialize(v, [...segments, i], meta, maps, blobs)[0];
|
56
|
+
});
|
57
|
+
return [json, meta, maps, blobs];
|
58
|
+
}
|
59
|
+
if (isObject(data)) {
|
60
|
+
const json = {};
|
61
|
+
for (const k in data) {
|
62
|
+
json[k] = this.serialize(data[k], [...segments, k], meta, maps, blobs)[0];
|
63
|
+
}
|
64
|
+
return [json, meta, maps, blobs];
|
65
|
+
}
|
66
|
+
return [data, meta, maps, blobs];
|
67
|
+
}
|
68
|
+
deserialize(json, meta, maps, getBlob) {
|
69
|
+
const ref = { data: json };
|
70
|
+
if (maps && getBlob) {
|
71
|
+
maps.forEach((segments, i) => {
|
72
|
+
let currentRef = ref;
|
73
|
+
let preSegment = "data";
|
74
|
+
segments.forEach((segment) => {
|
75
|
+
currentRef = currentRef[preSegment];
|
76
|
+
preSegment = segment;
|
77
|
+
});
|
78
|
+
currentRef[preSegment] = getBlob(i);
|
79
|
+
});
|
80
|
+
}
|
81
|
+
for (const [type, segments] of meta) {
|
82
|
+
let currentRef = ref;
|
83
|
+
let preSegment = "data";
|
84
|
+
segments.forEach((segment) => {
|
85
|
+
currentRef = currentRef[preSegment];
|
86
|
+
preSegment = segment;
|
87
|
+
});
|
88
|
+
switch (type) {
|
89
|
+
case 0:
|
90
|
+
currentRef[preSegment] = BigInt(currentRef[preSegment]);
|
91
|
+
break;
|
92
|
+
case 1:
|
93
|
+
currentRef[preSegment] = new Date(currentRef[preSegment] ?? "Invalid Date");
|
94
|
+
break;
|
95
|
+
case 2:
|
96
|
+
currentRef[preSegment] = Number.NaN;
|
97
|
+
break;
|
98
|
+
case 3:
|
99
|
+
currentRef[preSegment] = void 0;
|
100
|
+
break;
|
101
|
+
case 4:
|
102
|
+
currentRef[preSegment] = new URL(currentRef[preSegment]);
|
103
|
+
break;
|
104
|
+
case 5: {
|
105
|
+
const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
|
106
|
+
currentRef[preSegment] = new RegExp(pattern, flags);
|
107
|
+
break;
|
108
|
+
}
|
109
|
+
case 6:
|
110
|
+
currentRef[preSegment] = new Set(currentRef[preSegment]);
|
111
|
+
break;
|
112
|
+
case 7:
|
113
|
+
currentRef[preSegment] = new Map(currentRef[preSegment]);
|
114
|
+
break;
|
115
|
+
/* v8 ignore next 3 */
|
116
|
+
default: {
|
117
|
+
const _expected = type;
|
118
|
+
}
|
119
|
+
}
|
120
|
+
}
|
121
|
+
return ref.data;
|
122
|
+
}
|
123
|
+
};
|
124
|
+
|
125
|
+
// src/rpc/serializer.ts
|
126
|
+
import { isAsyncIteratorObject, stringifyJSON } from "@orpc/shared";
|
127
|
+
import { ErrorEvent } from "@orpc/standard-server";
|
128
|
+
var RPCSerializer = class {
|
129
|
+
constructor(jsonSerializer = new RPCJsonSerializer()) {
|
130
|
+
this.jsonSerializer = jsonSerializer;
|
131
|
+
}
|
132
|
+
serialize(data) {
|
133
|
+
if (isAsyncIteratorObject(data)) {
|
134
|
+
return mapEventIterator(data, {
|
135
|
+
value: async (value) => this.#serialize(value, false),
|
136
|
+
error: async (e) => {
|
137
|
+
if (e instanceof ErrorEvent) {
|
138
|
+
return new ErrorEvent({
|
139
|
+
data: this.#serialize(e.data, false),
|
140
|
+
cause: e
|
141
|
+
});
|
142
|
+
}
|
143
|
+
return new ErrorEvent({
|
144
|
+
data: this.#serialize(toORPCError(e).toJSON(), false),
|
145
|
+
cause: e
|
146
|
+
});
|
147
|
+
}
|
148
|
+
});
|
149
|
+
}
|
150
|
+
return this.#serialize(data, true);
|
151
|
+
}
|
152
|
+
#serialize(data, enableFormData) {
|
153
|
+
if (data === void 0 || data instanceof Blob) {
|
154
|
+
return data;
|
155
|
+
}
|
156
|
+
const [json, meta_, maps, blobs] = this.jsonSerializer.serialize(data);
|
157
|
+
const meta = meta_.length === 0 ? void 0 : meta_;
|
158
|
+
if (!enableFormData || blobs.length === 0) {
|
159
|
+
return {
|
160
|
+
json,
|
161
|
+
meta
|
162
|
+
};
|
163
|
+
}
|
164
|
+
const form = new FormData();
|
165
|
+
form.set("data", stringifyJSON({ json, meta, maps }));
|
166
|
+
blobs.forEach((blob, i) => {
|
167
|
+
form.set(i.toString(), blob);
|
168
|
+
});
|
169
|
+
return form;
|
170
|
+
}
|
171
|
+
deserialize(data) {
|
172
|
+
if (isAsyncIteratorObject(data)) {
|
173
|
+
return mapEventIterator(data, {
|
174
|
+
value: async (value) => this.#deserialize(value),
|
175
|
+
error: async (e) => {
|
176
|
+
if (!(e instanceof ErrorEvent)) {
|
177
|
+
return e;
|
178
|
+
}
|
179
|
+
const deserialized = this.#deserialize(e.data);
|
180
|
+
if (ORPCError.isValidJSON(deserialized)) {
|
181
|
+
return ORPCError.fromJSON(deserialized, { cause: e });
|
182
|
+
}
|
183
|
+
return new ErrorEvent({
|
184
|
+
data: deserialized,
|
185
|
+
cause: e
|
186
|
+
});
|
187
|
+
}
|
188
|
+
});
|
189
|
+
}
|
190
|
+
return this.#deserialize(data);
|
191
|
+
}
|
192
|
+
#deserialize(data) {
|
193
|
+
if (data === void 0 || data instanceof Blob) {
|
194
|
+
return data;
|
195
|
+
}
|
196
|
+
if (!(data instanceof FormData)) {
|
197
|
+
return this.jsonSerializer.deserialize(data.json, data.meta ?? []);
|
198
|
+
}
|
199
|
+
const serialized = JSON.parse(data.get("data"));
|
200
|
+
return this.jsonSerializer.deserialize(
|
201
|
+
serialized.json,
|
202
|
+
serialized.meta ?? [],
|
203
|
+
serialized.maps,
|
204
|
+
(i) => data.get(i.toString())
|
205
|
+
);
|
206
|
+
}
|
207
|
+
};
|
208
|
+
|
209
|
+
export {
|
210
|
+
RPCJsonSerializer,
|
211
|
+
RPCSerializer
|
212
|
+
};
|
213
|
+
//# sourceMappingURL=chunk-FF5VXXNP.js.map
|
package/dist/fetch.js
ADDED
@@ -0,0 +1,127 @@
|
|
1
|
+
import {
|
2
|
+
RPCSerializer
|
3
|
+
} from "./chunk-FF5VXXNP.js";
|
4
|
+
import {
|
5
|
+
ORPCError,
|
6
|
+
createAutoRetryEventIterator
|
7
|
+
} from "./chunk-7F3XVLRJ.js";
|
8
|
+
|
9
|
+
// src/adapters/fetch/rpc-link.ts
|
10
|
+
import { isAsyncIteratorObject, stringifyJSON, trim, value } from "@orpc/shared";
|
11
|
+
import { toFetchBody, toStandardBody } from "@orpc/standard-server-fetch";
|
12
|
+
var InvalidEventSourceRetryResponse = class extends Error {
|
13
|
+
};
|
14
|
+
var RPCLink = class {
|
15
|
+
fetch;
|
16
|
+
rpcSerializer;
|
17
|
+
maxUrlLength;
|
18
|
+
fallbackMethod;
|
19
|
+
method;
|
20
|
+
headers;
|
21
|
+
url;
|
22
|
+
eventSourceMaxNumberOfRetries;
|
23
|
+
eventSourceRetryDelay;
|
24
|
+
eventSourceRetry;
|
25
|
+
constructor(options) {
|
26
|
+
this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
|
27
|
+
this.rpcSerializer = options.rpcSerializer ?? new RPCSerializer();
|
28
|
+
this.maxUrlLength = options.maxUrlLength ?? 2083;
|
29
|
+
this.fallbackMethod = options.fallbackMethod ?? "POST";
|
30
|
+
this.url = options.url;
|
31
|
+
this.eventSourceMaxNumberOfRetries = options.eventSourceMaxNumberOfRetries ?? 5;
|
32
|
+
this.method = options.method ?? this.fallbackMethod;
|
33
|
+
this.headers = options.headers ?? {};
|
34
|
+
this.eventSourceRetry = options.eventSourceRetry ?? true;
|
35
|
+
this.eventSourceRetryDelay = options.eventSourceRetryDelay ?? (({ retryTimes, lastRetry }) => lastRetry ?? 1e3 * 2 ** retryTimes);
|
36
|
+
}
|
37
|
+
async call(path, input, options) {
|
38
|
+
const output = await this.performCall(path, input, options);
|
39
|
+
if (!isAsyncIteratorObject(output)) {
|
40
|
+
return output;
|
41
|
+
}
|
42
|
+
return createAutoRetryEventIterator(output, async (reconnectOptions) => {
|
43
|
+
if (options.signal?.aborted || reconnectOptions.retryTimes > this.eventSourceMaxNumberOfRetries) {
|
44
|
+
return null;
|
45
|
+
}
|
46
|
+
if (!await value(this.eventSourceRetry, reconnectOptions, options, path, input)) {
|
47
|
+
return null;
|
48
|
+
}
|
49
|
+
const delay = await value(this.eventSourceRetryDelay, reconnectOptions, options, path, input);
|
50
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
51
|
+
const updatedOptions = { ...options, lastEventId: reconnectOptions.lastEventId };
|
52
|
+
const maybeIterator = await this.performCall(path, input, updatedOptions);
|
53
|
+
if (!isAsyncIteratorObject(maybeIterator)) {
|
54
|
+
throw new InvalidEventSourceRetryResponse("Invalid EventSource retry response");
|
55
|
+
}
|
56
|
+
return maybeIterator;
|
57
|
+
}, void 0);
|
58
|
+
}
|
59
|
+
async performCall(path, input, options) {
|
60
|
+
const encoded = await this.encodeRequest(path, input, options);
|
61
|
+
const fetchBody = toFetchBody(encoded.body, encoded.headers);
|
62
|
+
if (options.lastEventId !== void 0) {
|
63
|
+
encoded.headers.set("last-event-id", options.lastEventId);
|
64
|
+
}
|
65
|
+
const response = await this.fetch(encoded.url, {
|
66
|
+
method: encoded.method,
|
67
|
+
headers: encoded.headers,
|
68
|
+
body: fetchBody,
|
69
|
+
signal: options.signal
|
70
|
+
}, options, path, input);
|
71
|
+
const body = await toStandardBody(response);
|
72
|
+
const deserialized = (() => {
|
73
|
+
try {
|
74
|
+
return this.rpcSerializer.deserialize(body);
|
75
|
+
} catch (error) {
|
76
|
+
if (response.ok) {
|
77
|
+
throw new ORPCError("INTERNAL_SERVER_ERROR", {
|
78
|
+
message: "Invalid RPC response",
|
79
|
+
cause: error
|
80
|
+
});
|
81
|
+
}
|
82
|
+
throw new ORPCError(response.status.toString(), {
|
83
|
+
message: response.statusText
|
84
|
+
});
|
85
|
+
}
|
86
|
+
})();
|
87
|
+
if (!response.ok) {
|
88
|
+
if (ORPCError.isValidJSON(deserialized)) {
|
89
|
+
throw ORPCError.fromJSON(deserialized);
|
90
|
+
}
|
91
|
+
throw new ORPCError("INTERNAL_SERVER_ERROR", {
|
92
|
+
message: "Invalid RPC error response",
|
93
|
+
cause: deserialized
|
94
|
+
});
|
95
|
+
}
|
96
|
+
return deserialized;
|
97
|
+
}
|
98
|
+
async encodeRequest(path, input, options) {
|
99
|
+
const expectedMethod = await value(this.method, options, path, input);
|
100
|
+
const headers = new Headers(await value(this.headers, options, path, input));
|
101
|
+
const url = new URL(`${trim(this.url, "/")}/${path.map(encodeURIComponent).join("/")}`);
|
102
|
+
const serialized = this.rpcSerializer.serialize(input);
|
103
|
+
if (expectedMethod === "GET" && !(serialized instanceof FormData) && !(serialized instanceof Blob) && !isAsyncIteratorObject(serialized)) {
|
104
|
+
const getUrl = new URL(url);
|
105
|
+
getUrl.searchParams.append("data", stringifyJSON(serialized) ?? "");
|
106
|
+
if (getUrl.toString().length <= this.maxUrlLength) {
|
107
|
+
return {
|
108
|
+
body: void 0,
|
109
|
+
method: expectedMethod,
|
110
|
+
headers,
|
111
|
+
url: getUrl
|
112
|
+
};
|
113
|
+
}
|
114
|
+
}
|
115
|
+
return {
|
116
|
+
url,
|
117
|
+
method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod,
|
118
|
+
headers,
|
119
|
+
body: serialized
|
120
|
+
};
|
121
|
+
}
|
122
|
+
};
|
123
|
+
export {
|
124
|
+
InvalidEventSourceRetryResponse,
|
125
|
+
RPCLink
|
126
|
+
};
|
127
|
+
//# sourceMappingURL=fetch.js.map
|