@orpc/client 0.0.0-next.bf323bf → 0.0.0-next.c0088c7

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.
@@ -0,0 +1,265 @@
1
+ import { isObject, isTypescriptObject, retry } from '@orpc/shared';
2
+ import { getEventMeta, withEventMeta } from '@orpc/standard-server';
3
+
4
+ const COMMON_ORPC_ERROR_DEFS = {
5
+ BAD_REQUEST: {
6
+ status: 400,
7
+ message: "Bad Request"
8
+ },
9
+ UNAUTHORIZED: {
10
+ status: 401,
11
+ message: "Unauthorized"
12
+ },
13
+ FORBIDDEN: {
14
+ status: 403,
15
+ message: "Forbidden"
16
+ },
17
+ NOT_FOUND: {
18
+ status: 404,
19
+ message: "Not Found"
20
+ },
21
+ METHOD_NOT_SUPPORTED: {
22
+ status: 405,
23
+ message: "Method Not Supported"
24
+ },
25
+ NOT_ACCEPTABLE: {
26
+ status: 406,
27
+ message: "Not Acceptable"
28
+ },
29
+ TIMEOUT: {
30
+ status: 408,
31
+ message: "Request Timeout"
32
+ },
33
+ CONFLICT: {
34
+ status: 409,
35
+ message: "Conflict"
36
+ },
37
+ PRECONDITION_FAILED: {
38
+ status: 412,
39
+ message: "Precondition Failed"
40
+ },
41
+ PAYLOAD_TOO_LARGE: {
42
+ status: 413,
43
+ message: "Payload Too Large"
44
+ },
45
+ UNSUPPORTED_MEDIA_TYPE: {
46
+ status: 415,
47
+ message: "Unsupported Media Type"
48
+ },
49
+ UNPROCESSABLE_CONTENT: {
50
+ status: 422,
51
+ message: "Unprocessable Content"
52
+ },
53
+ TOO_MANY_REQUESTS: {
54
+ status: 429,
55
+ message: "Too Many Requests"
56
+ },
57
+ CLIENT_CLOSED_REQUEST: {
58
+ status: 499,
59
+ message: "Client Closed Request"
60
+ },
61
+ INTERNAL_SERVER_ERROR: {
62
+ status: 500,
63
+ message: "Internal Server Error"
64
+ },
65
+ NOT_IMPLEMENTED: {
66
+ status: 501,
67
+ message: "Not Implemented"
68
+ },
69
+ BAD_GATEWAY: {
70
+ status: 502,
71
+ message: "Bad Gateway"
72
+ },
73
+ SERVICE_UNAVAILABLE: {
74
+ status: 503,
75
+ message: "Service Unavailable"
76
+ },
77
+ GATEWAY_TIMEOUT: {
78
+ status: 504,
79
+ message: "Gateway Timeout"
80
+ }
81
+ };
82
+ function fallbackORPCErrorStatus(code, status) {
83
+ return status ?? COMMON_ORPC_ERROR_DEFS[code]?.status ?? 500;
84
+ }
85
+ function fallbackORPCErrorMessage(code, message) {
86
+ return message || COMMON_ORPC_ERROR_DEFS[code]?.message || code;
87
+ }
88
+ class ORPCError extends Error {
89
+ defined;
90
+ code;
91
+ status;
92
+ data;
93
+ constructor(code, ...[options]) {
94
+ if (options?.status && (options.status < 400 || options.status >= 600)) {
95
+ throw new Error("[ORPCError] The error status code must be in the 400-599 range.");
96
+ }
97
+ const message = fallbackORPCErrorMessage(code, options?.message);
98
+ super(message, options);
99
+ this.code = code;
100
+ this.status = fallbackORPCErrorStatus(code, options?.status);
101
+ this.defined = options?.defined ?? false;
102
+ this.data = options?.data;
103
+ }
104
+ toJSON() {
105
+ return {
106
+ defined: this.defined,
107
+ code: this.code,
108
+ status: this.status,
109
+ message: this.message,
110
+ data: this.data
111
+ };
112
+ }
113
+ static fromJSON(json, options) {
114
+ return new ORPCError(json.code, {
115
+ ...options,
116
+ ...json
117
+ });
118
+ }
119
+ static isValidJSON(json) {
120
+ if (!isObject(json)) {
121
+ return false;
122
+ }
123
+ const validKeys = ["defined", "code", "status", "message", "data"];
124
+ if (Object.keys(json).some((k) => !validKeys.includes(k))) {
125
+ return false;
126
+ }
127
+ 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";
128
+ }
129
+ }
130
+ function isDefinedError(error) {
131
+ return error instanceof ORPCError && error.defined;
132
+ }
133
+ function toORPCError(error) {
134
+ return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", {
135
+ message: "Internal server error",
136
+ cause: error
137
+ });
138
+ }
139
+
140
+ const 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
+ function mapEventIterator(iterator, maps) {
168
+ return async function* () {
169
+ try {
170
+ while (true) {
171
+ const { done, value } = await iterator.next();
172
+ let mappedValue = await maps.value(value, done);
173
+ if (mappedValue !== value) {
174
+ const meta = getEventMeta(value);
175
+ if (meta && isTypescriptObject(mappedValue)) {
176
+ mappedValue = withEventMeta(mappedValue, meta);
177
+ }
178
+ }
179
+ if (done) {
180
+ return mappedValue;
181
+ }
182
+ yield mappedValue;
183
+ }
184
+ } catch (error) {
185
+ let mappedError = await maps.error(error);
186
+ if (mappedError !== error) {
187
+ const meta = getEventMeta(error);
188
+ if (meta && isTypescriptObject(mappedError)) {
189
+ mappedError = withEventMeta(mappedError, meta);
190
+ }
191
+ }
192
+ throw mappedError;
193
+ } finally {
194
+ await iterator.return?.();
195
+ }
196
+ }();
197
+ }
198
+ const MAX_ALLOWED_RETRY_TIMES = 99;
199
+ function createAutoRetryEventIterator(initial, reconnect, initialLastEventId) {
200
+ const state = {
201
+ status: "connected",
202
+ listeners: []
203
+ };
204
+ const iterator = async function* () {
205
+ let current = initial;
206
+ let lastEventId = initialLastEventId;
207
+ let lastRetry;
208
+ let retryTimes = 0;
209
+ try {
210
+ while (true) {
211
+ try {
212
+ updateEventIteratorStatus(state, "connected");
213
+ const { done, value } = await current.next();
214
+ const meta = getEventMeta(value);
215
+ lastEventId = meta?.id ?? lastEventId;
216
+ lastRetry = meta?.retry ?? lastRetry;
217
+ retryTimes = 0;
218
+ if (done) {
219
+ return value;
220
+ }
221
+ yield value;
222
+ } catch (e) {
223
+ updateEventIteratorStatus(state, "reconnecting");
224
+ const meta = getEventMeta(e);
225
+ lastEventId = meta?.id ?? lastEventId;
226
+ lastRetry = meta?.retry ?? lastRetry;
227
+ let currentError = e;
228
+ current = await retry({ times: MAX_ALLOWED_RETRY_TIMES }, async (exit) => {
229
+ retryTimes += 1;
230
+ if (retryTimes > MAX_ALLOWED_RETRY_TIMES) {
231
+ throw exit(new Error(
232
+ `Exceeded maximum retry attempts (${MAX_ALLOWED_RETRY_TIMES}) for event iterator. Possible infinite retry loop detected. Please review the retry logic.`,
233
+ { cause: currentError }
234
+ ));
235
+ }
236
+ const reconnected = await (async () => {
237
+ try {
238
+ return await reconnect({
239
+ lastRetry,
240
+ lastEventId,
241
+ retryTimes,
242
+ error: currentError
243
+ });
244
+ } catch (e2) {
245
+ currentError = e2;
246
+ throw e2;
247
+ }
248
+ })();
249
+ if (!reconnected) {
250
+ throw exit(currentError);
251
+ }
252
+ return reconnected;
253
+ });
254
+ }
255
+ }
256
+ } finally {
257
+ updateEventIteratorStatus(state, "closed");
258
+ await current.return?.();
259
+ }
260
+ }();
261
+ registerEventIteratorState(iterator, state);
262
+ return iterator;
263
+ }
264
+
265
+ export { COMMON_ORPC_ERROR_DEFS as C, ORPCError as O, fallbackORPCErrorMessage as a, createAutoRetryEventIterator as c, fallbackORPCErrorStatus as f, isDefinedError as i, mapEventIterator as m, onEventIteratorStatusChange as o, registerEventIteratorState as r, toORPCError as t, updateEventIteratorStatus as u };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/client",
3
3
  "type": "module",
