@orpc/client 2.0.0-beta.49 → 2.0.0-beta.50

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 (75) hide show
  1. package/dist/adapters/fetch/index.d.ts +3 -2
  2. package/dist/adapters/fetch/index.js +2 -2
  3. package/dist/adapters/fetch/rpc-link.d.ts +8 -8
  4. package/dist/adapters/fetch/rpc-link.js +16 -13
  5. package/dist/adapters/fetch/transport.d.ts +29 -31
  6. package/dist/adapters/fetch/transport.js +49 -63
  7. package/dist/adapters/message-port/index.d.ts +4 -3
  8. package/dist/adapters/message-port/index.js +3 -3
  9. package/dist/adapters/message-port/message-port.d.ts +13 -13
  10. package/dist/adapters/message-port/message-port.js +35 -53
  11. package/dist/adapters/message-port/rpc-link.d.ts +8 -8
  12. package/dist/adapters/message-port/rpc-link.js +17 -14
  13. package/dist/adapters/message-port/transport.d.ts +31 -34
  14. package/dist/adapters/message-port/transport.js +38 -52
  15. package/dist/adapters/standard/codec.d.ts +10 -10
  16. package/dist/adapters/standard/index.d.ts +6 -5
  17. package/dist/adapters/standard/index.js +2 -4
  18. package/dist/adapters/standard/link.d.ts +31 -31
  19. package/dist/adapters/standard/link.js +101 -85
  20. package/dist/adapters/standard/plugin.d.ts +25 -31
  21. package/dist/adapters/standard/plugin.js +14 -16
  22. package/dist/adapters/standard/rpc-link-codec.d.ts +53 -60
  23. package/dist/adapters/standard/rpc-link-codec.js +98 -102
  24. package/dist/adapters/standard/transport.d.ts +7 -7
  25. package/dist/adapters/websocket/index.d.ts +3 -2
  26. package/dist/adapters/websocket/index.js +2 -2
  27. package/dist/adapters/websocket/rpc-link.d.ts +8 -8
  28. package/dist/adapters/websocket/rpc-link.js +16 -13
  29. package/dist/adapters/websocket/transport.d.ts +101 -100
  30. package/dist/adapters/websocket/transport.js +102 -130
  31. package/dist/async-iterator-object.d.ts +2 -2
  32. package/dist/async-iterator-object.js +27 -28
  33. package/dist/client-safe.d.ts +4 -6
  34. package/dist/client-safe.js +29 -34
  35. package/dist/client.d.ts +24 -26
  36. package/dist/client.js +35 -37
  37. package/dist/consts.d.ts +1 -1
  38. package/dist/consts.js +18 -41
  39. package/dist/dynamic-link.d.ts +6 -6
  40. package/dist/dynamic-link.js +16 -16
  41. package/dist/error-utils.d.ts +3 -4
  42. package/dist/error-utils.js +47 -51
  43. package/dist/error.d.ts +79 -79
  44. package/dist/error.js +154 -166
  45. package/dist/index.d.ts +14 -53
  46. package/dist/index.js +12 -40
  47. package/dist/plugins/batch.d.ts +122 -155
  48. package/dist/plugins/batch.js +320 -391
  49. package/dist/plugins/cookie-jar.d.ts +64 -61
  50. package/dist/plugins/cookie-jar.js +208 -245
  51. package/dist/plugins/dedupe.d.ts +49 -53
  52. package/dist/plugins/dedupe.js +168 -211
  53. package/dist/plugins/index.d.ts +9 -28
  54. package/dist/plugins/index.js +8 -23
  55. package/dist/plugins/request-compression.d.ts +38 -35
  56. package/dist/plugins/request-compression.js +131 -177
  57. package/dist/plugins/response-compression.d.ts +21 -18
  58. package/dist/plugins/response-compression.js +64 -88
  59. package/dist/plugins/retry-after.d.ts +31 -38
  60. package/dist/plugins/retry-after.js +60 -85
  61. package/dist/plugins/retry.d.ts +55 -55
  62. package/dist/plugins/retry.js +118 -137
  63. package/dist/plugins/timeout.d.ts +19 -17
  64. package/dist/plugins/timeout.js +41 -36
  65. package/dist/rpc-json-serializer.d.ts +84 -84
  66. package/dist/rpc-json-serializer.js +338 -383
  67. package/dist/rpc-serializer.d.ts +20 -21
  68. package/dist/rpc-serializer.js +97 -125
  69. package/dist/types.d.ts +19 -31
  70. package/dist/utils.d.ts +18 -29
  71. package/dist/utils.js +63 -47
  72. package/package.json +5 -5
  73. package/dist/adapters/standard/codec.js +0 -1
  74. package/dist/adapters/standard/transport.js +0 -1
  75. package/dist/types.js +0 -1
