@orpc/client 1.14.5 → 2.0.0-beta.1

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 (38) hide show
  1. package/README.md +75 -106
  2. package/dist/adapters/fetch/index.d.mts +55 -36
  3. package/dist/adapters/fetch/index.d.ts +55 -36
  4. package/dist/adapters/fetch/index.mjs +50 -28
  5. package/dist/adapters/message-port/index.d.mts +25 -30
  6. package/dist/adapters/message-port/index.d.ts +25 -30
  7. package/dist/adapters/message-port/index.mjs +33 -29
  8. package/dist/adapters/standard/index.d.mts +58 -9
  9. package/dist/adapters/standard/index.d.ts +58 -9
  10. package/dist/adapters/standard/index.mjs +5 -5
  11. package/dist/adapters/websocket/index.d.mts +113 -21
  12. package/dist/adapters/websocket/index.d.ts +113 -21
  13. package/dist/adapters/websocket/index.mjs +98 -35
  14. package/dist/index.d.mts +84 -159
  15. package/dist/index.d.ts +84 -159
  16. package/dist/index.mjs +76 -34
  17. package/dist/plugins/index.d.mts +125 -132
  18. package/dist/plugins/index.d.ts +125 -132
  19. package/dist/plugins/index.mjs +373 -284
  20. package/dist/shared/client.8ug8I-zu.d.mts +167 -0
  21. package/dist/shared/client.8ug8I-zu.d.ts +167 -0
  22. package/dist/shared/client.BdItY5DT.d.mts +111 -0
  23. package/dist/shared/client.BdItY5DT.d.ts +111 -0
  24. package/dist/shared/client.CPF3hX6O.d.ts +96 -0
  25. package/dist/shared/client.Cby_-GGh.d.mts +96 -0
  26. package/dist/shared/client.DMXKFDyV.mjs +343 -0
  27. package/dist/shared/client.DXhchJ84.mjs +174 -0
  28. package/dist/shared/client.Dnfj8jnT.mjs +92 -0
  29. package/package.json +7 -7
  30. package/dist/shared/client.2jUAqzYU.d.ts +0 -45
  31. package/dist/shared/client.B3pNRBih.d.ts +0 -91
  32. package/dist/shared/client.BFAVy68H.d.mts +0 -91
  33. package/dist/shared/client.BLtwTQUg.mjs +0 -40
  34. package/dist/shared/client.C9pc00-H.mjs +0 -174
  35. package/dist/shared/client.CpCa3si8.d.mts +0 -45
  36. package/dist/shared/client.DxgEFWjV.mjs +0 -404
  37. package/dist/shared/client.i2uoJbEp.d.mts +0 -83
  38. package/dist/shared/client.i2uoJbEp.d.ts +0 -83
@@ -1,29 +1,121 @@
1
- import { StandardRequest, StandardLazyResponse } from '@orpc/standard-server';
2
- import { b as ClientContext, c as ClientOptions } from '../../shared/client.i2uoJbEp.js';
3
- import { f as StandardLinkClient } from '../../shared/client.2jUAqzYU.js';
4
- import { f as StandardRPCLinkOptions, g as StandardRPCLink } from '../../shared/client.B3pNRBih.js';
5
- import '@orpc/shared';
1
+ import { C as ClientContext, a as ClientOptions } from '../../shared/client.8ug8I-zu.js';
2
+ import { Promisable } from '@orpc/shared';
3
+ import { StandardRequest, StandardLazyResponse } from '@standardserver/core';
4
+ import { EncodePeerMessageOptions, DecodePeerMessageOptions } from '@standardserver/peer';
5
+ import { S as StandardLinkTransport, a as StandardLink, b as StandardLinkOptions } from '../../shared/client.CPF3hX6O.js';
6
+ import { RPCLinkCodecOptions } from '../standard/index.js';
7
+ import '../../shared/client.BdItY5DT.js';
6
8
 
