@orpc/client 2.0.0-beta.5 → 2.0.0-beta.51

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 (94) hide show
  1. package/README.md +139 -102
  2. package/dist/adapters/fetch/index.d.ts +3 -65
  3. package/dist/adapters/fetch/index.js +2 -0
  4. package/dist/adapters/fetch/rpc-link.d.ts +14 -0
  5. package/dist/adapters/fetch/rpc-link.js +17 -0
  6. package/dist/adapters/fetch/transport.d.ts +32 -0
  7. package/dist/adapters/fetch/transport.js +51 -0
  8. package/dist/adapters/message-port/index.d.ts +4 -75
  9. package/dist/adapters/message-port/index.js +3 -0
  10. package/dist/adapters/message-port/message-port.d.ts +29 -0
  11. package/dist/adapters/message-port/message-port.js +38 -0
  12. package/dist/adapters/message-port/rpc-link.d.ts +15 -0
  13. package/dist/adapters/message-port/rpc-link.js +18 -0
  14. package/dist/adapters/message-port/transport.d.ts +35 -0
  15. package/dist/adapters/message-port/transport.js +38 -0
  16. package/dist/adapters/standard/codec.d.ts +14 -0
  17. package/dist/adapters/standard/index.d.ts +6 -61
  18. package/dist/adapters/standard/index.js +2 -0
  19. package/dist/adapters/standard/link.d.ts +40 -0
  20. package/dist/adapters/standard/link.js +101 -0
  21. package/dist/adapters/standard/plugin.d.ts +26 -0
  22. package/dist/adapters/standard/plugin.js +14 -0
  23. package/dist/adapters/standard/rpc-link-codec.d.ts +56 -0
  24. package/dist/adapters/standard/rpc-link-codec.js +100 -0
  25. package/dist/adapters/standard/transport.d.ts +14 -0
  26. package/dist/adapters/websocket/index.d.ts +3 -121
  27. package/dist/adapters/websocket/index.js +2 -0
  28. package/dist/adapters/websocket/rpc-link.d.ts +14 -0
  29. package/dist/adapters/websocket/rpc-link.js +17 -0
  30. package/dist/adapters/websocket/transport.d.ts +116 -0
  31. package/dist/adapters/websocket/transport.js +105 -0
  32. package/dist/async-iterator-object.d.ts +2 -0
  33. package/dist/async-iterator-object.js +28 -0
  34. package/dist/client-safe.d.ts +17 -0
  35. package/dist/client-safe.js +31 -0
  36. package/dist/client.d.ts +39 -0
  37. package/dist/client.js +37 -0
  38. package/dist/consts.d.ts +10 -0
  39. package/dist/consts.js +20 -0
  40. package/dist/dynamic-link.d.ts +13 -0
  41. package/dist/dynamic-link.js +17 -0
  42. package/dist/error-utils.d.ts +20 -0
  43. package/dist/error-utils.js +54 -0
  44. package/dist/error.d.ts +141 -0
  45. package/dist/error.js +166 -0
  46. package/dist/index.d.ts +14 -155
  47. package/dist/index.js +12 -0
  48. package/dist/plugins/batch.d.ts +152 -0
  49. package/dist/plugins/batch.js +330 -0
  50. package/dist/plugins/cookie-jar.d.ts +85 -0
  51. package/dist/plugins/cookie-jar.js +231 -0
  52. package/dist/plugins/dedupe.d.ts +60 -0
  53. package/dist/plugins/dedupe.js +183 -0
  54. package/dist/plugins/index.d.ts +9 -242
  55. package/dist/plugins/index.js +8 -0
  56. package/dist/plugins/request-compression.d.ts +47 -0
  57. package/dist/plugins/request-compression.js +132 -0
  58. package/dist/plugins/response-compression.d.ts +31 -0
  59. package/dist/plugins/response-compression.js +67 -0
  60. package/dist/plugins/retry-after.d.ts +43 -0
  61. package/dist/plugins/retry-after.js +63 -0
  62. package/dist/plugins/retry.d.ts +84 -0
  63. package/dist/plugins/retry.js +121 -0
  64. package/dist/plugins/timeout.d.ts +27 -0
  65. package/dist/plugins/timeout.js +42 -0
  66. package/dist/rpc-json-serializer.d.ts +99 -0
  67. package/dist/rpc-json-serializer.js +347 -0
  68. package/dist/rpc-serializer.d.ts +31 -0
  69. package/dist/rpc-serializer.js +102 -0
  70. package/dist/types.d.ts +91 -0
  71. package/dist/utils.d.ts +36 -0
  72. package/dist/utils.js +67 -0
  73. package/package.json +47 -35
  74. package/dist/adapters/fetch/index.d.mts +0 -65
  75. package/dist/adapters/fetch/index.mjs +0 -68
  76. package/dist/adapters/message-port/index.d.mts +0 -75
  77. package/dist/adapters/message-port/index.mjs +0 -91
  78. package/dist/adapters/standard/index.d.mts +0 -61
  79. package/dist/adapters/standard/index.mjs +0 -6
  80. package/dist/adapters/websocket/index.d.mts +0 -121
  81. package/dist/adapters/websocket/index.mjs +0 -110
  82. package/dist/index.d.mts +0 -155
  83. package/dist/index.mjs +0 -154
  84. package/dist/plugins/index.d.mts +0 -242
  85. package/dist/plugins/index.mjs +0 -574
  86. package/dist/shared/client.8ug8I-zu.d.mts +0 -167
  87. package/dist/shared/client.8ug8I-zu.d.ts +0 -167
  88. package/dist/shared/client.BdItY5DT.d.mts +0 -111
  89. package/dist/shared/client.BdItY5DT.d.ts +0 -111
  90. package/dist/shared/client.CPF3hX6O.d.ts +0 -96
  91. package/dist/shared/client.Cby_-GGh.d.mts +0 -96
  92. package/dist/shared/client.DMXKFDyV.mjs +0 -343
  93. package/dist/shared/client.DXhchJ84.mjs +0 -174
  94. package/dist/shared/client.Dnfj8jnT.mjs +0 -92
