@orpc/client 0.0.0-next.3cb80cf → 0.0.0-next.3ee2e95

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 (45) hide show
  1. package/README.md +101 -0
  2. package/dist/adapters/fetch/index.d.mts +26 -0
  3. package/dist/adapters/fetch/index.d.ts +26 -0
  4. package/dist/adapters/fetch/index.mjs +32 -0
  5. package/dist/adapters/standard/index.d.mts +10 -0
  6. package/dist/adapters/standard/index.d.ts +10 -0
  7. package/dist/adapters/standard/index.mjs +4 -0
  8. package/dist/index.d.mts +155 -0
  9. package/dist/index.d.ts +155 -0
  10. package/dist/index.mjs +65 -0
  11. package/dist/plugins/index.d.mts +143 -0
  12. package/dist/plugins/index.d.ts +143 -0
  13. package/dist/plugins/index.mjs +290 -0
  14. package/dist/shared/client.2CWETx1V.d.mts +47 -0
  15. package/dist/shared/client.BCCZFC-T.d.ts +87 -0
  16. package/dist/shared/client.CRWEpqLB.mjs +175 -0
  17. package/dist/shared/client.CipPQkhk.d.mts +29 -0
  18. package/dist/shared/client.CipPQkhk.d.ts +29 -0
  19. package/dist/shared/client.DUjXqpDq.d.ts +47 -0
  20. package/dist/shared/client.DcDnlyRo.d.mts +87 -0
  21. package/dist/shared/client.vy3P78P6.mjs +348 -0
  22. package/package.json +20 -25
  23. package/dist/chunk-2UPNYYFF.js +0 -288
  24. package/dist/chunk-TPEMQB7D.js +0 -178
  25. package/dist/fetch.js +0 -128
  26. package/dist/index.js +0 -81
  27. package/dist/openapi.js +0 -329
  28. package/dist/rpc.js +0 -10
  29. package/dist/src/adapters/fetch/index.d.ts +0 -3
  30. package/dist/src/adapters/fetch/rpc-link.d.ts +0 -98
  31. package/dist/src/adapters/fetch/types.d.ts +0 -5
  32. package/dist/src/client.d.ts +0 -9
  33. package/dist/src/dynamic-link.d.ts +0 -12
  34. package/dist/src/error.d.ts +0 -106
  35. package/dist/src/event-iterator-state.d.ts +0 -9
  36. package/dist/src/event-iterator.d.ts +0 -12
  37. package/dist/src/index.d.ts +0 -9
  38. package/dist/src/openapi/bracket-notation.d.ts +0 -84
  39. package/dist/src/openapi/index.d.ts +0 -4
  40. package/dist/src/openapi/json-serializer.d.ts +0 -5
  41. package/dist/src/openapi/serializer.d.ts +0 -11
  42. package/dist/src/rpc/index.d.ts +0 -2
  43. package/dist/src/rpc/serializer.d.ts +0 -22
  44. package/dist/src/types.d.ts +0 -29
  45. package/dist/src/utils.d.ts +0 -5
