@orpc/client 0.0.0-next.b6be6f0 → 0.0.0-next.ba53a01

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,351 @@
1
+ import { intercept, isAsyncIteratorObject, value, isObject, trim, stringifyJSON } from '@orpc/shared';
2
+ import { c as createAutoRetryEventIterator, O as ORPCError, m as mapEventIterator, t as toORPCError } from './client.XAn8cDTM.mjs';
3
+ import { ErrorEvent } from '@orpc/standard-server';
4
+
5
+ class InvalidEventIteratorRetryResponse extends Error {
6
+ }
7
+ class StandardLink {
8
+ constructor(codec, sender, options) {
9
+ this.codec = codec;
10
+ this.sender = sender;
11
+ this.eventIteratorMaxRetries = options.eventIteratorMaxRetries ?? 5;
12
+ this.eventIteratorRetryDelay = options.eventIteratorRetryDelay ?? ((o) => o.lastRetry ?? 1e3 * 2 ** o.retryTimes);
13
+ this.eventIteratorShouldRetry = options.eventIteratorShouldRetry ?? true;
14
+ this.interceptors = options.interceptors ?? [];
15
+ this.clientInterceptors = options.clientInterceptors ?? [];
16
+ }
17
+ eventIteratorMaxRetries;
18
+ eventIteratorRetryDelay;
19
+ eventIteratorShouldRetry;
20
+ interceptors;
21
+ clientInterceptors;
22
+ call(path, input, options) {
23
+ return intercept(this.interceptors, { path, input, options }, async ({ path: path2, input: input2, options: options2 }) => {
24
+ const output = await this.#call(path2, input2, options2);
25
+ if (!isAsyncIteratorObject(output)) {
26
+ return output;
27
+ }
28
+ return createAutoRetryEventIterator(output, async (reconnectOptions) => {
29
+ const maxRetries = await value(this.eventIteratorMaxRetries, reconnectOptions, options2, path2, input2);
30
+ if (options2.signal?.aborted || reconnectOptions.retryTimes > maxRetries) {
31
+ return null;
32
+ }
33
+ const shouldRetry = await value(this.eventIteratorShouldRetry, reconnectOptions, options2, path2, input2);
34
+ if (!shouldRetry) {
35
+ return null;
36
+ }
37
+ const retryDelay = await value(this.eventIteratorRetryDelay, reconnectOptions, options2, path2, input2);
38
+ await new Promise((resolve) => setTimeout(resolve, retryDelay));
39
+ const updatedOptions = { ...options2, lastEventId: reconnectOptions.lastEventId };
40
+ const maybeIterator = await this.#call(path2, input2, updatedOptions);
41
+ if (!isAsyncIteratorObject(maybeIterator)) {
42
+ throw new InvalidEventIteratorRetryResponse("Invalid Event Iterator retry response");
43
+ }
44
+ return maybeIterator;
45
+ }, options2.lastEventId);
46
+ });
47
+ }
48
+ async #call(path, input, options) {
49
+ const request = await this.codec.encode(path, input, options);
50
+ const response = await intercept(
51
+ this.clientInterceptors,
52
+ { request },
53
+ ({ request: request2 }) => this.sender.call(request2, options, path, input)
54
+ );
55
+ const output = await this.codec.decode(response, options, path, input);
56
+ return output;
57
+ }
58
+ }
59
+
60
+ const STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES = {
61
+ BIGINT: 0,
62
+ DATE: 1,
63
+ NAN: 2,
64
+ UNDEFINED: 3,
65
+ URL: 4,
66
+ REGEXP: 5,
67
+ SET: 6,
68
+ MAP: 7
69
+ };
70
+ class StandardRPCJsonSerializer {
71
+ customSerializers;
72
+ constructor(options = {}) {
73
+ this.customSerializers = options.customJsonSerializers ?? [];
74
+ if (this.customSerializers.length !== new Set(this.customSerializers.map((custom) => custom.type)).size) {
75
+ throw new Error("Custom serializer type must be unique.");
76
+ }
77
+ }
78
+ serialize(data, segments = [], meta = [], maps = [], blobs = []) {
79
+ for (const custom of this.customSerializers) {
80
+ if (custom.condition(data)) {
81
+ const result = this.serialize(custom.serialize(data), segments, meta, maps, blobs);
82
+ meta.push([custom.type, ...segments]);
83
+ return result;
84
+ }
85
+ }
86
+ if (data instanceof Blob) {
87
+ maps.push(segments);
88
+ blobs.push(data);
89
+ return [data, meta, maps, blobs];
90
+ }
91
+ if (typeof data === "bigint") {
92
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT, ...segments]);
93
+ return [data.toString(), meta, maps, blobs];
94
+ }
95
+ if (data instanceof Date) {
96
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE, ...segments]);
97
+ if (Number.isNaN(data.getTime())) {
98
+ return [null, meta, maps, blobs];
99
+ }
100
+ return [data.toISOString(), meta, maps, blobs];
101
+ }
102
+ if (Number.isNaN(data)) {
103
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN, ...segments]);
104
+ return [null, meta, maps, blobs];
105
+ }
106
+ if (data instanceof URL) {
107
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL, ...segments]);
108
+ return [data.toString(), meta, maps, blobs];
109
+ }
110
+ if (data instanceof RegExp) {
111
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP, ...segments]);
112
+ return [data.toString(), meta, maps, blobs];
113
+ }
114
+ if (data instanceof Set) {
115
+ const result = this.serialize(Array.from(data), segments, meta, maps, blobs);
116
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET, ...segments]);
117
+ return result;
118
+ }
119
+ if (data instanceof Map) {
120
+ const result = this.serialize(Array.from(data.entries()), segments, meta, maps, blobs);
121
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP, ...segments]);
122
+ return result;
123
+ }
124
+ if (Array.isArray(data)) {
125
+ const json = data.map((v, i) => {
126
+ if (v === void 0) {
127
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED, ...segments, i]);
128
+ return v;
129
+ }
130
+ return this.serialize(v, [...segments, i], meta, maps, blobs)[0];
131
+ });
132
+ return [json, meta, maps, blobs];
133
+ }
134
+ if (isObject(data)) {
135
+ const json = {};
136
+ for (const k in data) {
137
+ json[k] = this.serialize(data[k], [...segments, k], meta, maps, blobs)[0];
138
+ }
139
+ return [json, meta, maps, blobs];
140
+ }
141
+ return [data, meta, maps, blobs];
142
+ }
143
+ deserialize(json, meta, maps, getBlob) {
144
+ const ref = { data: json };
145
+ if (maps && getBlob) {
146
+ maps.forEach((segments, i) => {
147
+ let currentRef = ref;
148
+ let preSegment = "data";
149
+ segments.forEach((segment) => {
150
+ currentRef = currentRef[preSegment];
151
+ preSegment = segment;
152
+ });
153
+ currentRef[preSegment] = getBlob(i);
154
+ });
155
+ }
156
+ for (const item of meta) {
157
+ const type = item[0];
158
+ let currentRef = ref;
159
+ let preSegment = "data";
160
+ for (let i = 1; i < item.length; i++) {
161
+ currentRef = currentRef[preSegment];
162
+ preSegment = item[i];
163
+ }
164
+ for (const custom of this.customSerializers) {
165
+ if (custom.type === type) {
166
+ currentRef[preSegment] = custom.deserialize(currentRef[preSegment]);
167
+ break;
168
+ }
169
+ }
170
+ switch (type) {
171
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT:
172
+ currentRef[preSegment] = BigInt(currentRef[preSegment]);
173
+ break;
174
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE:
175
+ currentRef[preSegment] = new Date(currentRef[preSegment] ?? "Invalid Date");
176
+ break;
177
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN:
178
+ currentRef[preSegment] = Number.NaN;
179
+ break;
180
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED:
181
+ currentRef[preSegment] = void 0;
182
+ break;
183
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL:
184
+ currentRef[preSegment] = new URL(currentRef[preSegment]);
185
+ break;
186
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP: {
187
+ const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
188
+ currentRef[preSegment] = new RegExp(pattern, flags);
189
+ break;
190
+ }
191
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET:
192
+ currentRef[preSegment] = new Set(currentRef[preSegment]);
193
+ break;
194
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP:
195
+ currentRef[preSegment] = new Map(currentRef[preSegment]);
196
+ break;
197
+ }
198
+ }
199
+ return ref.data;
200
+ }
201
+ }
202
+
203
+ class StandardRPCLinkCodec {
204
+ constructor(serializer, options) {
205
+ this.serializer = serializer;
206
+ this.baseUrl = options.url;
207
+ this.maxUrlLength = options.maxUrlLength ?? 2083;
208
+ this.fallbackMethod = options.fallbackMethod ?? "POST";
209
+ this.expectedMethod = options.method ?? this.fallbackMethod;
210
+ this.headers = options.headers ?? {};
211
+ }
212
+ baseUrl;
213
+ maxUrlLength;
214
+ fallbackMethod;
215
+ expectedMethod;
216
+ headers;
217
+ async encode(path, input, options) {
218
+ const expectedMethod = await value(this.expectedMethod, options, path, input);
219
+ const headers = await value(this.headers, options, path, input);
220
+ const baseUrl = await value(this.baseUrl, options, path, input);
221
+ const url = new URL(`${trim(baseUrl.toString(), "/")}/${path.map(encodeURIComponent).join("/")}`);
222
+ const serialized = this.serializer.serialize(input);
223
+ if (expectedMethod === "GET" && !(serialized instanceof FormData) && !(serialized instanceof Blob) && !isAsyncIteratorObject(serialized)) {
224
+ const maxUrlLength = await value(this.maxUrlLength, options, path, input);
225
+ const getUrl = new URL(url);
226
+ getUrl.searchParams.append("data", stringifyJSON(serialized) ?? "");
227
+ if (getUrl.toString().length <= maxUrlLength) {
228
+ return {
229
+ body: void 0,
230
+ method: expectedMethod,
231
+ headers,
232
+ url: getUrl,
233
+ signal: options.signal
234
+ };
235
+ }
236
+ }
237
+ return {
238
+ url,
239
+ method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod,
240
+ headers,
241
+ body: serialized,
242
+ signal: options.signal
243
+ };
244
+ }
245
+ async decode(response) {
246
+ const isOk = response.status >= 200 && response.status < 300;
247
+ const deserialized = await (async () => {
248
+ let isBodyOk = false;
249
+ try {
250
+ const body = await response.body();
251
+ isBodyOk = true;
252
+ return this.serializer.deserialize(body);
253
+ } catch (error) {
254
+ if (!isBodyOk) {
255
+ throw new Error("Cannot parse response body, please check the response body and content-type.", {
256
+ cause: error
257
+ });
258
+ }
259
+ throw new Error("Invalid RPC response format.", {
260
+ cause: error
261
+ });
262
+ }
263
+ })();
264
+ if (!isOk) {
265
+ if (ORPCError.isValidJSON(deserialized)) {
266
+ throw ORPCError.fromJSON(deserialized);
267
+ }
268
+ throw new Error("Invalid RPC error response format.", {
269
+ cause: deserialized
270
+ });
271
+ }
272
+ return deserialized;
273
+ }
274
+ }
275
+
276
+ class StandardRPCSerializer {
277
+ constructor(jsonSerializer) {
278
+ this.jsonSerializer = jsonSerializer;
279
+ }
280
+ serialize(data) {
281
+ if (isAsyncIteratorObject(data)) {
282
+ return mapEventIterator(data, {
283
+ value: async (value) => this.#serialize(value, false),
284
+ error: async (e) => {
285
+ return new ErrorEvent({
286
+ data: this.#serialize(toORPCError(e).toJSON(), false),
287
+ cause: e
288
+ });
289
+ }
290
+ });
291
+ }
292
+ return this.#serialize(data, true);
293
+ }
294
+ #serialize(data, enableFormData) {
295
+ if (data === void 0 || data instanceof Blob) {
296
+ return data;
297
+ }
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 (ORPCError.isValidJSON(deserialized)) {
323
+ return ORPCError.fromJSON(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 === void 0 || data instanceof Blob) {
336
+ return data;
337
+ }
338
+ if (!(data instanceof FormData)) {
339
+ return this.jsonSerializer.deserialize(data.json, data.meta ?? []);
340
+ }
341
+ const serialized = JSON.parse(data.get("data"));
342
+ return this.jsonSerializer.deserialize(
343
+ serialized.json,
344
+ serialized.meta ?? [],
345
+ serialized.maps,
346
+ (i) => data.get(i.toString())
347
+ );
348
+ }
349
+ }
350
+
351
+ export { InvalidEventIteratorRetryResponse as I, StandardLink as S, STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES as a, StandardRPCJsonSerializer as b, StandardRPCLinkCodec as c, StandardRPCSerializer as d };
@@ -0,0 +1,42 @@
1
+ type ClientContext = Record<string, any>;
2
+ type ClientOptions<TClientContext extends ClientContext> = {
3
+ signal?: AbortSignal;
4
+ lastEventId?: string | undefined;
5
+ } & (Record<never, never> extends TClientContext ? {
6
+ context?: TClientContext;
7
+ } : {
8
+ context: TClientContext;
9
+ });
10
+ type ClientRest<TClientContext extends ClientContext, TInput> = Record<never, never> extends TClientContext ? undefined extends TInput ? [input?: TInput, options?: ClientOptions<TClientContext>] : [input: TInput, options?: ClientOptions<TClientContext>] : [input: TInput, options: ClientOptions<TClientContext>];
11
+ type ClientPromiseResult<TOutput, TError extends Error> = Promise<TOutput> & {
12
+ __error?: {
13
+ type: TError;
14
+ };
15
+ };
16
+ interface Client<TClientContext extends ClientContext, TInput, TOutput, TError extends Error> {
17
+ (...rest: ClientRest<TClientContext, TInput>): ClientPromiseResult<TOutput, TError>;
18
+ }
19
+ type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | {
20
+ [k: string]: NestedClient<TClientContext>;
21
+ };
22
+ type InferClientContext<T extends NestedClient<any>> = T extends NestedClient<infer U> ? U : never;
23
+ type ClientOptionsOut<TClientContext extends ClientContext> = ClientOptions<TClientContext> & {
24
+ context: TClientContext;
25
+ };
26
+ interface ClientLink<TClientContext extends ClientContext> {
27
+ call: (path: readonly string[], input: unknown, options: ClientOptionsOut<TClientContext>) => Promise<unknown>;
28
+ }
29
+
30
+ declare function mapEventIterator<TYield, TReturn, TNext, TMap = TYield | TReturn>(iterator: AsyncIterator<TYield, TReturn, TNext>, maps: {
31
+ value: (value: NoInfer<TYield | TReturn>, done: boolean | undefined) => Promise<TMap>;
32
+ error: (error: unknown) => Promise<unknown>;
33
+ }): AsyncGenerator<TMap, TMap, TNext>;
34
+ interface EventIteratorReconnectOptions {
35
+ lastRetry: number | undefined;
36
+ lastEventId: string | undefined;
37
+ retryTimes: number;
38
+ error: unknown;
39
+ }
40
+ declare function createAutoRetryEventIterator<TYield, TReturn>(initial: AsyncIterator<TYield, TReturn, void>, reconnect: (options: EventIteratorReconnectOptions) => Promise<AsyncIterator<TYield, TReturn, void> | null>, initialLastEventId: string | undefined): AsyncGenerator<TYield, TReturn, void>;
41
+
42
+ export { type ClientContext as C, type EventIteratorReconnectOptions as E, type InferClientContext as I, type NestedClient as N, type ClientOptionsOut as a, type ClientLink as b, type ClientPromiseResult as c, createAutoRetryEventIterator as d, type ClientOptions as e, type ClientRest as f, type Client as g, mapEventIterator as m };
@@ -0,0 +1,42 @@
1
+ type ClientContext = Record<string, any>;
2
+ type ClientOptions<TClientContext extends ClientContext> = {
3
+ signal?: AbortSignal;
4
+ lastEventId?: string | undefined;
5
+ } & (Record<never, never> extends TClientContext ? {
6
+ context?: TClientContext;
7
+ } : {
8
+ context: TClientContext;
9
+ });
10
+ type ClientRest<TClientContext extends ClientContext, TInput> = Record<never, never> extends TClientContext ? undefined extends TInput ? [input?: TInput, options?: ClientOptions<TClientContext>] : [input: TInput, options?: ClientOptions<TClientContext>] : [input: TInput, options: ClientOptions<TClientContext>];
11
+ type ClientPromiseResult<TOutput, TError extends Error> = Promise<TOutput> & {
12
+ __error?: {
13
+ type: TError;
14
+ };
15
+ };
16
+ interface Client<TClientContext extends ClientContext, TInput, TOutput, TError extends Error> {
17
+ (...rest: ClientRest<TClientContext, TInput>): ClientPromiseResult<TOutput, TError>;
18
+ }
19
+ type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | {
20
+ [k: string]: NestedClient<TClientContext>;
21
+ };
22
+ type InferClientContext<T extends NestedClient<any>> = T extends NestedClient<infer U> ? U : never;
23
+ type ClientOptionsOut<TClientContext extends ClientContext> = ClientOptions<TClientContext> & {
24
+ context: TClientContext;
25
+ };
26
+ interface ClientLink<TClientContext extends ClientContext> {
27
+ call: (path: readonly string[], input: unknown, options: ClientOptionsOut<TClientContext>) => Promise<unknown>;
28
+ }
29
+
30
+ declare function mapEventIterator<TYield, TReturn, TNext, TMap = TYield | TReturn>(iterator: AsyncIterator<TYield, TReturn, TNext>, maps: {
31
+ value: (value: NoInfer<TYield | TReturn>, done: boolean | undefined) => Promise<TMap>;
32
+ error: (error: unknown) => Promise<unknown>;
33
+ }): AsyncGenerator<TMap, TMap, TNext>;
34
+ interface EventIteratorReconnectOptions {
35
+ lastRetry: number | undefined;
36
+ lastEventId: string | undefined;
37
+ retryTimes: number;
38
+ error: unknown;
39
+ }
40
+ declare function createAutoRetryEventIterator<TYield, TReturn>(initial: AsyncIterator<TYield, TReturn, void>, reconnect: (options: EventIteratorReconnectOptions) => Promise<AsyncIterator<TYield, TReturn, void> | null>, initialLastEventId: string | undefined): AsyncGenerator<TYield, TReturn, void>;
41
+
42
+ export { type ClientContext as C, type EventIteratorReconnectOptions as E, type InferClientContext as I, type NestedClient as N, type ClientOptionsOut as a, type ClientLink as b, type ClientPromiseResult as c, createAutoRetryEventIterator as d, type ClientOptions as e, type ClientRest as f, type Client as g, mapEventIterator as m };
@@ -0,0 +1,266 @@
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, options = {}) {
151
+ const notifyImmediately = options.notifyImmediately ?? true;
152
+ const state = iteratorStates.get(iterator);
153
+ if (!state) {
154
+ throw new Error("Iterator is not registered.");
155
+ }
156
+ if (notifyImmediately) {
157
+ callback(state.status);
158
+ }
159
+ state.listeners.push(callback);
160
+ return () => {
161
+ const index = state.listeners.indexOf(callback);
162
+ if (index !== -1) {
163
+ state.listeners.splice(index, 1);
164
+ }
165
+ };
166
+ }
167
+
168
+ function mapEventIterator(iterator, maps) {
169
+ return async function* () {
170
+ try {
171
+ while (true) {
172
+ const { done, value } = await iterator.next();
173
+ let mappedValue = await maps.value(value, done);
174
+ if (mappedValue !== value) {
175
+ const meta = getEventMeta(value);
176
+ if (meta && isTypescriptObject(mappedValue)) {
177
+ mappedValue = withEventMeta(mappedValue, meta);
178
+ }
179
+ }
180
+ if (done) {
181
+ return mappedValue;
182
+ }
183
+ yield mappedValue;
184
+ }
185
+ } catch (error) {
186
+ let mappedError = await maps.error(error);
187
+ if (mappedError !== error) {
188
+ const meta = getEventMeta(error);
189
+ if (meta && isTypescriptObject(mappedError)) {
190
+ mappedError = withEventMeta(mappedError, meta);
191
+ }
192
+ }
193
+ throw mappedError;
194
+ } finally {
195
+ await iterator.return?.();
196
+ }
197
+ }();
198
+ }
199
+ const MAX_ALLOWED_RETRY_TIMES = 99;
200
+ function createAutoRetryEventIterator(initial, reconnect, initialLastEventId) {
201
+ const state = {
202
+ status: "connected",
203
+ listeners: []
204
+ };
205
+ const iterator = async function* () {
206
+ let current = initial;
207
+ let lastEventId = initialLastEventId;
208
+ let lastRetry;
209
+ let retryTimes = 0;
210
+ try {
211
+ while (true) {
212
+ try {
213
+ updateEventIteratorStatus(state, "connected");
214
+ const { done, value } = await current.next();
215
+ const meta = getEventMeta(value);
216
+ lastEventId = meta?.id ?? lastEventId;
217
+ lastRetry = meta?.retry ?? lastRetry;
218
+ retryTimes = 0;
219
+ if (done) {
220
+ return value;
221
+ }
222
+ yield value;
223
+ } catch (e) {
224
+ updateEventIteratorStatus(state, "reconnecting");
225
+ const meta = getEventMeta(e);
226
+ lastEventId = meta?.id ?? lastEventId;
227
+ lastRetry = meta?.retry ?? lastRetry;
228
+ let currentError = e;
229
+ current = await retry({ times: MAX_ALLOWED_RETRY_TIMES }, async (exit) => {
230
+ retryTimes += 1;
231
+ if (retryTimes > MAX_ALLOWED_RETRY_TIMES) {
232
+ throw exit(new Error(
233
+ `Exceeded maximum retry attempts (${MAX_ALLOWED_RETRY_TIMES}) for event iterator. Possible infinite retry loop detected. Please review the retry logic.`,
234
+ { cause: currentError }
235
+ ));
236
+ }
237
+ const reconnected = await (async () => {
238
+ try {
239
+ return await reconnect({
240
+ lastRetry,
241
+ lastEventId,
242
+ retryTimes,
243
+ error: currentError
244
+ });
245
+ } catch (e2) {
246
+ currentError = e2;
247
+ throw e2;
248
+ }
249
+ })();
250
+ if (!reconnected) {
251
+ throw exit(currentError);
252
+ }
253
+ return reconnected;
254
+ });
255
+ }
256
+ }
257
+ } finally {
258
+ updateEventIteratorStatus(state, "closed");
259
+ await current.return?.();
260
+ }
261
+ }();
262
+ registerEventIteratorState(iterator, state);
263
+ return iterator;
264
+ }
265
+
266
+ 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 };