@@ -1,110 +0,0 @@
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
-
9
- const WEBSOCKET_CONNECTING = 0;
10
- const WEBSOCKET_OPEN = 1;
11
- class WebsocketLinkTransport {
12
- connect;
13
- reconnectEnabled;
14
- reconnectDelay;
15
- reconnectMaxAttempt;
16
- reconnectOnCloseEnabled;
17
- reconnectOnCloseDelay;
18
- encodePeerMessageOptions;
19
- decodePeerMessageOptions;
20
- constructor(options) {
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;
96
- }
97
- });
98
- return this.getConnectedPeer();
99
- }
100
- }
101
-
102
- class RPCLink extends StandardLink {
103
- constructor(options) {
104
- const codec = new RPCLinkCodec(options);
105
- const transport = new WebsocketLinkTransport(options);
106
- super(codec, transport, options);
107
- }
108
- }
109
-
110
- export { RPCLink, WebsocketLinkTransport };
package/dist/index.d.mts DELETED
@@ -1,155 +0,0 @@
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, MaybeOptionalOptions, PromiseWithError, 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, EventMeta, getEventMeta, unwrapEvent, withEventMeta } from '@standardserver/core';
7
-
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> {
20
- /**
21
- * Interceptors that wrap the entire client call lifecycle.
22
- */
23
- interceptors?: ORPCClientInterceptor<TClientContext, TInput, TOutput, TError>[];
24
- }
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;
27
- };
28
- interface ORPCClientOptions<T extends AnyNestedClient> {
29
- /**
30
- * Use as base path for all procedure, useful when you only want to call a subset of the procedure.
31
- */
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>;
43
- }
44
- declare function createORPCClient<T extends AnyNestedClient>(link: ClientLink<InferClientContext<T>>, { path, ...options }?: NoInfer<ORPCClientOptions<T>>): T;
45
-
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] & {
49
- error: null;
50
- data: TOutput;
51
- inferableError: null;
52
- isSuccess: true;
53
- } | [error: Exclude<TError, AnyORPCError>, data: undefined, inferableError: null, isSuccess: false] & {
54
- error: Exclude<TError, AnyORPCError>;
55
- data: undefined;
56
- inferableError: null;
57
- isSuccess: false;
58
- } | [error: Extract<TError, AnyORPCError>, data: undefined, inferableError: Extract<TError, AnyORPCError>, isSuccess: false] & {
59
- error: Extract<TError, AnyORPCError>;
60
- data: undefined;
61
- inferableError: Extract<TError, AnyORPCError>;
62
- isSuccess: false;
63
- };
64
- /**
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(...))
71
- *
72
- * if (inferableError) {
73
- * console.log(inferableError) // or error, both are well typed
74
- * }
75
- */
76
- declare function safe<TOutput, TError = ThrowableError>(promise: PromiseWithError<TOutput, TError>): Promise<SafeResult<TOutput, TError>>;
77
- interface ConsumeEventIteratorOptions<T, TReturn, TError> {
78
- /**
79
- * Called on each event
80
- */
81
- onEvent: (event: T) => void;
82
- /**
83
- * Called once error happens
84
- */
85
- onError?: (error: TError) => void;
86
- /**
87
- * Called once event iterator is done
88
- *
89
- * @info If iterator is canceled, `undefined` can be passed on success
90
- */
91
- onSuccess?: (value: TReturn | undefined) => void;
92
- /**
93
- * Called once after onError or onSuccess
94
- *
95
- * @info If iterator is canceled, `undefined` can be passed on success
96
- */
97
- onFinish?: (state: [error: TError, data: undefined, isSuccess: false] | [error: null, data: TReturn | undefined, isSuccess: true]) => void;
98
- }
99
- /**
100
- * Consumes an event iterator with lifecycle callbacks
101
- *
102
- * @warning If no `onError` or `onFinish` is provided, error will be thrown into unhandled rejection channel.
103
- * @return unsubscribe callback
104
- */
105
- declare function consumeEventIterator<T, TReturn, TError = ThrowableError>(iterator: AsyncIterator<T, TReturn> | PromiseWithError<AsyncIterator<T, TReturn>, TError>, options: ConsumeEventIteratorOptions<T, TReturn, TError>): () => Promise<void>;
106
-
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;
109
- };
110
- /**
111
- * Create a safe client that automatically wraps all procedure calls with the `safe` util.
112
- *
113
- * @example
114
- * ```ts
115
- * const safeClient = createSafeClient(client)
116
- * const { error, data, inferrableError, isSuccess } = await safeClient.doSomething({ id: '123' })
117
- * // or const [error, data, inferrableError, isSuccess] = await safeClient.doSomething({ id: '123' })
118
- * ```
119
- *
120
- * @see {@link https://orpc.dev/docs/client/error-handling#using-createsafeclient Safe Client Docs}
121
- */
122
- declare function createSafeClient<T extends AnyNestedClient>(client: T): SafeClient<T>;
123
-
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>;
134
-
135
- /**
136
- * DynamicLink provides a way to dynamically resolve and delegate calls to other ClientLinks
137
- * based on the request path, input, and context.
138
- *
139
- * @see {@link https://orpc.dev/docs/client/dynamic-link Dynamic Link Docs}
140
- */
141
- declare class DynamicLink<TClientContext extends ClientContext> implements ClientLink<TClientContext> {
142
- private readonly linkResolver;
143
- constructor(linkResolver: (options: ClientOptions<TClientContext>, path: string[], input: unknown) => Promisable<ClientLink<TClientContext>>);
144
- call(path: string[], input: unknown, options: ClientOptions<TClientContext>): Promise<unknown>;
145
- }
146
-
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;
153
-
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 };
package/dist/index.mjs DELETED
@@ -1,154 +0,0 @@
1
- import { a as isInferableError } from './shared/client.DMXKFDyV.mjs';
2
- export { b as RPCJsonSerializer, R as RPCSerializer, d as cloneORPCError, c as createORPCErrorFromJson, i as isORPCErrorJson, t as toORPCError, w as wrapEventIteratorPreservingMeta } from './shared/client.DMXKFDyV.mjs';
3
- import { getOrBind, toArray, intercept, isTypescriptObject } from '@orpc/shared';
4
- export { AsyncIteratorClass, asyncIteratorToStream as eventIteratorToStream, asyncIteratorToUnproxiedDataStream as eventIteratorToUnproxiedDataStream, onError, onFinish, onStart, onSuccess, streamToAsyncIteratorClass as streamToEventIterator } from '@orpc/shared';
5
- export { C as COMMON_ERROR_STATUS_MAP, O as ORPCError } from './shared/client.Dnfj8jnT.mjs';
6
- export { ErrorEvent, getEventMeta, unwrapEvent, withEventMeta } from '@standardserver/core';
7
-
8
- const RECURSIVE_CLIENT_UNWRAP_KEYS = /* @__PURE__ */ new Set([
9
- /**
10
- * Prevents the client from being treated as a thenable when users
11
- * accidentally write `await client`.
12
- */
13
- "then",
14
- /**
15
- * Commonly used by libraries to bind functions to a specific `this`
16
- * context.
17
- */
18
- "bind",
19
- /**
20
- * Commonly accessed during primitive conversion, inspection, and logging.
21
- */
22
- "valueOf",
23
- /**
24
- * Commonly accessed during string conversion, inspection, and logging.
25
- */
26
- "toString",
27
- /**
28
- * Commonly accessed by serializers such as `JSON.stringify`.
29
- */
30
- "toJSON"
31
- ]);
32
-
33
- function resolveFriendlyClientOptions(options) {
34
- return {
35
- ...options,
36
- context: options.context ?? {}
37
- // Context only optional if all fields are optional
38
- };
39
- }
40
- function resolveClientRest(rest) {
41
- return [
42
- rest[0],
43
- // rest[0] can be undefined if TInput is optional,
44
- resolveFriendlyClientOptions(rest[1] ?? {})
45
- // rest[1] can be undefined if all fields of FriendlyClientOptions are optional
46
- ];
47
- }
48
- async function safe(promise) {
49
- try {
50
- const output = await promise;
51
- return Object.assign(
52
- [null, output, null, true],
53
- { error: null, data: output, inferableError: null, isSuccess: true }
54
- );
55
- } catch (e) {
56
- const error = e;
57
- if (isInferableError(error)) {
58
- return Object.assign(
59
- [error, void 0, error, false],
60
- { error, data: void 0, inferableError: error, isSuccess: false }
61
- );
62
- }
63
- return Object.assign(
64
- [error, void 0, null, false],
65
- { error, data: void 0, inferableError: null, isSuccess: false }
66
- );
67
- }
68
- }
69
- function consumeEventIterator(iterator, options) {
70
- void (async () => {
71
- let onFinishState;
72
- try {
73
- const resolvedIterator = await iterator;
74
- while (true) {
75
- const { done, value } = await resolvedIterator.next();
76
- if (done) {
77
- const realValue = value;
78
- onFinishState = [null, realValue, true];
79
- options.onSuccess?.(realValue);
80
- break;
81
- }
82
- options.onEvent(value);
83
- }
84
- } catch (error) {
85
- onFinishState = [error, void 0, false];
86
- if (!options.onError && !options.onFinish) {
87
- throw error;
88
- }
89
- options.onError?.(error);
90
- } finally {
91
- options.onFinish?.(onFinishState);
92
- }
93
- })();
94
- return async () => {
95
- await (await iterator)?.return?.();
96
- };
97
- }
98
-
99
- function createORPCClient(link, { path = [], ...options } = {}) {
100
- const procedureClient = (...rest) => {
101
- const [input, callOptions] = resolveClientRest(rest);
102
- const interceptors = [
103
- ...toArray(options.interceptors),
104
- ...toArray(options.scoped?.interceptors)
105
- ];
106
- return intercept(
107
- interceptors,
108
- { ...callOptions, input, path },
109
- ({ path: path2, input: input2, ...callOptions2 }) => link.call(path2, input2, callOptions2)
110
- );
111
- };
112
- const recursive = new Proxy(procedureClient, {
113
- get(target, key) {
114
- if (typeof key !== "string" || RECURSIVE_CLIENT_UNWRAP_KEYS.has(key)) {
115
- return getOrBind(target, key);
116
- }
117
- const scoped = options.scoped === void 0 ? void 0 : options.scoped[key];
118
- return createORPCClient(link, {
119
- ...options,
120
- path: [...path, key],
121
- scoped
122
- });
123
- }
124
- });
125
- return recursive;
126
- }
127
-
128
- function createSafeClient(client) {
129
- const proxy = new Proxy((...args) => safe(client(...args)), {
130
- get(_, prop) {
131
- const value = getOrBind(client, prop);
132
- if (!isTypescriptObject(value)) {
133
- return value;
134
- }
135
- return createSafeClient(value);
136
- }
137
- });
138
- return proxy;
139
- }
140
-
141
- class DynamicLink {
142
- constructor(linkResolver) {
143
- this.linkResolver = linkResolver;
144
- }
145
- async call(path, input, options) {
146
- const resolvedLink = await this.linkResolver(options, path, input);
147
- const output = await resolvedLink.call(path, input, options);
148
- return output;
149
- }
150
- }
151
-
152
- const isDefinedError = isInferableError;
153
-
154
- export { DynamicLink, RECURSIVE_CLIENT_UNWRAP_KEYS, consumeEventIterator, createORPCClient, createSafeClient, isDefinedError, isInferableError, resolveClientRest, resolveFriendlyClientOptions, safe };
@@ -1,242 +0,0 @@
1
- import { Value, Promisable } from '@orpc/shared';
2
- import { StandardUrl, StandardHeaders, StandardRequest, StandardLazyResponse } from '@standardserver/core';
3
- import { C as ClientContext } from '../shared/client.8ug8I-zu.mjs';
4
- import { c as StandardLinkPlugin, d as StandardLinkTransportInterceptorOptions, b as StandardLinkOptions, e as StandardLinkInterceptorOptions } from '../shared/client.Cby_-GGh.mjs';
5
-
6
- type BatchLinkPluginMode = 'streaming' | 'buffered';
7
- interface BatchLinkPluginGroup<T extends ClientContext> {
8
- /**
9
- * Determines whether a request should be included in this batch group.
10
- * Requests will be evaluated against each group's condition in order,
11
- * and included in the first group whose condition returns true.
12
- * If no group's condition returns true, the request will not be batched.
13
- */
14
- condition: Value<boolean, [options: StandardLinkTransportInterceptorOptions<T>]>;
15
- /**
16
- * The client context applied to requests in this batch group for the remainder of the link chain.
17
- */
18
- context: Value<T, [items: [StandardLinkTransportInterceptorOptions<T>, ...StandardLinkTransportInterceptorOptions<T>[]]]>;
19
- /**
20
- * The path segments applied to requests in this batch group for the remainder of the link chain.
21
- *
22
- * @default []
23
- */
24
- path?: Value<string[], [items: [StandardLinkTransportInterceptorOptions<T>, ...StandardLinkTransportInterceptorOptions<T>[]]]>;
25
- }
26
- declare class BatchLinkPluginError extends TypeError {
27
- }
28
- interface BatchLinkPluginOptions<T extends ClientContext> {
29
- groups: [BatchLinkPluginGroup<T>, ...BatchLinkPluginGroup<T>[]];
30
- /**
31
- * Filters requests to batch.
32
- *
33
- * @default () => true
34
- */
35
- filter?: Value<boolean, [options: StandardLinkTransportInterceptorOptions<T>]>;
36
- /**
37
- * The maximum number of requests in the batch.
38
- *
39
- * @default 10
40
- */
41
- maxSize?: Value<Promisable<number>, [subOptionsList: [StandardLinkTransportInterceptorOptions<T>, ...StandardLinkTransportInterceptorOptions<T>[]]]>;
42
- /**
43
- * The batch response mode.
44
- *
45
- * @default 'streaming'
46
- */
47
- mode?: Value<BatchLinkPluginMode, [subOptionsList: [StandardLinkTransportInterceptorOptions<T>, ...StandardLinkTransportInterceptorOptions<T>[]]]>;
48
- /**
49
- * URL for the batch request.
50
- *
51
- * @default URL of the first subrequest in the batch + '/__batch__'
52
- */
53
- url?: Value<Promisable<StandardUrl>, [subOptionsList: [StandardLinkTransportInterceptorOptions<T>, ...StandardLinkTransportInterceptorOptions<T>[]]]>;
54
- /**
55
- * The maximum length of the URL that runtime supports,
56
- * if exceeded, the batch will be split into smaller batches and sent sequentially.
57
- *
58
- * This only applies to GET batch requests where the batch data is sent via URL query parameter.
59
- *
60
- * @default 2083
61
- */
62
- maxUrlLength?: Value<Promisable<number>, [subOptionsList: [StandardLinkTransportInterceptorOptions<T>, ...StandardLinkTransportInterceptorOptions<T>[]]]>;
63
- /**
64
- * Headers used for the batch request.
65
- *
66
- * @default Common headers among all subrequests in the batch.
67
- */
68
- headers?: Value<Promisable<StandardHeaders>, [subOptionsList: [StandardLinkTransportInterceptorOptions<T>, ...StandardLinkTransportInterceptorOptions<T>[]]]>;
69
- /**
70
- * Map each subrequest in the batch before it is sent.
71
- *
72
- * @default Removes headers that are duplicated with the batch headers
73
- */
74
- mapSubrequest?: (subOptions: StandardLinkTransportInterceptorOptions<T>, partialBatchRequest: Pick<StandardRequest, 'url' | 'headers'>) => StandardRequest;
75
- /**
76
- * Maps each subresponse before returning the final response.
77
- *
78
- * @default Low-priority merges headers from the batch response into each subresponse.
79
- */
80
- mapSubresponse?: (subResponse: StandardLazyResponse, batchResponse: StandardLazyResponse, subOptions: StandardLinkTransportInterceptorOptions<T>) => StandardLazyResponse;
81
- }
82
- declare class BatchLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
83
- name: string;
84
- private readonly groups;
85
- private readonly filter;
86
- private readonly maxSize;
87
- private readonly mode;
88
- private readonly batchUrl;
89
- private readonly maxUrlLength;
90
- private readonly batchHeaders;
91
- private readonly mapSubrequest;
92
- private readonly mapSubresponse;
93
- private readonly queue;
94
- constructor(options: NoInfer<BatchLinkPluginOptions<T>>);
95
- init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
96
- private processPendingBatches;
97
- private executeBatch;
98
- }
99
-
100
- interface DedupeLinkPluginGroup<T extends ClientContext> {
101
- condition: Value<boolean, [options: StandardLinkTransportInterceptorOptions<T>]>;
102
- /**
103
- * The context used for the rest of the request lifecycle.
104
- */
105
- context: Value<T, [
106
- items: [
107
- StandardLinkTransportInterceptorOptions<T>,
108
- StandardLinkTransportInterceptorOptions<T>,
109
- ...StandardLinkTransportInterceptorOptions<T>[]
110
- ]
111
- ]>;
112
- }
113
- interface DedupeLinkPluginOptions<T extends ClientContext> {
114
- /**
115
- * To enable deduplication, a request must match at least one defined group.
116
- * Requests that fall into the same group are considered for deduplication together.
117
- */
118
- groups: [DedupeLinkPluginGroup<T>, ...DedupeLinkPluginGroup<T>[]];
119
- /**
120
- * Filters requests to dedupe.
121
- *
122
- * @default ({ request }) => request.method === 'GET'
123
- */
124
- filter?: Value<boolean, [options: StandardLinkTransportInterceptorOptions<T>]>;
125
- }
126
- declare class DedupeLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
127
- name: string;
128
- before: string[];
129
- private readonly groups;
130
- private readonly filter;
131
- private readonly queue;
132
- constructor(options: NoInfer<DedupeLinkPluginOptions<T>>);
133
- init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
134
- private enqueue;
135
- private processPendingRequests;
136
- private execute;
137
- }
138
-
139
- interface RetryLinkPluginAttemptOptions<T extends RetryLinkPluginContext> extends StandardLinkInterceptorOptions<T> {
140
- /**
141
- * Latest retry delay advertised by the server via event metadata.
142
- */
143
- lastEventRetry: number | undefined;
144
- /**
145
- * Current retry attempt number, starting at 1.
146
- */
147
- attempt: number;
148
- /**
149
- * Error that triggered this retry attempt.
150
- */
151
- error: unknown;
152
- }
153
- interface RetryLinkPluginContext {
154
- /**
155
- * Maximum retry attempts before throwing.
156
- * Use `Number.POSITIVE_INFINITY` for infinite retries (e.g. for event iterators).
157
- *
158
- * @default 0
159
- */
160
- retry?: Value<Promisable<number>, [Omit<StandardLinkInterceptorOptions<RetryLinkPluginContext>, 'next'>]>;
161
- /**
162
- * Delay (in ms) before retrying.
163
- *
164
- * @info Why 2000ms? The EventSource spec suggests a default retry delay of 2 seconds if it doesn't specify
165
- * @default (o) => o.lastEventRetry ?? 2000
166
- */
167
- retryDelay?: Value<Promisable<number>, [RetryLinkPluginAttemptOptions<RetryLinkPluginContext>]>;
168
- /**
169
- * Determine whether to retry.
170
- *
171
- * @default true
172
- */
173
- shouldRetry?: Value<Promisable<boolean>, [RetryLinkPluginAttemptOptions<RetryLinkPluginContext>]>;
174
- /**
175
- * Hook called before each retry. Can return a cleanup callback.
176
- */
177
- onRetry?: (options: RetryLinkPluginAttemptOptions<RetryLinkPluginContext>) => void | ((isSuccess: boolean) => void);
178
- }
179
- interface RetryLinkPluginOptions<_T extends RetryLinkPluginContext> {
180
- /**
181
- * Default retry options. Can be overridden by individual calls via the context.
182
- */
183
- default?: RetryLinkPluginContext | undefined;
184
- }
185
- declare class RetryLinkPluginInvalidEventIteratorRetryResponse extends Error {
186
- }
187
- declare class RetryLinkPlugin<T extends RetryLinkPluginContext & ClientContext> implements StandardLinkPlugin<T> {
188
- private readonly defaultRetry;
189
- private readonly defaultRetryDelay;
190
- private readonly defaultShouldRetry;
191
- private readonly defaultOnRetry;
192
- name: string;
193
- constructor(options?: RetryLinkPluginOptions<T>);
194
- init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
195
- }
196
-
197
- interface RetryAfterLinkPluginOptions<T extends ClientContext> {
198
- /**
199
- * Override condition to determine whether to retry or not.
200
- *
201
- * @default ((response) => response.status === 429 || response.status === 503)
202
- */
203
- condition?: Value<boolean, [
204
- response: StandardLazyResponse,
205
- options: StandardLinkTransportInterceptorOptions<T>
206
- ]>;
207
- /**
208
- * Maximum attempts before giving up retries.
209
- *
210
- * @default 3
211
- */
212
- maxAttempts?: Value<number, [
213
- response: StandardLazyResponse,
214
- options: StandardLinkTransportInterceptorOptions<T>
215
- ]>;
216
- /**
217
- * Maximum timeout in milliseconds to wait before giving up retries.
218
- *
219
- * @default 5 * 60 * 1000 (5 minutes)
220
- */
221
- timeout?: Value<number, [
222
- response: StandardLazyResponse,
223
- options: StandardLinkTransportInterceptorOptions<T>
224
- ]>;
225
- }
226
- /**
227
- * The Retry After Link Plugin automatically retries requests based on server `retry-after` header.
228
- * This is particularly useful for handling rate limiting and temporary server unavailability.
229
- *
230
- * @see {@link https://orpc.dev/docs/plugins/retry-after Retry After Plugin Docs}
231
- */
232
- declare class RetryAfterLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
233
- private readonly condition;
234
- private readonly maxAttempts;
235
- private readonly timeout;
236
- name: string;
237
- constructor(options?: RetryAfterLinkPluginOptions<T>);
238
- init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
239
- }
240
-
241
- export { BatchLinkPlugin, BatchLinkPluginError, DedupeLinkPlugin, RetryAfterLinkPlugin, RetryLinkPlugin, RetryLinkPluginInvalidEventIteratorRetryResponse };
242
- export type { BatchLinkPluginGroup, BatchLinkPluginMode, BatchLinkPluginOptions, DedupeLinkPluginGroup, DedupeLinkPluginOptions, RetryAfterLinkPluginOptions, RetryLinkPluginAttemptOptions, RetryLinkPluginContext, RetryLinkPluginOptions };