@@ -0,0 +1,348 @@
1
+ import { toArray, intercept, isObject, value, isAsyncIteratorObject, stringifyJSON } from '@orpc/shared';
2
+ import { mergeStandardHeaders, ErrorEvent } from '@orpc/standard-server';
3
+ import { C as COMMON_ORPC_ERROR_DEFS, b as isORPCErrorStatus, c as isORPCErrorJson, d as createORPCErrorFromJson, O as ORPCError, m as mapEventIterator, t as toORPCError } from './client.CRWEpqLB.mjs';
4
+
5
+ class CompositeStandardLinkPlugin {
6
+ plugins;
7
+ constructor(plugins = []) {
8
+ this.plugins = [...plugins].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
9
+ }
10
+ init(options) {
11
+ for (const plugin of this.plugins) {
12
+ plugin.init?.(options);
13
+ }
14
+ }
15
+ }
16
+
17
+ class InvalidEventIteratorRetryResponse extends Error {
18
+ }
19
+ class StandardLink {
20
+ constructor(codec, sender, options = {}) {
21
+ this.codec = codec;
22
+ this.sender = sender;
23
+ const plugin = new CompositeStandardLinkPlugin(options.plugins);
24
+ plugin.init(options);
25
+ this.interceptors = toArray(options.interceptors);
26
+ this.clientInterceptors = toArray(options.clientInterceptors);
27
+ }
28
+ interceptors;
29
+ clientInterceptors;
30
+ call(path, input, options) {
31
+ return intercept(this.interceptors, { ...options, path, input }, async ({ path: path2, input: input2, ...options2 }) => {
32
+ const output = await this.#call(path2, input2, options2);
33
+ return output;
34
+ });
35
+ }
36
+ async #call(path, input, options) {
37
+ const request = await this.codec.encode(path, input, options);
38
+ const response = await intercept(
39
+ this.clientInterceptors,
40
+ { ...options, input, path, request },
41
+ ({ input: input2, path: path2, request: request2, ...options2 }) => this.sender.call(request2, options2, path2, input2)
42
+ );
43
+ const output = await this.codec.decode(response, options, path, input);
44
+ return output;
45
+ }
46
+ }
47
+
48
+ const STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES = {
49
+ BIGINT: 0,
50
+ DATE: 1,
51
+ NAN: 2,
52
+ UNDEFINED: 3,
53
+ URL: 4,
54
+ REGEXP: 5,
55
+ SET: 6,
56
+ MAP: 7
57
+ };
58
+ class StandardRPCJsonSerializer {
59
+ customSerializers;
60
+ constructor(options = {}) {
61
+ this.customSerializers = options.customJsonSerializers ?? [];
62
+ if (this.customSerializers.length !== new Set(this.customSerializers.map((custom) => custom.type)).size) {
63
+ throw new Error("Custom serializer type must be unique.");
64
+ }
65
+ }
66
+ serialize(data, segments = [], meta = [], maps = [], blobs = []) {
67
+ for (const custom of this.customSerializers) {
68
+ if (custom.condition(data)) {
69
+ const result = this.serialize(custom.serialize(data), segments, meta, maps, blobs);
70
+ meta.push([custom.type, ...segments]);
71
+ return result;
72
+ }
73
+ }
74
+ if (data instanceof Blob) {
75
+ maps.push(segments);
76
+ blobs.push(data);
77
+ return [data, meta, maps, blobs];
78
+ }
79
+ if (typeof data === "bigint") {
80
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT, ...segments]);
81
+ return [data.toString(), meta, maps, blobs];
82
+ }
83
+ if (data instanceof Date) {
84
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE, ...segments]);
85
+ if (Number.isNaN(data.getTime())) {
86
+ return [null, meta, maps, blobs];
87
+ }
88
+ return [data.toISOString(), meta, maps, blobs];
89
+ }
90
+ if (Number.isNaN(data)) {
91
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN, ...segments]);
92
+ return [null, meta, maps, blobs];
93
+ }
94
+ if (data instanceof URL) {
95
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL, ...segments]);
96
+ return [data.toString(), meta, maps, blobs];
97
+ }
98
+ if (data instanceof RegExp) {
99
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP, ...segments]);
100
+ return [data.toString(), meta, maps, blobs];
101
+ }
102
+ if (data instanceof Set) {
103
+ const result = this.serialize(Array.from(data), segments, meta, maps, blobs);
104
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET, ...segments]);
105
+ return result;
106
+ }
107
+ if (data instanceof Map) {
108
+ const result = this.serialize(Array.from(data.entries()), segments, meta, maps, blobs);
109
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP, ...segments]);
110
+ return result;
111
+ }
112
+ if (Array.isArray(data)) {
113
+ const json = data.map((v, i) => {
114
+ if (v === void 0) {
115
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED, ...segments, i]);
116
+ return v;
117
+ }
118
+ return this.serialize(v, [...segments, i], meta, maps, blobs)[0];
119
+ });
120
+ return [json, meta, maps, blobs];
121
+ }
122
+ if (isObject(data)) {
123
+ const json = {};
124
+ for (const k in data) {
125
+ if (k === "toJSON" && typeof data[k] === "function") {
126
+ continue;
127
+ }
128
+ json[k] = this.serialize(data[k], [...segments, k], meta, maps, blobs)[0];
129
+ }
130
+ return [json, meta, maps, blobs];
131
+ }
132
+ return [data, meta, maps, blobs];
133
+ }
134
+ deserialize(json, meta, maps, getBlob) {
135
+ const ref = { data: json };
136
+ if (maps && getBlob) {
137
+ maps.forEach((segments, i) => {
138
+ let currentRef = ref;
139
+ let preSegment = "data";
140
+ segments.forEach((segment) => {
141
+ currentRef = currentRef[preSegment];
142
+ preSegment = segment;
143
+ });
144
+ currentRef[preSegment] = getBlob(i);
145
+ });
146
+ }
147
+ for (const item of meta) {
148
+ const type = item[0];
149
+ let currentRef = ref;
150
+ let preSegment = "data";
151
+ for (let i = 1; i < item.length; i++) {
152
+ currentRef = currentRef[preSegment];
153
+ preSegment = item[i];
154
+ }
155
+ for (const custom of this.customSerializers) {
156
+ if (custom.type === type) {
157
+ currentRef[preSegment] = custom.deserialize(currentRef[preSegment]);
158
+ break;
159
+ }
160
+ }
161
+ switch (type) {
162
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT:
163
+ currentRef[preSegment] = BigInt(currentRef[preSegment]);
164
+ break;
165
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE:
166
+ currentRef[preSegment] = new Date(currentRef[preSegment] ?? "Invalid Date");
167
+ break;
168
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN:
169
+ currentRef[preSegment] = Number.NaN;
170
+ break;
171
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED:
172
+ currentRef[preSegment] = void 0;
173
+ break;
174
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL:
175
+ currentRef[preSegment] = new URL(currentRef[preSegment]);
176
+ break;
177
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP: {
178
+ const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
179
+ currentRef[preSegment] = new RegExp(pattern, flags);
180
+ break;
181
+ }
182
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET:
183
+ currentRef[preSegment] = new Set(currentRef[preSegment]);
184
+ break;
185
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP:
186
+ currentRef[preSegment] = new Map(currentRef[preSegment]);
187
+ break;
188
+ }
189
+ }
190
+ return ref.data;
191
+ }
192
+ }
193
+
194
+ function toHttpPath(path) {
195
+ return `/${path.map(encodeURIComponent).join("/")}`;
196
+ }
197
+ function getMalformedResponseErrorCode(status) {
198
+ return Object.entries(COMMON_ORPC_ERROR_DEFS).find(([, def]) => def.status === status)?.[0] ?? "MALFORMED_ORPC_ERROR_RESPONSE";
199
+ }
200
+
201
+ class StandardRPCLinkCodec {
202
+ constructor(serializer, options) {
203
+ this.serializer = serializer;
204
+ this.baseUrl = options.url;
205
+ this.maxUrlLength = options.maxUrlLength ?? 2083;
206
+ this.fallbackMethod = options.fallbackMethod ?? "POST";
207
+ this.expectedMethod = options.method ?? this.fallbackMethod;
208
+ this.headers = options.headers ?? {};
209
+ }
210
+ baseUrl;
211
+ maxUrlLength;
212
+ fallbackMethod;
213
+ expectedMethod;
214
+ headers;
215
+ async encode(path, input, options) {
216
+ const expectedMethod = await value(this.expectedMethod, options, path, input);
217
+ let headers = await value(this.headers, options, path, input);
218
+ const baseUrl = await value(this.baseUrl, options, path, input);
219
+ const url = new URL(baseUrl);
220
+ url.pathname = `${url.pathname.replace(/\/$/, "")}${toHttpPath(path)}`;
221
+ if (options.lastEventId !== void 0) {
222
+ headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
223
+ }
224
+ const serialized = this.serializer.serialize(input);
225
+ if (expectedMethod === "GET" && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
226
+ const maxUrlLength = await value(this.maxUrlLength, options, path, input);
227
+ const getUrl = new URL(url);
228
+ getUrl.searchParams.append("data", stringifyJSON(serialized));
229
+ if (getUrl.toString().length <= maxUrlLength) {
230
+ return {
231
+ body: void 0,
232
+ method: expectedMethod,
233
+ headers,
234
+ url: getUrl,
235
+ signal: options.signal
236
+ };
237
+ }
238
+ }
239
+ return {
240
+ url,
241
+ method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod,
242
+ headers,
243
+ body: serialized,
244
+ signal: options.signal
245
+ };
246
+ }
247
+ async decode(response) {
248
+ const isOk = !isORPCErrorStatus(response.status);
249
+ const deserialized = await (async () => {
250
+ let isBodyOk = false;
251
+ try {
252
+ const body = await response.body();
253
+ isBodyOk = true;
254
+ return this.serializer.deserialize(body);
255
+ } catch (error) {
256
+ if (!isBodyOk) {
257
+ throw new Error("Cannot parse response body, please check the response body and content-type.", {
258
+ cause: error
259
+ });
260
+ }
261
+ throw new Error("Invalid RPC response format.", {
262
+ cause: error
263
+ });
264
+ }
265
+ })();
266
+ if (!isOk) {
267
+ if (isORPCErrorJson(deserialized)) {
268
+ throw createORPCErrorFromJson(deserialized);
269
+ }
270
+ throw new ORPCError(getMalformedResponseErrorCode(response.status), {
271
+ status: response.status,
272
+ data: { ...response, body: deserialized }
273
+ });
274
+ }
275
+ return deserialized;
276
+ }
277
+ }
278
+
279
+ class StandardRPCSerializer {
280
+ constructor(jsonSerializer) {
281
+ this.jsonSerializer = jsonSerializer;
282
+ }
283
+ serialize(data) {
284
+ if (isAsyncIteratorObject(data)) {
285
+ return mapEventIterator(data, {
286
+ value: async (value) => this.#serialize(value, false),
287
+ error: async (e) => {
288
+ return new ErrorEvent({
289
+ data: this.#serialize(toORPCError(e).toJSON(), false),
290
+ cause: e
291
+ });
292
+ }
293
+ });
294
+ }
295
+ return this.#serialize(data, true);
296
+ }
297
+ #serialize(data, enableFormData) {
298
+ const [json, meta_, maps, blobs] = this.jsonSerializer.serialize(data);
299
+ const meta = meta_.length === 0 ? void 0 : meta_;
300
+ if (!enableFormData || blobs.length === 0) {
301
+ return {
302
+ json,
303
+ meta
304
+ };
305
+ }
306
+ const form = new FormData();
307
+ form.set("data", stringifyJSON({ json, meta, maps }));
308
+ blobs.forEach((blob, i) => {
309
+ form.set(i.toString(), blob);
310
+ });
311
+ return form;
312
+ }
313
+ deserialize(data) {
314
+ if (isAsyncIteratorObject(data)) {
315
+ return mapEventIterator(data, {
316
+ value: async (value) => this.#deserialize(value),
317
+ error: async (e) => {
318
+ if (!(e instanceof ErrorEvent)) {
319
+ return e;
320
+ }
321
+ const deserialized = this.#deserialize(e.data);
322
+ if (isORPCErrorJson(deserialized)) {
323
+ return createORPCErrorFromJson(deserialized, { cause: e });
324
+ }
325
+ return new ErrorEvent({
326
+ data: deserialized,
327
+ cause: e
328
+ });
329
+ }
330
+ });
331
+ }
332
+ return this.#deserialize(data);
333
+ }
334
+ #deserialize(data) {
335
+ if (!(data instanceof FormData)) {
336
+ return this.jsonSerializer.deserialize(data.json, data.meta ?? []);
337
+ }
338
+ const serialized = JSON.parse(data.get("data"));
339
+ return this.jsonSerializer.deserialize(
340
+ serialized.json,
341
+ serialized.meta ?? [],
342
+ serialized.maps,
343
+ (i) => data.get(i.toString())
344
+ );
345
+ }
346
+ }
347
+
348
+ export { CompositeStandardLinkPlugin as C, InvalidEventIteratorRetryResponse as I, StandardLink as S, STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES as a, StandardRPCJsonSerializer as b, StandardRPCLinkCodec as c, StandardRPCSerializer as d, getMalformedResponseErrorCode as g, toHttpPath as t };
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.3cb80cf",
4
+ "version": "0.0.0-next.3ee2e95",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -15,44 +15,39 @@
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
- "./openapi": {
23
- "types": "./dist/src/openapi/index.d.ts",
24
- "import": "./dist/openapi.js",
25
- "default": "./dist/openapi.js"
22
+ "./plugins": {
23
+ "types": "./dist/plugins/index.d.mts",
24
+ "import": "./dist/plugins/index.mjs",
25
+ "default": "./dist/plugins/index.mjs"
26
26
  },
27
- "./rpc": {
28
- "types": "./dist/src/rpc/index.d.ts",
29
- "import": "./dist/rpc.js",
30
- "default": "./dist/rpc.js"
27
+ "./standard": {
28
+ "types": "./dist/adapters/standard/index.d.mts",
29
+ "import": "./dist/adapters/standard/index.mjs",
30
+ "default": "./dist/adapters/standard/index.mjs"
31
31
  },
32
32
  "./fetch": {
33
- "types": "./dist/src/adapters/fetch/index.d.ts",
34
- "import": "./dist/fetch.js",
35
- "default": "./dist/fetch.js"
36
- },
37
- "./🔒/*": {
38
- "types": "./dist/src/*.d.ts"
33
+ "types": "./dist/adapters/fetch/index.d.mts",
34
+ "import": "./dist/adapters/fetch/index.mjs",
35
+ "default": "./dist/adapters/fetch/index.mjs"
39
36
  }
40
37
  },
41
38
  "files": [
42
- "!**/*.map",
43
- "!**/*.tsbuildinfo",
44
39
  "dist"
45
40
  ],
46
41
  "dependencies": {
47
- "@orpc/server-standard": "^0.4.0",
48
- "@orpc/server-standard-fetch": "^0.4.0",
49
- "@orpc/shared": "0.0.0-next.3cb80cf"
42
+ "@orpc/shared": "0.0.0-next.3ee2e95",
43
+ "@orpc/standard-server-fetch": "0.0.0-next.3ee2e95",
44
+ "@orpc/standard-server": "0.0.0-next.3ee2e95"
50
45
  },
51
46
  "devDependencies": {
52
- "zod": "^3.24.1"
47
+ "zod": "^3.24.2"
53
48
  },
54
49
  "scripts": {
55
- "build": "tsup --onSuccess='tsc -b --noCheck'",
50
+ "build": "unbuild",
56
51
  "build:watch": "pnpm run build --watch",
57
52
  "type:check": "tsc -b"
58
53
  }
@@ -1,288 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
6
-
7
- // src/error.ts
8
- import { isObject } from "@orpc/shared";
9
- var COMMON_ORPC_ERROR_DEFS = {
10
- BAD_REQUEST: {
11
- status: 400,
12
- message: "Bad Request"
13
- },
14
- UNAUTHORIZED: {
15
- status: 401,
16
- message: "Unauthorized"
17
- },
18
- FORBIDDEN: {
19
- status: 403,
20
- message: "Forbidden"
21
- },
22
- NOT_FOUND: {
23
- status: 404,
24
- message: "Not Found"
25
- },
26
- METHOD_NOT_SUPPORTED: {
27
- status: 405,
28
- message: "Method Not Supported"
29
- },
30
- NOT_ACCEPTABLE: {
31
- status: 406,
32
- message: "Not Acceptable"
33
- },
34
- TIMEOUT: {
35
- status: 408,
36
- message: "Request Timeout"
37
- },
38
- CONFLICT: {
39
- status: 409,
40
- message: "Conflict"
41
- },
42
- PRECONDITION_FAILED: {
43
- status: 412,
44
- message: "Precondition Failed"
45
- },
46
- PAYLOAD_TOO_LARGE: {
47
- status: 413,
48
- message: "Payload Too Large"
49
- },
50
- UNSUPPORTED_MEDIA_TYPE: {
51
- status: 415,
52
- message: "Unsupported Media Type"
53
- },
54
- UNPROCESSABLE_CONTENT: {
55
- status: 422,
56
- message: "Unprocessable Content"
57
- },
58
- TOO_MANY_REQUESTS: {
59
- status: 429,
60
- message: "Too Many Requests"
61
- },
62
- CLIENT_CLOSED_REQUEST: {
63
- status: 499,
64
- message: "Client Closed Request"
65
- },
66
- INTERNAL_SERVER_ERROR: {
67
- status: 500,
68
- message: "Internal Server Error"
69
- },
70
- NOT_IMPLEMENTED: {
71
- status: 501,
72
- message: "Not Implemented"
73
- },
74
- BAD_GATEWAY: {
75
- status: 502,
76
- message: "Bad Gateway"
77
- },
78
- SERVICE_UNAVAILABLE: {
79
- status: 503,
80
- message: "Service Unavailable"
81
- },
82
- GATEWAY_TIMEOUT: {
83
- status: 504,
84
- message: "Gateway Timeout"
85
- }
86
- };
87
- function fallbackORPCErrorStatus(code, status) {
88
- return status ?? COMMON_ORPC_ERROR_DEFS[code]?.status ?? 500;
89
- }
90
- function fallbackORPCErrorMessage(code, message) {
91
- return message || COMMON_ORPC_ERROR_DEFS[code]?.message || code;
92
- }
93
- var ORPCError = class _ORPCError extends Error {
94
- defined;
95
- code;
96
- status;
97
- data;
98
- constructor(code, ...[options]) {
99
- if (options?.status && (options.status < 400 || options.status >= 600)) {
100
- throw new Error("[ORPCError] The error status code must be in the 400-599 range.");
101
- }
102
- const message = fallbackORPCErrorMessage(code, options?.message);
103
- super(message, options);
104
- this.code = code;
105
- this.status = fallbackORPCErrorStatus(code, options?.status);
106
- this.defined = options?.defined ?? false;
107
- this.data = options?.data;
108
- }
109
- toJSON() {
110
- return {
111
- defined: this.defined,
112
- code: this.code,
113
- status: this.status,
114
- message: this.message,
115
- data: this.data
116
- };
117
- }
118
- static fromJSON(json, options) {
119
- return new _ORPCError(json.code, {
120
- ...options,
121
- ...json
122
- });
123
- }
124
- static isValidJSON(json) {
125
- if (!isObject(json)) {
126
- return false;
127
- }
128
- const validKeys = ["defined", "code", "status", "message", "data"];
129
- if (Object.keys(json).some((k) => !validKeys.includes(k))) {
130
- return false;
131
- }
132
- 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";
133
- }
134
- };
135
- function isDefinedError(error) {
136
- return error instanceof ORPCError && error.defined;
137
- }
138
- function toORPCError(error) {
139
- return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", {
140
- message: "Internal server error",
141
- cause: error
142
- });
143
- }
144
-
145
- // src/event-iterator-state.ts
146
- var iteratorStates = /* @__PURE__ */ new WeakMap();
147
- function registerEventIteratorState(iterator, state) {
148
- iteratorStates.set(iterator, state);
149
- }
150
- function updateEventIteratorStatus(state, status) {
151
- if (state.status !== status) {
152
- state.status = status;
153
- state.listeners.forEach((cb) => cb(status));
154
- }
155
- }
156
- function onEventIteratorStatusChange(iterator, callback, notifyImmediately = true) {
157
- const state = iteratorStates.get(iterator);
158
- if (!state) {
159
- throw new Error("Iterator is not registered.");
160
- }
161
- if (notifyImmediately) {
162
- callback(state.status);
163
- }
164
- state.listeners.push(callback);
165
- return () => {
166
- const index = state.listeners.indexOf(callback);
167
- if (index !== -1) {
168
- state.listeners.splice(index, 1);
169
- }
170
- };
171
- }
172
-
173
- // src/event-iterator.ts
174
- import { getEventMeta, isEventMetaContainer, withEventMeta } from "@orpc/server-standard";
175
- import { retry } from "@orpc/shared";
176
- function mapEventIterator(iterator, maps) {
177
- return async function* () {
178
- try {
179
- while (true) {
180
- const { done, value } = await iterator.next();
181
- let mappedValue = await maps.value(value, done);
182
- if (mappedValue !== value) {
183
- const meta = getEventMeta(value);
184
- if (meta && isEventMetaContainer(mappedValue)) {
185
- mappedValue = withEventMeta(mappedValue, meta);
186
- }
187
- }
188
- if (done) {
189
- return mappedValue;
190
- }
191
- yield mappedValue;
192
- }
193
- } catch (error) {
194
- let mappedError = await maps.error(error);
195
- if (mappedError !== error) {
196
- const meta = getEventMeta(error);
197
- if (meta && isEventMetaContainer(mappedError)) {
198
- mappedError = withEventMeta(mappedError, meta);
199
- }
200
- }
201
- throw mappedError;
202
- } finally {
203
- await iterator.return?.();
204
- }
205
- }();
206
- }
207
- var MAX_ALLOWED_RETRY_TIMES = 99;
208
- function createAutoRetryEventIterator(initial, reconnect, initialLastEventId) {
209
- const state = {
210
- status: "connected",
211
- listeners: []
212
- };
213
- const iterator = async function* () {
214
- let current = initial;
215
- let lastEventId = initialLastEventId;
216
- let lastRetry;
217
- let retryTimes = 0;
218
- try {
219
- while (true) {
220
- try {
221
- updateEventIteratorStatus(state, "connected");
222
- const { done, value } = await current.next();
223
- const meta = getEventMeta(value);
224
- lastEventId = meta?.id ?? lastEventId;
225
- lastRetry = meta?.retry ?? lastRetry;
226
- retryTimes = 0;
227
- if (done) {
228
- return value;
229
- }
230
- yield value;
231
- } catch (e) {
232
- updateEventIteratorStatus(state, "reconnecting");
233
- const meta = getEventMeta(e);
234
- lastEventId = meta?.id ?? lastEventId;
235
- lastRetry = meta?.retry ?? lastRetry;
236
- let currentError = e;
237
- current = await retry({ times: MAX_ALLOWED_RETRY_TIMES }, async (exit) => {
238
- retryTimes += 1;
239
- if (retryTimes > MAX_ALLOWED_RETRY_TIMES) {
240
- throw exit(new Error(
241
- `Exceeded maximum retry attempts (${MAX_ALLOWED_RETRY_TIMES}) for event source. Possible infinite retry loop detected. Please review the retry logic.`,
242
- { cause: currentError }
243
- ));
244
- }
245
- const reconnected = await (async () => {
246
- try {
247
- return await reconnect({
248
- lastRetry,
249
- lastEventId,
250
- retryTimes,
251
- error: currentError
252
- });
253
- } catch (e2) {
254
- currentError = e2;
255
- throw e2;
256
- }
257
- })();
258
- if (!reconnected) {
259
- throw exit(currentError);
260
- }
261
- return reconnected;
262
- });
263
- }
264
- }
265
- } finally {
266
- updateEventIteratorStatus(state, "closed");
267
- await current.return?.();
268
- }
269
- }();
270
- registerEventIteratorState(iterator, state);
271
- return iterator;
272
- }
273
-
274
- export {
275
- __export,
276
- COMMON_ORPC_ERROR_DEFS,
277
- fallbackORPCErrorStatus,
278
- fallbackORPCErrorMessage,
279
- ORPCError,
280
- isDefinedError,
281
- toORPCError,
282
- registerEventIteratorState,
283
- updateEventIteratorStatus,
284
- onEventIteratorStatusChange,
285
- mapEventIterator,
286
- createAutoRetryEventIterator
287
- };
288
- //# sourceMappingURL=chunk-2UPNYYFF.js.map