4
- "version": "0.0.0-next.bf323bf",
4
+ "version": "0.0.0-next.c0088c7",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -15,37 +15,34 @@
15
15
  ],
16
16
  "exports": {
17
17
  ".": {
18
- "types": "./dist/src/index.d.ts",
19
- "import": "./dist/index.js",
20
- "default": "./dist/index.js"
18
+ "types": "./dist/index.d.mts",
19
+ "import": "./dist/index.mjs",
20
+ "default": "./dist/index.mjs"
21
21
  },
22
- "./fetch": {
23
- "types": "./dist/src/adapters/fetch/index.d.ts",
24
- "import": "./dist/fetch.js",
25
- "default": "./dist/fetch.js"
22
+ "./standard": {
23
+ "types": "./dist/adapters/standard/index.d.mts",
24
+ "import": "./dist/adapters/standard/index.mjs",
25
+ "default": "./dist/adapters/standard/index.mjs"
26
26
  },
27
- "./🔒/*": {
28
- "types": "./dist/src/*.d.ts"
27
+ "./fetch": {
28
+ "types": "./dist/adapters/fetch/index.d.mts",
29
+ "import": "./dist/adapters/fetch/index.mjs",
30
+ "default": "./dist/adapters/fetch/index.mjs"
29
31
  }
30
32
  },
31
33
  "files": [
32
- "!**/*.map",
33
- "!**/*.tsbuildinfo",
34
34
  "dist"
35
35
  ],
36
36
  "dependencies": {
37
- "@orpc/server-standard": "^0.4.0",
38
- "@orpc/server-standard-fetch": "^0.4.0",
39
- "@orpc/server": "0.0.0-next.bf323bf",
40
- "@orpc/contract": "0.0.0-next.bf323bf",
41
- "@orpc/shared": "0.0.0-next.bf323bf"
37
+ "@orpc/shared": "0.0.0-next.c0088c7",
38
+ "@orpc/standard-server": "0.0.0-next.c0088c7",
39
+ "@orpc/standard-server-fetch": "0.0.0-next.c0088c7"
42
40
  },
43
41
  "devDependencies": {
44
- "zod": "^3.24.1",
45
- "@orpc/openapi": "0.0.0-next.bf323bf"
42
+ "zod": "^3.24.2"
46
43
  },
47
44
  "scripts": {
48
- "build": "tsup --onSuccess='tsc -b --noCheck'",
45
+ "build": "unbuild",
49
46
  "build:watch": "pnpm run build --watch",
50
47
  "type:check": "tsc -b"
51
48
  }
@@ -1,105 +0,0 @@
1
- // src/event-iterator-state.ts
2
- var iteratorStates = /* @__PURE__ */ new WeakMap();
3
- function registerEventIteratorState(iterator, state) {
4
- iteratorStates.set(iterator, state);
5
- }
6
- function updateEventIteratorStatus(state, status) {
7
- if (state.status !== status) {
8
- state.status = status;
9
- state.listeners.forEach((cb) => cb(status));
10
- }
11
- }
12
- function onEventIteratorStatusChange(iterator, callback, notifyImmediately = true) {
13
- const state = iteratorStates.get(iterator);
14
- if (!state) {
15
- throw new Error("Iterator is not registered.");
16
- }
17
- if (notifyImmediately) {
18
- callback(state.status);
19
- }
20
- state.listeners.push(callback);
21
- return () => {
22
- const index = state.listeners.indexOf(callback);
23
- if (index !== -1) {
24
- state.listeners.splice(index, 1);
25
- }
26
- };
27
- }
28
-
29
- // src/event-iterator.ts
30
- import { getEventMeta } from "@orpc/server-standard";
31
- import { retry } from "@orpc/shared";
32
- var MAX_ALLOWED_RETRY_TIMES = 99;
33
- function createAutoRetryEventIterator(initial, reconnect, initialLastEventId) {
34
- const state = {
35
- status: "connected",
36
- listeners: []
37
- };
38
- const iterator = async function* () {
39
- let current = initial;
40
- let lastEventId = initialLastEventId;
41
- let lastRetry;
42
- let retryTimes = 0;
43
- try {
44
- while (true) {
45
- try {
46
- updateEventIteratorStatus(state, "connected");
47
- const { done, value } = await current.next();
48
- const meta = getEventMeta(value);
49
- lastEventId = meta?.id ?? lastEventId;
50
- lastRetry = meta?.retry ?? lastRetry;
51
- retryTimes = 0;
52
- if (done) {
53
- return value;
54
- }
55
- yield value;
56
- } catch (e) {
57
- updateEventIteratorStatus(state, "reconnecting");
58
- const meta = getEventMeta(e);
59
- lastEventId = meta?.id ?? lastEventId;
60
- lastRetry = meta?.retry ?? lastRetry;
61
- let currentError = e;
62
- current = await retry({ times: MAX_ALLOWED_RETRY_TIMES }, async (exit) => {
63
- retryTimes += 1;
64
- if (retryTimes > MAX_ALLOWED_RETRY_TIMES) {
65
- throw exit(new Error(
66
- `Exceeded maximum retry attempts (${MAX_ALLOWED_RETRY_TIMES}) for event source. Possible infinite retry loop detected. Please review the retry logic.`,
67
- { cause: currentError }
68
- ));
69
- }
70
- const reconnected = await (async () => {
71
- try {
72
- return await reconnect({
73
- lastRetry,
74
- lastEventId,
75
- retryTimes,
76
- error: currentError
77
- });
78
- } catch (e2) {
79
- currentError = e2;
80
- throw e2;
81
- }
82
- })();
83
- if (!reconnected) {
84
- throw exit(currentError);
85
- }
86
- return reconnected;
87
- });
88
- }
89
- }
90
- } finally {
91
- updateEventIteratorStatus(state, "closed");
92
- await current.return?.();
93
- }
94
- }();
95
- registerEventIteratorState(iterator, state);
96
- return iterator;
97
- }
98
-
99
- export {
100
- registerEventIteratorState,
101
- updateEventIteratorStatus,
102
- onEventIteratorStatusChange,
103
- createAutoRetryEventIterator
104
- };
105
- //# sourceMappingURL=chunk-HYT35LXG.js.map
package/dist/fetch.js DELETED
@@ -1,126 +0,0 @@
1
- import {
2
- createAutoRetryEventIterator
3
- } from "./chunk-HYT35LXG.js";
4
-
5
- // src/adapters/fetch/orpc-link.ts
6
- import { ORPCError } from "@orpc/contract";
7
- import { isAsyncIteratorObject } from "@orpc/server-standard";
8
- import { toFetchBody, toStandardBody } from "@orpc/server-standard-fetch";
9
- import { RPCSerializer } from "@orpc/server/standard";
10
- import { trim, value } from "@orpc/shared";
11
- var InvalidEventSourceRetryResponse = class extends Error {
12
- };
13
- var RPCLink = class {
14
- fetch;
15
- rpcSerializer;
16
- maxUrlLength;
17
- fallbackMethod;
18
- method;
19
- headers;
20
- url;
21
- eventSourceMaxNumberOfRetries;
22
- eventSourceRetryDelay;
23
- eventSourceRetry;
24
- constructor(options) {
25
- this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
26
- this.rpcSerializer = options.rpcSerializer ?? new RPCSerializer();
27
- this.maxUrlLength = options.maxUrlLength ?? 2083;
28
- this.fallbackMethod = options.fallbackMethod ?? "POST";
29
- this.url = options.url;
30
- this.eventSourceMaxNumberOfRetries = options.eventSourceMaxNumberOfRetries ?? 5;
31
- this.method = options.method ?? this.fallbackMethod;
32
- this.headers = options.headers ?? {};
33
- this.eventSourceRetry = options.eventSourceRetry ?? true;
34
- this.eventSourceRetryDelay = options.eventSourceRetryDelay ?? (({ retryTimes, lastRetry }) => lastRetry ?? 1e3 * 2 ** retryTimes);
35
- }
36
- async call(path, input, options) {
37
- const output = await this.performCall(path, input, options);
38
- if (!isAsyncIteratorObject(output)) {
39
- return output;
40
- }
41
- return createAutoRetryEventIterator(output, async (reconnectOptions) => {
42
- if (options.signal?.aborted || reconnectOptions.retryTimes > this.eventSourceMaxNumberOfRetries) {
43
- return null;
44
- }
45
- if (!await value(this.eventSourceRetry, reconnectOptions, options, path, input)) {
46
- return null;
47
- }
48
- const delay = await value(this.eventSourceRetryDelay, reconnectOptions, options, path, input);
49
- await new Promise((resolve) => setTimeout(resolve, delay));
50
- const updatedOptions = { ...options, lastEventId: reconnectOptions.lastEventId };
51
- const maybeIterator = await this.performCall(path, input, updatedOptions);
52
- if (!isAsyncIteratorObject(maybeIterator)) {
53
- throw new InvalidEventSourceRetryResponse("Invalid EventSource retry response");
54
- }
55
- return maybeIterator;
56
- }, void 0);
57
- }
58
- async performCall(path, input, options) {
59
- const encoded = await this.encodeRequest(path, input, options);
60
- const fetchBody = toFetchBody(encoded.body, encoded.headers);
61
- if (options.lastEventId !== void 0) {
62
- encoded.headers.set("last-event-id", options.lastEventId);
63
- }
64
- const response = await this.fetch(encoded.url, {
65
- method: encoded.method,
66
- headers: encoded.headers,
67
- body: fetchBody,
68
- signal: options.signal
69
- }, options, path, input);
70
- const body = await toStandardBody(response);
71
- const deserialized = (() => {
72
- try {
73
- return this.rpcSerializer.deserialize(body);
74
- } catch (error) {
75
- if (response.ok) {
76
- throw new ORPCError("INTERNAL_SERVER_ERROR", {
77
- message: "Invalid RPC response",
78
- cause: error
79
- });
80
- }
81
- throw new ORPCError(response.status.toString(), {
82
- message: response.statusText
83
- });
84
- }
85
- })();
86
- if (!response.ok) {
87
- if (ORPCError.isValidJSON(deserialized)) {
88
- throw ORPCError.fromJSON(deserialized);
89
- }
90
- throw new ORPCError("INTERNAL_SERVER_ERROR", {
91
- message: "Invalid RPC error response",
92
- cause: deserialized
93
- });
94
- }
95
- return deserialized;
96
- }
97
- async encodeRequest(path, input, options) {
98
- const expectedMethod = await value(this.method, options, path, input);
99
- const headers = new Headers(await value(this.headers, options, path, input));
100
- const url = new URL(`${trim(this.url, "/")}/${path.map(encodeURIComponent).join("/")}`);
101
- const serialized = this.rpcSerializer.serialize(input);
102
- if (expectedMethod === "GET" && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
103
- const getUrl = new URL(url);
104
- getUrl.searchParams.append("data", JSON.stringify(serialized));
105
- if (getUrl.toString().length <= this.maxUrlLength) {
106
- return {
107
- body: void 0,
108
- method: expectedMethod,
109
- headers,
110
- url: getUrl
111
- };
112
- }
113
- }
114
- return {
115
- url,
116
- method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod,
117
- headers,
118
- body: serialized
119
- };
120
- }
121
- };
122
- export {
123
- InvalidEventSourceRetryResponse,
124
- RPCLink
125
- };
126
- //# sourceMappingURL=fetch.js.map
package/dist/index.js DELETED
@@ -1,58 +0,0 @@
1
- import {
2
- createAutoRetryEventIterator,
3
- onEventIteratorStatusChange,
4
- registerEventIteratorState,
5
- updateEventIteratorStatus
6
- } from "./chunk-HYT35LXG.js";
7
-
8
- // src/client.ts
9
- function createORPCClient(link, options) {
10
- const path = options?.path ?? [];
11
- const procedureClient = async (...[input, options2]) => {
12
- const optionsOut = {
13
- ...options2,
14
- context: options2?.context ?? {}
15
- // options.context can be undefined when all field is optional
16
- };
17
- return await link.call(path, input, optionsOut);
18
- };
19
- const recursive = new Proxy(procedureClient, {
20
- get(target, key) {
21
- if (typeof key !== "string") {
22
- return Reflect.get(target, key);
23
- }
24
- return createORPCClient(link, {
25
- ...options,
26
- path: [...path, key]
27
- });
28
- }
29
- });
30
- return recursive;
31
- }
32
-
33
- // src/dynamic-link.ts
34
- var DynamicLink = class {
35
- constructor(linkResolver) {
36
- this.linkResolver = linkResolver;
37
- }
38
- async call(path, input, options) {
39
- const resolvedLink = await this.linkResolver(options, path, input);
40
- const output = await resolvedLink.call(path, input, options);
41
- return output;
42
- }
43
- };
44
-
45
- // src/index.ts
46
- import { isDefinedError, ORPCError, safe } from "@orpc/contract";
47
- export {
48
- DynamicLink,
49
- ORPCError,
50
- createAutoRetryEventIterator,
51
- createORPCClient,
52
- isDefinedError,
53
- onEventIteratorStatusChange,
54
- registerEventIteratorState,
55
- safe,
56
- updateEventIteratorStatus
57
- };
58
- //# sourceMappingURL=index.js.map
@@ -1,3 +0,0 @@
1
- export * from './orpc-link';
2
- export * from './types';
3
- //# sourceMappingURL=index.d.ts.map