7
- interface LinkWebsocketClientOptions {
8
- websocket: Pick<WebSocket, 'addEventListener' | 'send' | 'readyState'>;
9
+ type WebSocketLike = Pick<WebSocket, 'addEventListener' | 'removeEventListener' | 'send' | 'readyState'>;
10
+ interface WebsocketLinkTransportAttemptInfo {
11
+ /**
12
+ * Total number of connection attempts for this transport's lifetime.
13
+ * Starts at 1 on the first attempt, increments on every subsequent
14
+ * attempt, and never resets.
15
+ */
16
+ totalAttempt: number;
17
+ /**
18
+ * Attempt number within the current (re)connect cycle.
19
+ * Starts at 1, increments on each consecutive failure, and resets to 1
20
+ * once a connection succeeds. Use this for backoff calculations.
21
+ */
22
+ attempt: number;
9
23
  }
10
- declare class LinkWebsocketClient<T extends ClientContext> implements StandardLinkClient<T> {
11
- private readonly peer;
12
- constructor(options: LinkWebsocketClientOptions);
13
- call(request: StandardRequest, _options: ClientOptions<T>, _path: readonly string[], _input: unknown): Promise<StandardLazyResponse>;
24
+ interface WebsocketLinkTransportReconnectOptions {
25
+ /**
26
+ * Whether to automatically reconnect when the connection is lost.
27
+ *
28
+ * @default false
29
+ */
30
+ enabled: boolean;
31
+ /**
32
+ * Delay before a (re)connect attempt, in milliseconds.
33
+ *
34
+ * @default info => info.attempt === 1 ? 0 : 2_000
35
+ */
36
+ delay?: undefined | ((info: WebsocketLinkTransportAttemptInfo) => number);
37
+ /**
38
+ * Maximum number of consecutive failed attempts before giving up.
39
+ * When exceeded, `getConnectedPeer` throws instead of retrying.
40
+ * Should greater than 1
41
+ *
42
+ * @default Infinity
43
+ */
44
+ maxAttempt?: undefined | number;
45
+ /**
46
+ * Whether to proactively reconnect right after the socket closes,
47
+ * rather than waiting for the next call to trigger reconnection.
48
+ * Reduces latency for the next request.
49
+ *
50
+ * @default { enabled: false }
51
+ */
52
+ onClose?: undefined | {
53
+ /**
54
+ * Whether to proactively reconnect right after the socket closes,
55
+ * rather than waiting for the next call to trigger reconnection.
56
+ * Reduces latency for the next request.
57
+ *
58
+ * @default false
59
+ */
60
+ enabled: boolean;
61
+ /**
62
+ * Delay before reconnecting after the socket closes, in milliseconds.
63
+ *
64
+ * @default 0
65
+ */
66
+ delay?: number;
67
+ };
68
+ }
69
+ interface WebsocketLinkTransportOptions<_T extends ClientContext> {
70
+ /**
71
+ * Returns a WebSocket instance for peer communication.
72
+ * Can be async for lazy resolution.
73
+ */
74
+ connect: (info: WebsocketLinkTransportAttemptInfo) => Promisable<WebSocketLike>;
75
+ /**
76
+ * Whether to connect immediately on initialization, instead of waiting
77
+ * for the first call. Reduces latency for the first request.
78
+ *
79
+ * @default false
80
+ */
81
+ connectOnInit?: undefined | boolean;
82
+ /**
83
+ * Reconnection behavior when the connection is lost.
84
+ *
85
+ * @default { enabled: false }
86
+ */
87
+ reconnect?: undefined | WebsocketLinkTransportReconnectOptions;
88
+ /**
89
+ * Options for encoding peer messages. such as `prefix` for distinguishing messages on the same channel..
90
+ */
91
+ encodePeerMessage?: EncodePeerMessageOptions | undefined;
92
+ /**
93
+ * Options for decoding peer messages. such as `prefix` for distinguishing messages on the same channel..
94
+ */
95
+ decodePeerMessage?: DecodePeerMessageOptions | undefined;
96
+ }
97
+ declare class WebsocketLinkTransport<T extends ClientContext> implements StandardLinkTransport<T> {
98
+ private readonly connect;
99
+ private readonly reconnectEnabled;
100
+ private readonly reconnectDelay;
101
+ private readonly reconnectMaxAttempt;
102
+ private readonly reconnectOnCloseEnabled;
103
+ private readonly reconnectOnCloseDelay;
104
+ private readonly encodePeerMessageOptions;
105
+ private readonly decodePeerMessageOptions;
106
+ constructor(options: WebsocketLinkTransportOptions<T>);
107
+ send(standardRequest: StandardRequest, _path: string[], _options: ClientOptions<T>): Promise<StandardLazyResponse>;
108
+ private totalAttempt;
109
+ private attempt;
110
+ private current;
111
+ private getConnectedPeer;
14
112
  }
15
113
 
16
- interface RPCLinkOptions<T extends ClientContext> extends Omit<StandardRPCLinkOptions<T>, 'url' | 'method' | 'fallbackMethod' | 'maxUrlLength'>, LinkWebsocketClientOptions {
114
+ interface RPCLinkOptions<T extends ClientContext> extends StandardLinkOptions<T>, WebsocketLinkTransportOptions<T>, RPCLinkCodecOptions<T> {
17
115
  }
18
- /**
19
- * The RPC Link communicates with the server using the RPC protocol over WebSocket.
20
- *
21
- * @see {@link https://orpc.dev/docs/client/rpc-link RPC Link Docs}
22
- * @see {@link https://orpc.dev/docs/adapters/websocket WebSocket Adapter Docs}
23
- */
24
- declare class RPCLink<T extends ClientContext> extends StandardRPCLink<T> {
116
+ declare class RPCLink<T extends ClientContext> extends StandardLink<T> {
25
117
  constructor(options: RPCLinkOptions<T>);
26
118
  }
27
119
 
28
- export { LinkWebsocketClient, RPCLink };
29
- export type { LinkWebsocketClientOptions, RPCLinkOptions };
120
+ export { RPCLink, WebsocketLinkTransport };
121
+ export type { RPCLinkOptions, WebSocketLike, WebsocketLinkTransportAttemptInfo, WebsocketLinkTransportOptions, WebsocketLinkTransportReconnectOptions };
@@ -1,47 +1,110 @@
1
- import { readAsBuffer } from '@orpc/shared';
2
- import { ClientPeer } from '@orpc/standard-server-peer';
3
- import { c as StandardRPCLink } from '../../shared/client.DxgEFWjV.mjs';
4
- import '@orpc/standard-server';
5
- import '../../shared/client.C9pc00-H.mjs';
6
- import '@orpc/standard-server-fetch';
7
- import '../../shared/client.BLtwTQUg.mjs';
1
+ import { runWithSignal, AbortError, sleep, promiseWithResolvers, toStringOrBytes } from '@orpc/shared';
2
+ import { ClientPeer, encodePeerMessage, decodePeerMessage, isServerPeerSendMessage } from '@standardserver/peer';
3
+ import { S as StandardLink, R as RPCLinkCodec } from '../../shared/client.DXhchJ84.mjs';
4
+ import '@standardserver/core';
5
+ import '@standardserver/fetch';
6
+ import '../../shared/client.Dnfj8jnT.mjs';
7
+ import '../../shared/client.DMXKFDyV.mjs';
8
8
 
9
9
  const WEBSOCKET_CONNECTING = 0;
10
- class LinkWebsocketClient {
11
- peer;
10
+ const WEBSOCKET_OPEN = 1;
11
+ class WebsocketLinkTransport {
12
+ connect;
13
+ reconnectEnabled;
14
+ reconnectDelay;
15
+ reconnectMaxAttempt;
16
+ reconnectOnCloseEnabled;
17
+ reconnectOnCloseDelay;
18
+ encodePeerMessageOptions;
19
+ decodePeerMessageOptions;
12
20
  constructor(options) {
13
- const untilOpen = new Promise((resolve) => {
14
- if (options.websocket.readyState === WEBSOCKET_CONNECTING) {
15
- options.websocket.addEventListener("open", () => {
16
- resolve();
17
- }, { once: true });
18
- } else {
19
- resolve();
21
+ this.connect = options.connect;
22
+ this.reconnectEnabled = options.reconnect?.enabled ?? false;
23
+ this.reconnectDelay = options.reconnect?.delay ?? ((info) => info.attempt === 1 ? 0 : 2e3);
24
+ this.reconnectMaxAttempt = options.reconnect?.maxAttempt ?? Infinity;
25
+ this.reconnectOnCloseEnabled = this.reconnectEnabled && (options.reconnect?.onClose?.enabled ?? false);
26
+ this.reconnectOnCloseDelay = options.reconnect?.onClose?.delay ?? 0;
27
+ this.encodePeerMessageOptions = options.encodePeerMessage;
28
+ this.decodePeerMessageOptions = options.decodePeerMessage;
29
+ if (options.connectOnInit) {
30
+ this.getConnectedPeer().catch(() => {
31
+ });
32
+ }
33
+ }
34
+ async send(standardRequest, _path, _options) {
35
+ const peer = await runWithSignal(
36
+ standardRequest.signal,
37
+ () => this.getConnectedPeer()
38
+ );
39
+ return peer.request(standardRequest);
40
+ }
41
+ totalAttempt = 0;
42
+ attempt = 0;
43
+ current;
44
+ async getConnectedPeer() {
45
+ const current = this.current;
46
+ const resolved = await current;
47
+ if (resolved && (!this.reconnectEnabled || resolved.websocket.readyState === WEBSOCKET_OPEN)) {
48
+ this.attempt = 0;
49
+ return resolved.peer;
50
+ }
51
+ if (current !== this.current) {
52
+ return this.getConnectedPeer();
53
+ }
54
+ if (this.attempt >= this.reconnectMaxAttempt) {
55
+ throw new AbortError(`WebSocket reconnect failed after ${this.attempt} attempt(s)`);
56
+ }
57
+ this.current = (async () => {
58
+ this.totalAttempt += 1;
59
+ this.attempt += 1;
60
+ const info = { totalAttempt: this.totalAttempt, attempt: this.attempt };
61
+ await sleep(this.reconnectDelay(info));
62
+ const websocket = await this.connect(info);
63
+ const peer = new ClientPeer(async (message) => {
64
+ const encoded = await encodePeerMessage(message, this.encodePeerMessageOptions);
65
+ return websocket.send(encoded);
66
+ });
67
+ let connectingResolvers;
68
+ if (websocket.readyState === WEBSOCKET_CONNECTING) {
69
+ connectingResolvers = promiseWithResolvers();
70
+ websocket.addEventListener("open", () => {
71
+ connectingResolvers?.resolve();
72
+ });
73
+ }
74
+ websocket.addEventListener("message", async (event) => {
75
+ const message = await toStringOrBytes(event.data);
76
+ const result = decodePeerMessage(message, this.decodePeerMessageOptions);
77
+ if (result.matched && isServerPeerSendMessage(result.message)) {
78
+ await peer.message(result.message);
79
+ }
80
+ });
81
+ websocket.addEventListener("close", async (event) => {
82
+ connectingResolvers?.resolve();
83
+ if (this.reconnectOnCloseEnabled) {
84
+ sleep(this.reconnectOnCloseDelay).then(() => this.getConnectedPeer()).catch(() => {
85
+ });
86
+ }
87
+ const reason = new AbortError(`WebSocket closed (code ${event.code}: ${event.reason})`);
88
+ await peer.close(reason);
89
+ });
90
+ await connectingResolvers?.promise;
91
+ connectingResolvers = void 0;
92
+ return { websocket, peer };
93
+ })().catch((error) => {
94
+ if (!this.reconnectEnabled) {
95
+ throw error;
20
96
  }
21
97
  });
22
- this.peer = new ClientPeer(async (message) => {
23
- await untilOpen;
24
- return options.websocket.send(message);
25
- });
26
- options.websocket.addEventListener("message", async (event) => {
27
- const message = event.data instanceof Blob ? await readAsBuffer(event.data) : event.data;
28
- this.peer.message(message);
29
- });
30
- options.websocket.addEventListener("close", () => {
31
- this.peer.close();
32
- });
33
- }
34
- async call(request, _options, _path, _input) {
35
- const response = await this.peer.request(request);
36
- return { ...response, body: () => Promise.resolve(response.body) };
98
+ return this.getConnectedPeer();
37
99
  }
38
100
  }
39
101
 
40
- class RPCLink extends StandardRPCLink {
102
+ class RPCLink extends StandardLink {
41
103
  constructor(options) {
42
- const linkClient = new LinkWebsocketClient(options);
43
- super(linkClient, { ...options, url: "http://orpc" });
104
+ const codec = new RPCLinkCodec(options);
105
+ const transport = new WebsocketLinkTransport(options);
106
+ super(codec, transport, options);
44
107
  }
45
108
  }
46
109
 
47
- export { LinkWebsocketClient, RPCLink };
110
+ export { RPCLink, WebsocketLinkTransport };
package/dist/index.d.mts CHANGED
@@ -1,165 +1,79 @@
1
- import { N as NestedClient, C as ClientLink, I as InferClientContext, a as ClientPromiseResult, b as ClientContext, F as FriendlyClientOptions, c as ClientOptions, d as Client, e as ClientRest } from './shared/client.i2uoJbEp.mjs';
2
- export { f as HTTPMethod, H as HTTPPath, h as InferClientBodyInputs, j as InferClientBodyOutputs, l as InferClientErrorUnion, k as InferClientErrors, g as InferClientInputs, i as InferClientOutputs } from './shared/client.i2uoJbEp.mjs';
3
- import { MaybeOptionalOptions, ThrowableError, OnFinishState, Promisable, AsyncIteratorClass } from '@orpc/shared';
4
- export { AsyncIteratorClass, EventPublisher, EventPublisherOptions, EventPublisherSubscribeIteratorOptions, Registry, ThrowableError, asyncIteratorToStream as eventIteratorToStream, asyncIteratorToUnproxiedDataStream as eventIteratorToUnproxiedDataStream, onError, onFinish, onStart, onSuccess, streamToAsyncIteratorClass as streamToEventIterator } from '@orpc/shared';
5
- export { ErrorEvent, EventMeta, getEventMeta, withEventMeta } from '@orpc/standard-server';
1
+ import { O as ORPCErrorCode, c as ORPCError, d as ORPCErrorJSON, A as AnyORPCError, C as ClientContext, a as ClientOptions, e as AnyNestedClient, I as InferClientContext, f as InferClientError, g as Client, b as ClientLink, h as ClientRest, F as FriendlyClientOptions } from './shared/client.8ug8I-zu.mjs';
2
+ export { i as AnyORPCErrorJSON, j as COMMON_ERROR_STATUS_MAP, k as InferClientBodyInputs, l as InferClientBodyOutputs, m as InferClientErrors, n as InferClientInputs, o as InferClientOutputs, N as NestedClient, p as ORPCErrorOptions } from './shared/client.8ug8I-zu.mjs';
3
+ import { Interceptor, PromiseWithError, ThrowableError, Promisable, WrapAsyncIteratorOptions, AsyncIteratorClass } from '@orpc/shared';
4
+ export { AsyncCleanupFn, AsyncIteratorClass, AsyncIteratorClassNextFn, Registry, ThrowableError, asyncIteratorToStream as eventIteratorToStream, asyncIteratorToUnproxiedDataStream as eventIteratorToUnproxiedDataStream, onError, onFinish, onStart, onSuccess, streamToAsyncIteratorClass as streamToEventIterator } from '@orpc/shared';
5
+ export { R as RPCJsonSerialization, a as RPCJsonSerializationMeta, b as RPCJsonSerializer, c as RPCJsonSerializerHandler, d as RPCJsonSerializerOptions, e as RPCSerializer, f as RPCSerializerOptions, g as RPCSerializerSerializeOptions } from './shared/client.BdItY5DT.mjs';
6
+ export { ErrorEvent, getEventMeta, unwrapEvent, withEventMeta } from '@standardserver/core';
6
7
 
7
- interface createORPCClientOptions {
8
+ declare function isInferableError<T>(error: T): error is Extract<T, AnyORPCError>;
9
+ declare function toORPCError<T>(error: T): Extract<T, AnyORPCError> | ORPCError<'INTERNAL_SERVER_ERROR', undefined>;
10
+ declare function isORPCErrorJson(json: unknown): json is ORPCErrorJSON<ORPCErrorCode, unknown>;
11
+ declare function createORPCErrorFromJson<TCode extends ORPCErrorCode, TData>(json: ORPCErrorJSON<TCode, TData>, options?: ErrorOptions): ORPCError<TCode, TData>;
12
+ declare function cloneORPCError<T extends ORPCErrorCode, TData>(error: ORPCError<T, TData>): ORPCError<T, TData>;
13
+
14
+ interface ORPCClientInterceptorOptions<TClientContext extends ClientContext, TInput> extends ClientOptions<TClientContext> {
15
+ path: string[];
16
+ input: TInput;
17
+ }
18
+ type ORPCClientInterceptor<TClientContext extends ClientContext, TInput, TOutput, TError> = Interceptor<ORPCClientInterceptorOptions<TClientContext, TInput>, PromiseWithError<TOutput, TError>>;
19
+ interface ORPCClientScopedOptions<TClientContext extends ClientContext, TInput, TOutput, TError> {
8
20
  /**
9
- * Use as base path for all procedure, useful when you only want to call a subset of the procedure.
21
+ * Interceptors that wrap the entire client call lifecycle.
10
22
  */
11
- path?: readonly string[];
23
+ interceptors?: ORPCClientInterceptor<TClientContext, TInput, TOutput, TError>[];
12
24
  }
13
- /**
14
- * Create a oRPC client-side client from a link.
15
- *
16
- * @see {@link https://orpc.dev/docs/client/client-side Client-side Client Docs}
17
- */
18
- declare function createORPCClient<T extends NestedClient<any>>(link: ClientLink<InferClientContext<T>>, options?: createORPCClientOptions): T;
19
-
20
- declare const COMMON_ORPC_ERROR_DEFS: {
21
- readonly BAD_REQUEST: {
22
- readonly status: 400;
23
- readonly message: "Bad Request";
24
- };
25
- readonly UNAUTHORIZED: {
26
- readonly status: 401;
27
- readonly message: "Unauthorized";
28
- };
29
- readonly FORBIDDEN: {
30
- readonly status: 403;
31
- readonly message: "Forbidden";
32
- };
33
- readonly NOT_FOUND: {
34
- readonly status: 404;
35
- readonly message: "Not Found";
36
- };
37
- readonly METHOD_NOT_SUPPORTED: {
38
- readonly status: 405;
39
- readonly message: "Method Not Supported";
40
- };
41
- readonly NOT_ACCEPTABLE: {
42
- readonly status: 406;
43
- readonly message: "Not Acceptable";
44
- };
45
- readonly TIMEOUT: {
46
- readonly status: 408;
47
- readonly message: "Request Timeout";
48
- };
49
- readonly CONFLICT: {
50
- readonly status: 409;
51
- readonly message: "Conflict";
52
- };
53
- readonly PRECONDITION_FAILED: {
54
- readonly status: 412;
55
- readonly message: "Precondition Failed";
56
- };
57
- readonly PAYLOAD_TOO_LARGE: {
58
- readonly status: 413;
59
- readonly message: "Payload Too Large";
60
- };
61
- readonly UNSUPPORTED_MEDIA_TYPE: {
62
- readonly status: 415;
63
- readonly message: "Unsupported Media Type";
64
- };
65
- readonly UNPROCESSABLE_CONTENT: {
66
- readonly status: 422;
67
- readonly message: "Unprocessable Content";
68
- };
69
- readonly TOO_MANY_REQUESTS: {
70
- readonly status: 429;
71
- readonly message: "Too Many Requests";
72
- };
73
- readonly CLIENT_CLOSED_REQUEST: {
74
- readonly status: 499;
75
- readonly message: "Client Closed Request";
76
- };
77
- readonly INTERNAL_SERVER_ERROR: {
78
- readonly status: 500;
79
- readonly message: "Internal Server Error";
80
- };
81
- readonly NOT_IMPLEMENTED: {
82
- readonly status: 501;
83
- readonly message: "Not Implemented";
84
- };
85
- readonly BAD_GATEWAY: {
86
- readonly status: 502;
87
- readonly message: "Bad Gateway";
88
- };
89
- readonly SERVICE_UNAVAILABLE: {
90
- readonly status: 503;
91
- readonly message: "Service Unavailable";
92
- };
93
- readonly GATEWAY_TIMEOUT: {
94
- readonly status: 504;
95
- readonly message: "Gateway Timeout";
96
- };
25
+ type ORPCClientScoped<T extends AnyNestedClient> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? ORPCClientScopedOptions<UClientContext, UInput, UOutput, UError> : {
26
+ [K in keyof T]?: T[K] extends AnyNestedClient ? ORPCClientScoped<T[K]> : never;
97
27
  };
98
- type CommonORPCErrorCode = keyof typeof COMMON_ORPC_ERROR_DEFS;
99
- type ORPCErrorCode = CommonORPCErrorCode | (string & {});
100
- declare function fallbackORPCErrorStatus(code: ORPCErrorCode, status: number | undefined): number;
101
- declare function fallbackORPCErrorMessage(code: ORPCErrorCode, message: string | undefined): string;
102
- type ORPCErrorOptions<TData> = ErrorOptions & {
103
- defined?: boolean;
104
- status?: number;
105
- message?: string;
106
- } & (undefined extends TData ? {
107
- data?: TData;
108
- } : {
109
- data: TData;
110
- });
111
- declare class ORPCError<TCode extends ORPCErrorCode, TData> extends Error {
112
- readonly defined: boolean;
113
- readonly code: TCode;
114
- readonly status: number;
115
- readonly data: TData;
116
- constructor(code: TCode, ...rest: MaybeOptionalOptions<ORPCErrorOptions<TData>>);
117
- toJSON(): ORPCErrorJSON<TCode, TData>;
28
+ interface ORPCClientOptions<T extends AnyNestedClient> {
118
29
  /**
119
- * Workaround for Next.js where different contexts use separate
120
- * dependency graphs, causing multiple ORPCError constructors existing and breaking
121
- * `instanceof` checks across contexts.
122
- *
123
- * This is particularly problematic with "Optimized SSR", where orpc-client
124
- * executes in one context but is invoked from another. When an error is thrown
125
- * in the execution context, `instanceof ORPCError` checks fail in the
126
- * invocation context due to separate class constructors.
127
- *
128
- * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.
30
+ * Use as base path for all procedure, useful when you only want to call a subset of the procedure.
129
31
  */
130
- static [Symbol.hasInstance](instance: unknown): boolean;
32
+ path?: string[];
33
+ /**
34
+ * Interceptors that wrap the entire client call lifecycle, applied to every procedure call.
35
+ */
36
+ interceptors?: ORPCClientInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[];
37
+ /**
38
+ * Per-procedure options following the shape of the router.
39
+ * Allows fine-grained configuration (e.g. additional interceptors) for individual procedures
40
+ * without affecting the rest of the router.
41
+ */
42
+ scoped?: ORPCClientScoped<T>;
131
43
  }
132
- type ORPCErrorJSON<TCode extends string, TData> = Pick<ORPCError<TCode, TData>, 'defined' | 'code' | 'status' | 'message' | 'data'>;
133
- declare function isDefinedError<T>(error: T): error is Extract<T, ORPCError<any, any>>;
134
- declare function toORPCError(error: unknown): ORPCError<any, any>;
135
- declare function isORPCErrorStatus(status: number): boolean;
136
- declare function isORPCErrorJson(json: unknown): json is ORPCErrorJSON<ORPCErrorCode, unknown>;
137
- declare function createORPCErrorFromJson<TCode extends ORPCErrorCode, TData>(json: ORPCErrorJSON<TCode, TData>, options?: ErrorOptions): ORPCError<TCode, TData>;
44
+ declare function createORPCClient<T extends AnyNestedClient>(link: ClientLink<InferClientContext<T>>, { path, ...options }?: NoInfer<ORPCClientOptions<T>>): T;
138
45
 
139
- type SafeResult<TOutput, TError> = [error: null, data: TOutput, isDefined: false, isSuccess: true] & {
46
+ declare function resolveFriendlyClientOptions<T extends ClientContext>(options: FriendlyClientOptions<T>): ClientOptions<T>;
47
+ declare function resolveClientRest<TClientContext extends ClientContext, TInput>(rest: ClientRest<TClientContext, TInput>): [input: TInput, options: ClientOptions<TClientContext>];
48
+ type SafeResult<TOutput, TError> = [error: null, data: TOutput, inferableError: null, isSuccess: true] & {
140
49
  error: null;
141
50
  data: TOutput;
142
- isDefined: false;
51
+ inferableError: null;
143
52
  isSuccess: true;
144
- } | [error: Exclude<TError, ORPCError<any, any>>, data: undefined, isDefined: false, isSuccess: false] & {
145
- error: Exclude<TError, ORPCError<any, any>>;
53
+ } | [error: Exclude<TError, AnyORPCError>, data: undefined, inferableError: null, isSuccess: false] & {
54
+ error: Exclude<TError, AnyORPCError>;
146
55
  data: undefined;
147
- isDefined: false;
56
+ inferableError: null;
148
57
  isSuccess: false;
149
- } | [error: Extract<TError, ORPCError<any, any>>, data: undefined, isDefined: true, isSuccess: false] & {
150
- error: Extract<TError, ORPCError<any, any>>;
58
+ } | [error: Extract<TError, AnyORPCError>, data: undefined, inferableError: Extract<TError, AnyORPCError>, isSuccess: false] & {
59
+ error: Extract<TError, AnyORPCError>;
151
60
  data: undefined;
152
- isDefined: true;
61
+ inferableError: Extract<TError, AnyORPCError>;
153
62
  isSuccess: false;
154
63
  };
155
64
  /**
156
- * Works like try/catch, but can infer error types.
65
+ * Works like try/catch, but help you infer the error type if it is inferable ORPCError.
66
+ *
67
+ * @example
68
+ * ```ts
69
+ * const [error, data, inferableError, isSuccess] = await safe(client(...))
70
+ * // or const { error, data, inferableError, isSuccess } = await safe(client(...))
157
71
  *
158
- * @info support both tuple `[error, data, isDefined, isSuccess]` and object `{ error, data, isDefined, isSuccess }` styles.
159
- * @see {@link https://orpc.dev/docs/client/error-handling Client Error Handling Docs}
72
+ * if (inferableError) {
73
+ * console.log(inferableError) // or error, both are well typed
74
+ * }
160
75
  */
161
- declare function safe<TOutput, TError = ThrowableError>(promise: ClientPromiseResult<TOutput, TError>): Promise<SafeResult<TOutput, TError>>;
162
- declare function resolveFriendlyClientOptions<T extends ClientContext>(options: FriendlyClientOptions<T>): ClientOptions<T>;
76
+ declare function safe<TOutput, TError = ThrowableError>(promise: PromiseWithError<TOutput, TError>): Promise<SafeResult<TOutput, TError>>;
163
77
  interface ConsumeEventIteratorOptions<T, TReturn, TError> {
164
78
  /**
165
79
  * Called on each event
@@ -180,18 +94,18 @@ interface ConsumeEventIteratorOptions<T, TReturn, TError> {
180
94
  *
181
95
  * @info If iterator is canceled, `undefined` can be passed on success
182
96
  */
183
- onFinish?: (state: OnFinishState<TReturn | undefined, TError>) => void;
97
+ onFinish?: (state: [error: TError, data: undefined, isSuccess: false] | [error: null, data: TReturn | undefined, isSuccess: true]) => void;
184
98
  }
185
99
  /**
186
100
  * Consumes an event iterator with lifecycle callbacks
187
101
  *
188
- * @warning If no `onError` or `onFinish` is provided, unhandled rejections will be thrown
102
+ * @warning If no `onError` or `onFinish` is provided, error will be thrown into unhandled rejection channel.
189
103
  * @return unsubscribe callback
190
104
  */
191
- declare function consumeEventIterator<T, TReturn, TError = ThrowableError>(iterator: AsyncIterator<T, TReturn> | ClientPromiseResult<AsyncIterator<T, TReturn>, TError>, options: ConsumeEventIteratorOptions<T, TReturn, TError>): () => Promise<void>;
105
+ declare function consumeEventIterator<T, TReturn, TError = ThrowableError>(iterator: AsyncIterator<T, TReturn> | PromiseWithError<AsyncIterator<T, TReturn>, TError>, options: ConsumeEventIteratorOptions<T, TReturn, TError>): () => Promise<void>;
192
106
 
193
- type SafeClient<T extends NestedClient<any>> = T extends Client<infer UContext, infer UInput, infer UOutput, infer UError> ? (...rest: ClientRest<UContext, UInput>) => Promise<SafeResult<UOutput, UError>> : {
194
- [K in keyof T]: T[K] extends NestedClient<any> ? SafeClient<T[K]> : never;
107
+ type SafeClient<T extends AnyNestedClient> = T extends Client<infer UContext, infer UInput, infer UOutput, infer UError> ? (...rest: ClientRest<UContext, UInput>) => Promise<SafeResult<UOutput, UError>> : {
108
+ [K in keyof T]: T[K] extends AnyNestedClient ? SafeClient<T[K]> : never;
195
109
  };
196
110
  /**
197
111
  * Create a safe client that automatically wraps all procedure calls with the `safe` util.
@@ -199,15 +113,24 @@ type SafeClient<T extends NestedClient<any>> = T extends Client<infer UContext,
199
113
  * @example
200
114
  * ```ts
201
115
  * const safeClient = createSafeClient(client)
202
- * const { error, data, isDefined } = await safeClient.doSomething({ id: '123' })
116
+ * const { error, data, inferrableError, isSuccess } = await safeClient.doSomething({ id: '123' })
117
+ * // or const [error, data, inferrableError, isSuccess] = await safeClient.doSomething({ id: '123' })
203
118
  * ```
204
119
  *
205
120
  * @see {@link https://orpc.dev/docs/client/error-handling#using-createsafeclient Safe Client Docs}
206
121
  */
207
- declare function createSafeClient<T extends NestedClient<any>>(client: T): SafeClient<T>;
122
+ declare function createSafeClient<T extends AnyNestedClient>(client: T): SafeClient<T>;
208
123
 
209
- declare const ORPC_CLIENT_PACKAGE_NAME = "@orpc/client";
210
- declare const ORPC_CLIENT_PACKAGE_VERSION = "1.14.5";
124
+ /**
125
+ * Property names that should resolve to the underlying value instead of
126
+ * continuing recursive proxy traversal.
127
+ *
128
+ * These properties are commonly accessed automatically by JavaScript runtimes,
129
+ * language features, or third-party libraries. Returning another recursive
130
+ * proxy for them can cause unexpected behavior, compatibility issues, or
131
+ * infinite proxy chains.
132
+ */
133
+ declare const RECURSIVE_CLIENT_UNWRAP_KEYS: Set<string>;
211
134
 
212
135
  /**
213
136
  * DynamicLink provides a way to dynamically resolve and delegate calls to other ClientLinks
@@ -217,14 +140,16 @@ declare const ORPC_CLIENT_PACKAGE_VERSION = "1.14.5";
217
140
  */
218
141
  declare class DynamicLink<TClientContext extends ClientContext> implements ClientLink<TClientContext> {
219
142
  private readonly linkResolver;
220
- constructor(linkResolver: (options: ClientOptions<TClientContext>, path: readonly string[], input: unknown) => Promisable<ClientLink<TClientContext>>);
221
- call(path: readonly string[], input: unknown, options: ClientOptions<TClientContext>): Promise<unknown>;
143
+ constructor(linkResolver: (options: ClientOptions<TClientContext>, path: string[], input: unknown) => Promisable<ClientLink<TClientContext>>);
144
+ call(path: string[], input: unknown, options: ClientOptions<TClientContext>): Promise<unknown>;
222
145
  }
223
146
 
224
- declare function mapEventIterator<TYield, TReturn, TNext, TMap = TYield | TReturn>(iterator: AsyncIterator<TYield, TReturn, TNext>, maps: {
225
- value: (value: NoInfer<TYield | TReturn>, done: boolean | undefined) => Promise<TMap>;
226
- error: (error: unknown) => Promise<unknown>;
227
- }): AsyncIteratorClass<TMap, TMap, TNext>;
147
+ declare function wrapEventIteratorPreservingMeta<TYield, TReturn, TMappedYield = TYield, TMappedReturn = TReturn>(iterator: AsyncIterator<TYield, TReturn>, { mapResult, mapError, ...rest }: WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>): AsyncIteratorClass<TMappedYield, TMappedReturn>;
148
+
149
+ /**
150
+ * @deprecated Use `isInferableError` instead.
151
+ */
152
+ declare const isDefinedError: typeof isInferableError;
228
153
 
229
- export { COMMON_ORPC_ERROR_DEFS, Client, ClientContext, ClientLink, ClientOptions, ClientPromiseResult, ClientRest, DynamicLink, FriendlyClientOptions, InferClientContext, NestedClient, ORPCError, ORPC_CLIENT_PACKAGE_NAME, ORPC_CLIENT_PACKAGE_VERSION, consumeEventIterator, createORPCClient, createORPCErrorFromJson, createSafeClient, fallbackORPCErrorMessage, fallbackORPCErrorStatus, isDefinedError, isORPCErrorJson, isORPCErrorStatus, mapEventIterator, resolveFriendlyClientOptions, safe, toORPCError };
230
- export type { CommonORPCErrorCode, ConsumeEventIteratorOptions, ORPCErrorCode, ORPCErrorJSON, ORPCErrorOptions, SafeClient, SafeResult, createORPCClientOptions };
154
+ export { AnyNestedClient, AnyORPCError, Client, ClientContext, ClientLink, ClientOptions, ClientRest, DynamicLink, FriendlyClientOptions, InferClientContext, InferClientError, ORPCError, ORPCErrorCode, ORPCErrorJSON, RECURSIVE_CLIENT_UNWRAP_KEYS, cloneORPCError, consumeEventIterator, createORPCClient, createORPCErrorFromJson, createSafeClient, isDefinedError, isInferableError, isORPCErrorJson, resolveClientRest, resolveFriendlyClientOptions, safe, toORPCError, wrapEventIteratorPreservingMeta };
155
+ export type { ConsumeEventIteratorOptions, ORPCClientInterceptor, ORPCClientInterceptorOptions, ORPCClientOptions, ORPCClientScoped, ORPCClientScopedOptions, SafeClient, SafeResult };