@@ -1,133 +1,105 @@
1
- import { AbortError, loadBytes, promiseWithResolvers, runWithSignal, sequential, sleep, toStringOrBytes, } from '@orpc/shared';
2
- import { ClientPeer, decodePeerMessage, encodePeerMessage, isServerPeerSendMessage, } from '@standard-server/peer';
1
+ import { AbortError, loadBytes, promiseWithResolvers, runWithSignal, sequential, sleep, toStringOrBytes } from "@orpc/shared";
2
+ import { ClientPeer, decodePeerMessage, encodePeerMessage, isServerPeerSendMessage } from "@standard-server/peer";
3
+ // src/adapters/websocket/transport.ts
3
4
  /**
4
- * Some env maybe not available WebSocket global, like node 20
5
- */
5
+ * Some env maybe not available WebSocket global, like node 20
6
+ */
6
7
  const WEBSOCKET_CONNECTING = 0;
7
8
  const WEBSOCKET_OPEN = 1;
8
- export class WebSocketLinkTransport {
9
- connect;
10
- reconnectEnabled;
11
- reconnectDelay;
12
- reconnectMaxAttempt;
13
- reconnectMaxTotalAttempt;
14
- reconnectOnCloseEnabled;
15
- reconnectOnCloseDelay;
16
- encodePeerMessageOptions;
17
- decodePeerMessageOptions;
18
- constructor(options) {
19
- this.connect = options.connect;
20
- const reconnect = typeof options.reconnect === 'object' ? options.reconnect : {};
21
- const onClose = typeof reconnect.onClose === 'object' ? reconnect.onClose : {};
22
- this.reconnectEnabled = options.reconnect !== undefined && options.reconnect !== false;
23
- this.reconnectDelay = reconnect.delay ?? ((info) => (info.attempt === 1 ? 0 : 2_000));
24
- this.reconnectMaxAttempt = reconnect.maxAttempt ?? Infinity;
25
- this.reconnectMaxTotalAttempt = reconnect.maxTotalAttempt ?? Infinity;
26
- this.reconnectOnCloseEnabled =
27
- this.reconnectEnabled && reconnect.onClose !== undefined && reconnect.onClose !== false;
28
- this.reconnectOnCloseDelay = onClose.delay ?? 0;
29
- this.encodePeerMessageOptions = options.encodePeerMessage;
30
- this.decodePeerMessageOptions = options.decodePeerMessage;
31
- if (options.connectOnInit) {
32
- this.getConnectedPeer().catch(() => { });
33
- }
34
- }
35
- async send(standardRequest, _path, _options) {
36
- const peer = await runWithSignal(standardRequest.signal, () => this.getConnectedPeer());
37
- return peer.request(standardRequest);
38
- }
39
- totalAttempt = 0;
40
- attempt = 0;
41
- current;
42
- async getConnectedPeer() {
43
- const current = this.current;
44
- const resolved = await current;
45
- if (resolved && (!this.reconnectEnabled || resolved.websocket.readyState === WEBSOCKET_OPEN)) {
46
- return resolved.peer;
47
- }
48
- if (current !== this.current) {
49
- return this.getConnectedPeer();
50
- }
51
- if (this.totalAttempt >= this.reconnectMaxTotalAttempt) {
52
- throw new AbortError(`WebSocket reconnect stopped after ${this.totalAttempt} total attempt(s)`);
53
- }
54
- this.current = (async () => {
55
- this.totalAttempt += 1;
56
- this.attempt += 1;
57
- const info = {
58
- totalAttempt: this.totalAttempt,
59
- attempt: this.attempt,
60
- };
61
- await sleep(this.reconnectDelay(info));
62
- const websocket = await this.connect(info);
63
- if (websocket.readyState !== WEBSOCKET_CONNECTING &&
64
- websocket.readyState !== WEBSOCKET_OPEN) {
65
- throw new AbortError('WebSocket is already closing or closed');
66
- }
67
- let closeReason;
68
- const peer = new ClientPeer(async (message) => {
69
- // `send` silently discards data once the socket is closed, so requests would never settle
70
- if (closeReason) {
71
- throw closeReason;
72
- }
73
- const encoded = await encodePeerMessage(message, this.encodePeerMessageOptions);
74
- return websocket.send(encoded);
75
- });
76
- let connectingResolvers;
77
- if (websocket.readyState === WEBSOCKET_CONNECTING) {
78
- connectingResolvers = promiseWithResolvers();
79
- websocket.addEventListener('open', () => {
80
- connectingResolvers?.resolve();
81
- });
82
- }
83
- /**
84
- * Message order is important: loading -> decode -> .message.
85
- * This flow must stay synchronous, or we need to use `sequential` helper
86
- */
87
- websocket.addEventListener('message', sequential(async (event) => {
88
- // For better compatibility avoid control or depend on websocket.binaryType
89
- const message = event.data instanceof Blob ? await loadBytes(event.data) : toStringOrBytes(event.data);
90
- const result = decodePeerMessage(message, this.decodePeerMessageOptions);
91
- if (result.matched && isServerPeerSendMessage(result.message)) {
92
- // Not awaited: `peer.message` runs handling message may be slow,
93
- // and awaiting it would block decoding of subsequent messages.
94
- void peer.message(result.message);
95
- }
96
- }));
97
- websocket.addEventListener('close', async (event) => {
98
- closeReason = new AbortError(`WebSocket closed (code ${event.code}: ${event.reason})`);
99
- connectingResolvers?.resolve();
100
- await peer.close(closeReason);
101
- });
102
- // EventEmitter-based implementations like `ws` throw an unhandled `error` event,
103
- // so a refused connection or malformed frame would crash the process. `close` always follows and handles cleanup.
104
- websocket.addEventListener('error', () => { });
105
- await connectingResolvers?.promise;
106
- if (closeReason) {
107
- throw closeReason;
108
- }
109
- if (this.reconnectOnCloseEnabled) {
110
- websocket.addEventListener('close', () => {
111
- sleep(this.reconnectOnCloseDelay)
112
- .then(() => this.getConnectedPeer())
113
- .catch(() => { });
114
- });
115
- }
116
- this.attempt = 0;
117
- return { websocket, peer };
118
- })().catch((error) => {
119
- if (!this.reconnectEnabled) {
120
- throw error;
121
- }
122
- if (this.attempt >= this.reconnectMaxAttempt) {
123
- const attempt = this.attempt;
124
- this.attempt = 0;
125
- this.current = undefined;
126
- throw new AbortError(`WebSocket reconnect failed after ${attempt} attempt(s)`, {
127
- cause: error,
128
- });
129
- }
130
- });
131
- return this.getConnectedPeer();
132
- }
133
- }
9
+ var WebSocketLinkTransport = class {
10
+ connect;
11
+ reconnectEnabled;
12
+ reconnectDelay;
13
+ reconnectMaxAttempt;
14
+ reconnectMaxTotalAttempt;
15
+ reconnectOnCloseEnabled;
16
+ reconnectOnCloseDelay;
17
+ encodePeerMessageOptions;
18
+ decodePeerMessageOptions;
19
+ constructor(options) {
20
+ this.connect = options.connect;
21
+ const reconnect = typeof options.reconnect === "object" ? options.reconnect : {};
22
+ const onClose = typeof reconnect.onClose === "object" ? reconnect.onClose : {};
23
+ this.reconnectEnabled = options.reconnect !== void 0 && options.reconnect !== false;
24
+ this.reconnectDelay = reconnect.delay ?? ((info) => info.attempt === 1 ? 0 : 2e3);
25
+ this.reconnectMaxAttempt = reconnect.maxAttempt ?? Infinity;
26
+ this.reconnectMaxTotalAttempt = reconnect.maxTotalAttempt ?? Infinity;
27
+ this.reconnectOnCloseEnabled = this.reconnectEnabled && reconnect.onClose !== void 0 && reconnect.onClose !== false;
28
+ this.reconnectOnCloseDelay = onClose.delay ?? 0;
29
+ this.encodePeerMessageOptions = options.encodePeerMessage;
30
+ this.decodePeerMessageOptions = options.decodePeerMessage;
31
+ if (options.connectOnInit) this.getConnectedPeer().catch(() => {});
32
+ }
33
+ async send(standardRequest, _path, _options) {
34
+ return (await runWithSignal(standardRequest.signal, () => this.getConnectedPeer())).request(standardRequest);
35
+ }
36
+ totalAttempt = 0;
37
+ attempt = 0;
38
+ current;
39
+ async getConnectedPeer() {
40
+ const current = this.current;
41
+ const resolved = await current;
42
+ if (resolved && (!this.reconnectEnabled || resolved.websocket.readyState === WEBSOCKET_OPEN)) return resolved.peer;
43
+ if (current !== this.current) return this.getConnectedPeer();
44
+ if (this.totalAttempt >= this.reconnectMaxTotalAttempt) throw new AbortError(`WebSocket reconnect stopped after ${this.totalAttempt} total attempt(s)`);
45
+ this.current = (async () => {
46
+ this.totalAttempt += 1;
47
+ this.attempt += 1;
48
+ const info = {
49
+ totalAttempt: this.totalAttempt,
50
+ attempt: this.attempt
51
+ };
52
+ await sleep(this.reconnectDelay(info));
53
+ const websocket = await this.connect(info);
54
+ if (websocket.readyState !== WEBSOCKET_CONNECTING && websocket.readyState !== WEBSOCKET_OPEN) throw new AbortError("WebSocket is already closing or closed");
55
+ let closeReason;
56
+ const peer = new ClientPeer(async (message) => {
57
+ if (closeReason) throw closeReason;
58
+ const encoded = await encodePeerMessage(message, this.encodePeerMessageOptions);
59
+ return websocket.send(encoded);
60
+ });
61
+ let connectingResolvers;
62
+ if (websocket.readyState === WEBSOCKET_CONNECTING) {
63
+ connectingResolvers = promiseWithResolvers();
64
+ websocket.addEventListener("open", () => {
65
+ connectingResolvers?.resolve();
66
+ });
67
+ }
68
+ /**
69
+ * Message order is important: loading -> decode -> .message.
70
+ * This flow must stay synchronous, or we need to use `sequential` helper
71
+ */
72
+ websocket.addEventListener("message", sequential(async (event) => {
73
+ const message = event.data instanceof Blob ? await loadBytes(event.data) : toStringOrBytes(event.data);
74
+ const result = decodePeerMessage(message, this.decodePeerMessageOptions);
75
+ if (result.matched && isServerPeerSendMessage(result.message)) peer.message(result.message);
76
+ }));
77
+ websocket.addEventListener("close", async (event) => {
78
+ closeReason = new AbortError(`WebSocket closed (code ${event.code}: ${event.reason})`);
79
+ connectingResolvers?.resolve();
80
+ await peer.close(closeReason);
81
+ });
82
+ websocket.addEventListener("error", () => {});
83
+ await connectingResolvers?.promise;
84
+ if (closeReason) throw closeReason;
85
+ if (this.reconnectOnCloseEnabled) websocket.addEventListener("close", () => {
86
+ sleep(this.reconnectOnCloseDelay).then(() => this.getConnectedPeer()).catch(() => {});
87
+ });
88
+ this.attempt = 0;
89
+ return {
90
+ websocket,
91
+ peer
92
+ };
93
+ })().catch((error) => {
94
+ if (!this.reconnectEnabled) throw error;
95
+ if (this.attempt >= this.reconnectMaxAttempt) {
96
+ const attempt = this.attempt;
97
+ this.attempt = 0;
98
+ this.current = void 0;
99
+ throw new AbortError(`WebSocket reconnect failed after ${attempt} attempt(s)`, { cause: error });
100
+ }
101
+ });
102
+ return this.getConnectedPeer();
103
+ }
104
+ };
105
+ export { WebSocketLinkTransport };
@@ -1,2 +1,2 @@
1
- import type { AsyncIteratorClass, WrapAsyncIteratorOptions } from '@orpc/shared';
2
- export declare function wrapAsyncIteratorPreservingEventMeta<TYield, TReturn, TMappedYield = TYield, TMappedReturn = TReturn>(iterator: AsyncIterator<TYield, TReturn>, { mapResult, mapError, ...rest }: WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>): AsyncIteratorClass<TMappedYield, TMappedReturn>;
1
+ import { AsyncIteratorClass, WrapAsyncIteratorOptions } from "@orpc/shared";
2
+ export declare function wrapAsyncIteratorPreservingEventMeta<TYield, TReturn, TMappedYield = TYield, TMappedReturn = TReturn>(iterator: AsyncIterator<TYield, TReturn>, { mapResult, mapError, ...rest }: WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>): AsyncIteratorClass<TMappedYield, TMappedReturn>;
@@ -1,29 +1,28 @@
1
- import { isNonPrimitive, wrapAsyncIterator } from '@orpc/shared';
2
- import { getEventMeta, withEventMeta } from '@standard-server/core';
3
- export function wrapAsyncIteratorPreservingEventMeta(iterator, { mapResult, mapError, ...rest }) {
4
- return wrapAsyncIterator(iterator, {
5
- ...rest,
6
- mapResult: mapResult &&
7
- (async (result) => {
8
- const mapped = await mapResult(result);
9
- if (mapped.value !== result.value) {
10
- const meta = getEventMeta(result.value);
11
- if (meta && isNonPrimitive(mapped.value)) {
12
- return { done: mapped.done, value: withEventMeta(mapped.value, meta) };
13
- }
14
- }
15
- return mapped;
16
- }),
17
- mapError: mapError &&
18
- (async (error) => {
19
- const mapped = await mapError(error);
20
- if (mapped !== error) {
21
- const meta = getEventMeta(error);
22
- if (meta && isNonPrimitive(mapped)) {
23
- return withEventMeta(mapped, meta);
24
- }
25
- }
26
- return mapped;
27
- }),
28
- });
1
+ import { isNonPrimitive, wrapAsyncIterator } from "@orpc/shared";
2
+ import { getEventMeta, withEventMeta } from "@standard-server/core";
3
+ // src/async-iterator-object.ts
4
+ function wrapAsyncIteratorPreservingEventMeta(iterator, { mapResult, mapError, ...rest }) {
5
+ return wrapAsyncIterator(iterator, {
6
+ ...rest,
7
+ mapResult: mapResult && (async (result) => {
8
+ const mapped = await mapResult(result);
9
+ if (mapped.value !== result.value) {
10
+ const meta = getEventMeta(result.value);
11
+ if (meta && isNonPrimitive(mapped.value)) return {
12
+ done: mapped.done,
13
+ value: withEventMeta(mapped.value, meta)
14
+ };
15
+ }
16
+ return mapped;
17
+ }),
18
+ mapError: mapError && (async (error) => {
19
+ const mapped = await mapError(error);
20
+ if (mapped !== error) {
21
+ const meta = getEventMeta(error);
22
+ if (meta && isNonPrimitive(mapped)) return withEventMeta(mapped, meta);
23
+ }
24
+ return mapped;
25
+ })
26
+ });
29
27
  }
28
+ export { wrapAsyncIteratorPreservingEventMeta };
@@ -1,8 +1,6 @@
1
- import type { AnyNestedClient, Client, ClientRest } from './types.ts';
2
- import type { SafeResult } from './utils.ts';
3
- export type SafeClient<T extends AnyNestedClient> = T extends Client<infer UContext, infer UInput, infer UOutput, infer UError> ? (...rest: ClientRest<UContext, UInput>) => Promise<SafeResult<UOutput, UError>> : {
4
- [K in keyof T]: T[K] extends AnyNestedClient ? SafeClient<T[K]> : never;
5
- };
1
+ import { AnyNestedClient, Client, ClientRest } from "./types.js";
2
+ import { SafeResult } from "./utils.js";
3
+ export type SafeClient<T extends AnyNestedClient> = T extends Client<infer UContext, infer UInput, infer UOutput, infer UError> ? (...rest: ClientRest<UContext, UInput>) => Promise<SafeResult<UOutput, UError>> : { [K in keyof T]: T[K] extends AnyNestedClient ? SafeClient<T[K]> : never; };
6
4
  /**
7
5
  * Create a safe client that automatically wraps all procedure calls with the `safe` util.
8
6
  *
@@ -15,4 +13,4 @@ export type SafeClient<T extends AnyNestedClient> = T extends Client<infer UCont
15
13
  *
16
14
  * @see {@link https://orpc.dev/docs/client/error-handling#safe-client | Client Error Handling - Safe Client}
17
15
  */
18
- export declare function createSafeClient<T extends AnyNestedClient>(client: T): SafeClient<T>;
16
+ export declare function createSafeClient<T extends AnyNestedClient>(client: T): SafeClient<T>;
@@ -1,36 +1,31 @@
1
- import { isNonPrimitive } from '@orpc/shared';
2
- import { RECURSIVE_CLIENT_UNWRAP_KEYS } from './consts.js';
3
- import { safe } from './utils.js';
1
+ import { RECURSIVE_CLIENT_UNWRAP_KEYS } from "./consts.js";
2
+ import { safe } from "./utils.js";
3
+ import { isNonPrimitive } from "@orpc/shared";
4
+ // src/client-safe.ts
4
5
  /**
5
- * Create a safe client that automatically wraps all procedure calls with the `safe` util.
6
- *
7
- * @example
8
- * ```ts
9
- * const safeClient = createSafeClient(client)
10
- * const { error, data, definedError, isSuccess } = await safeClient.doSomething({ id: '123' })
11
- * // or const [error, data, definedError, isSuccess] = await safeClient.doSomething({ id: '123' })
12
- * ```
13
- *
14
- * @see {@link https://orpc.dev/docs/client/error-handling#safe-client | Client Error Handling - Safe Client}
15
- */
16
- export function createSafeClient(client) {
17
- const cache = new Map();
18
- const proxy = new Proxy((...args) => safe(client(...args)), {
19
- get(target, prop) {
20
- if (typeof prop !== 'string' || RECURSIVE_CLIENT_UNWRAP_KEYS.has(prop)) {
21
- return Reflect.get(target, prop);
22
- }
23
- let safeClient = cache.get(prop);
24
- if (safeClient === undefined) {
25
- const value = client[prop];
26
- if (!isNonPrimitive(value)) {
27
- return value;
28
- }
29
- safeClient = createSafeClient(value);
30
- cache.set(prop, safeClient);
31
- }
32
- return safeClient;
33
- },
34
- });
35
- return proxy;
6
+ * Create a safe client that automatically wraps all procedure calls with the `safe` util.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * const safeClient = createSafeClient(client)
11
+ * const { error, data, definedError, isSuccess } = await safeClient.doSomething({ id: '123' })
12
+ * // or const [error, data, definedError, isSuccess] = await safeClient.doSomething({ id: '123' })
13
+ * ```
14
+ *
15
+ * @see {@link https://orpc.dev/docs/client/error-handling#safe-client | Client Error Handling - Safe Client}
16
+ */
17
+ function createSafeClient(client) {
18
+ const cache = /* @__PURE__ */ new Map();
19
+ return new Proxy((...args) => safe(client(...args)), { get(target, prop) {
20
+ if (typeof prop !== "string" || RECURSIVE_CLIENT_UNWRAP_KEYS.has(prop)) return Reflect.get(target, prop);
21
+ let safeClient = cache.get(prop);
22
+ if (safeClient === void 0) {
23
+ const value = client[prop];
24
+ if (!isNonPrimitive(value)) return value;
25
+ safeClient = createSafeClient(value);
26
+ cache.set(prop, safeClient);
27
+ }
28
+ return safeClient;
29
+ } });
36
30
  }
31
+ export { createSafeClient };
package/dist/client.d.ts CHANGED
@@ -1,34 +1,32 @@
1
- import type { Interceptor, PromiseWithError } from '@orpc/shared';
2
- import type { AnyNestedClient, Client, ClientContext, ClientLink, ClientOptions, InferClientContext, InferClientError } from './types.ts';
1
+ import { AnyNestedClient, Client, ClientContext, ClientLink, ClientOptions, InferClientContext, InferClientError } from "./types.js";
2
+ import { Interceptor, PromiseWithError } from "@orpc/shared";
3
3
  export interface ORPCClientInterceptorOptions<TClientContext extends ClientContext, TInput> extends ClientOptions<TClientContext> {
4
- path: string[];
5
- input: TInput;
4
+ path: string[];
5
+ input: TInput;
6
6
  }
7
7
  export type ORPCClientInterceptor<TClientContext extends ClientContext, TInput, TOutput, TError> = Interceptor<ORPCClientInterceptorOptions<TClientContext, TInput>, PromiseWithError<TOutput, TError>>;
8
8
  export interface ORPCClientScopedOptions<TClientContext extends ClientContext, TInput, TOutput, TError> {
9
- /**
10
- * Interceptors that wrap the entire client call lifecycle.
11
- */
12
- interceptors?: ORPCClientInterceptor<TClientContext, TInput, TOutput, TError>[] | undefined;
9
+ /**
10
+ * Interceptors that wrap the entire client call lifecycle.
11
+ */
12
+ interceptors?: ORPCClientInterceptor<TClientContext, TInput, TOutput, TError>[] | undefined;
13
13
  }
14
- export type ORPCClientScoped<T extends AnyNestedClient> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? ORPCClientScopedOptions<UClientContext, UInput, UOutput, UError> : {
15
- [K in keyof T]?: (T[K] extends AnyNestedClient ? ORPCClientScoped<T[K]> : never) | undefined;
16
- };
14
+ export type ORPCClientScoped<T extends AnyNestedClient> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? ORPCClientScopedOptions<UClientContext, UInput, UOutput, UError> : { [K in keyof T]?: (T[K] extends AnyNestedClient ? ORPCClientScoped<T[K]> : never) | undefined; };
17
15
  export interface ORPCClientOptions<T extends AnyNestedClient> {
18
- /**
19
- * Use as base path for all procedure, useful when you only want to call a subset of the procedure.
20
- */
21
- path?: string[] | undefined;
22
- /**
23
- * Interceptors that wrap the entire client call lifecycle, applied to every procedure call.
24
- */
25
- interceptors?: ORPCClientInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
26
- /**
27
- * Per-procedure options following the shape of the router.
28
- * Allows fine-grained configuration (e.g. additional interceptors) for individual procedures
29
- * without affecting the rest of the router.
30
- */
31
- scoped?: ORPCClientScoped<T> | undefined;
16
+ /**
17
+ * Use as base path for all procedure, useful when you only want to call a subset of the procedure.
18
+ */
19
+ path?: string[] | undefined;
20
+ /**
21
+ * Interceptors that wrap the entire client call lifecycle, applied to every procedure call.
22
+ */
23
+ interceptors?: ORPCClientInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
24
+ /**
25
+ * Per-procedure options following the shape of the router.
26
+ * Allows fine-grained configuration (e.g. additional interceptors) for individual procedures
27
+ * without affecting the rest of the router.
28
+ */
29
+ scoped?: ORPCClientScoped<T> | undefined;
32
30
  }
33
31
  /**
34
32
  * Creates a fully typed oRPC client from a link.
@@ -37,4 +35,4 @@ export interface ORPCClientOptions<T extends AnyNestedClient> {
37
35
  *
38
36
  * @see {@link https://orpc.dev/docs/client/client-side | Client-Side Clients}
39
37
  */
40
- export declare function createORPCClient<T extends AnyNestedClient>(link: ClientLink<InferClientContext<T>>, { path, ...options }?: NoInfer<ORPCClientOptions<T>>): T;
38
+ export declare function createORPCClient<T extends AnyNestedClient>(link: ClientLink<InferClientContext<T>>, { path, ...options }?: NoInfer<ORPCClientOptions<T>>): T;
package/dist/client.js CHANGED
@@ -1,39 +1,37 @@
1
- import { intercept, toArray } from '@orpc/shared';
2
- import { RECURSIVE_CLIENT_UNWRAP_KEYS } from './consts.js';
3
- import { resolveClientRest } from './utils.js';
1
+ import { RECURSIVE_CLIENT_UNWRAP_KEYS } from "./consts.js";
2
+ import { resolveClientRest } from "./utils.js";
3
+ import { intercept, toArray } from "@orpc/shared";
4
+ // src/client.ts
4
5
  /**
5
- * Creates a fully typed oRPC client from a link.
6
- * The returned client mirrors the shape of your router or contract,
7
- * so calling a procedure is as simple as calling a function.
8
- *
9
- * @see {@link https://orpc.dev/docs/client/client-side | Client-Side Clients}
10
- */
11
- export function createORPCClient(link, { path = [], ...options } = {}) {
12
- const procedureClient = (...rest) => {
13
- const [input, callOptions] = resolveClientRest(rest);
14
- const interceptors = [
15
- ...toArray(options.interceptors),
16
- ...toArray(options.scoped?.interceptors),
17
- ];
18
- return intercept(interceptors, { ...callOptions, input, path }, ({ path, input, ...callOptions }) => link.call(path, input, callOptions));
19
- };
20
- const cache = new Map();
21
- const recursive = new Proxy(procedureClient, {
22
- get(target, key) {
23
- if (typeof key !== 'string' || RECURSIVE_CLIENT_UNWRAP_KEYS.has(key)) {
24
- return Reflect.get(target, key);
25
- }
26
- let client = cache.get(key);
27
- if (client === undefined) {
28
- client = createORPCClient(link, {
29
- ...options,
30
- path: [...path, key],
31
- scoped: options.scoped?.[key],
32
- });
33
- cache.set(key, client);
34
- }
35
- return client;
36
- },
37
- });
38
- return recursive;
6
+ * Creates a fully typed oRPC client from a link.
7
+ * The returned client mirrors the shape of your router or contract,
8
+ * so calling a procedure is as simple as calling a function.
9
+ *
10
+ * @see {@link https://orpc.dev/docs/client/client-side | Client-Side Clients}
11
+ */
12
+ function createORPCClient(link, { path = [], ...options } = {}) {
13
+ const procedureClient = (...rest) => {
14
+ const [input, callOptions] = resolveClientRest(rest);
15
+ const interceptors = [...toArray(options.interceptors), ...toArray(options.scoped?.interceptors)];
16
+ return intercept(interceptors, {
17
+ ...callOptions,
18
+ input,
19
+ path
20
+ }, ({ path, input, ...callOptions }) => link.call(path, input, callOptions));
21
+ };
22
+ const cache = /* @__PURE__ */ new Map();
23
+ return new Proxy(procedureClient, { get(target, key) {
24
+ if (typeof key !== "string" || RECURSIVE_CLIENT_UNWRAP_KEYS.has(key)) return Reflect.get(target, key);
25
+ let client = cache.get(key);
26
+ if (client === void 0) {
27
+ client = createORPCClient(link, {
28
+ ...options,
29
+ path: [...path, key],
30
+ scoped: options.scoped?.[key]
31
+ });
32
+ cache.set(key, client);
33
+ }
34
+ return client;
35
+ } });
39
36
  }
37
+ export { createORPCClient };
package/dist/consts.d.ts CHANGED
@@ -7,4 +7,4 @@
7
7
  * proxy for them can cause unexpected behavior, compatibility issues, or
8
8
  * infinite proxy chains.
9
9
  */
10
- export declare const RECURSIVE_CLIENT_UNWRAP_KEYS: Set<PropertyKey>;
10
+ export declare const RECURSIVE_CLIENT_UNWRAP_KEYS: Set<PropertyKey>;
package/dist/consts.js CHANGED
@@ -1,43 +1,20 @@
1
+ // src/consts.ts
1
2
  /**
2
- * Property names that should resolve to the underlying value instead of
3
- * continuing recursive proxy traversal.
4
- *
5
- * These properties are commonly accessed automatically by JavaScript runtimes,
6
- * language features, or third-party libraries. Returning another recursive
7
- * proxy for them can cause unexpected behavior, compatibility issues, or
8
- * infinite proxy chains.
9
- */
10
- export const RECURSIVE_CLIENT_UNWRAP_KEYS = /* @__PURE__ */ new Set([
11
- /**
12
- * Prevents the client from being treated as a thenable when users
13
- * accidentally write `await client`.
14
- */
15
- 'then',
16
- /**
17
- * Commonly used by libraries to bind functions to a specific `this`
18
- * context.
19
- */
20
- 'bind',
21
- /**
22
- * Commonly used by libraries to invoke functions with a specific `this`
23
- * context.
24
- */
25
- 'call',
26
- /**
27
- * Commonly used by libraries to invoke functions with a specific `this`
28
- * context and an arguments array.
29
- */
30
- 'apply',
31
- /**
32
- * Commonly accessed during primitive conversion, inspection, and logging.
33
- */
34
- 'valueOf',
35
- /**
36
- * Commonly accessed during string conversion, inspection, and logging.
37
- */
38
- 'toString',
39
- /**
40
- * Commonly accessed by serializers such as `JSON.stringify`.
41
- */
42
- 'toJSON',
3
+ * Property names that should resolve to the underlying value instead of
4
+ * continuing recursive proxy traversal.
5
+ *
6
+ * These properties are commonly accessed automatically by JavaScript runtimes,
7
+ * language features, or third-party libraries. Returning another recursive
8
+ * proxy for them can cause unexpected behavior, compatibility issues, or
9
+ * infinite proxy chains.
10
+ */
11
+ const RECURSIVE_CLIENT_UNWRAP_KEYS = /* @__PURE__ */ new Set([
12
+ "then",
13
+ "bind",
14
+ "call",
15
+ "apply",
16
+ "valueOf",
17
+ "toString",
18
+ "toJSON"
43
19
  ]);
20
+ export { RECURSIVE_CLIENT_UNWRAP_KEYS };
@@ -1,5 +1,5 @@
1
- import type { Promisable } from '@orpc/shared';
2
- import type { ClientContext, ClientLink, ClientOptions } from './types.ts';
1
+ import { ClientContext, ClientLink, ClientOptions } from "./types.js";
2
+ import { Promisable } from "@orpc/shared";
3
3
  /**
4
4
  * DynamicLink provides a way to dynamically resolve and delegate calls to other ClientLinks
5
5
  * based on the request path, input, and context.
@@ -7,7 +7,7 @@ import type { ClientContext, ClientLink, ClientOptions } from './types.ts';
7
7
  * @see {@link https://orpc.dev/docs/client/dynamic-link | DynamicLink}
8
8
  */
9
9
  export declare class DynamicLink<TClientContext extends ClientContext> implements ClientLink<TClientContext> {
10
- private readonly linkResolver;
11
- constructor(linkResolver: (options: ClientOptions<TClientContext>, path: string[], input: unknown) => Promisable<ClientLink<TClientContext>>);
12
- call(path: string[], input: unknown, options: ClientOptions<TClientContext>): Promise<unknown>;
13
- }
10
+ private readonly linkResolver;
11
+ constructor(linkResolver: (options: ClientOptions<TClientContext>, path: string[], input: unknown) => Promisable<ClientLink<TClientContext>>);
12
+ call(path: string[], input: unknown, options: ClientOptions<TClientContext>): Promise<unknown>;
13
+ }