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

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 (147) hide show
  1. package/README.md +4 -4
  2. package/dist/adapters/fetch/index.d.ts +2 -0
  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 +14 -0
  6. package/dist/adapters/fetch/transport.d.ts +34 -0
  7. package/dist/adapters/fetch/transport.js +65 -0
  8. package/dist/adapters/message-port/index.d.ts +3 -0
  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 +56 -0
  12. package/dist/adapters/message-port/rpc-link.d.ts +15 -0
  13. package/dist/adapters/message-port/rpc-link.js +15 -0
  14. package/dist/adapters/message-port/transport.d.ts +38 -0
  15. package/dist/adapters/message-port/transport.js +52 -0
  16. package/dist/adapters/standard/codec.d.ts +14 -0
  17. package/dist/adapters/standard/index.d.ts +5 -0
  18. package/dist/adapters/standard/index.js +4 -0
  19. package/dist/adapters/standard/link.d.ts +40 -0
  20. package/dist/adapters/standard/link.js +85 -0
  21. package/dist/adapters/standard/plugin.d.ts +32 -0
  22. package/dist/adapters/standard/plugin.js +16 -0
  23. package/dist/adapters/standard/rpc-link-codec.d.ts +63 -0
  24. package/dist/adapters/standard/rpc-link-codec.js +104 -0
  25. package/dist/adapters/standard/transport.d.ts +14 -0
  26. package/dist/adapters/websocket/index.d.ts +2 -0
  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 +14 -0
  30. package/dist/adapters/websocket/transport.d.ts +115 -0
  31. package/dist/adapters/websocket/transport.js +133 -0
  32. package/dist/async-iterator-object.d.ts +2 -0
  33. package/dist/async-iterator-object.js +29 -0
  34. package/dist/client-safe.d.ts +18 -0
  35. package/dist/client-safe.js +36 -0
  36. package/dist/client.d.ts +40 -0
  37. package/dist/client.js +39 -0
  38. package/dist/consts.d.ts +10 -0
  39. package/dist/consts.js +43 -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 +21 -0
  43. package/dist/error-utils.js +58 -0
  44. package/dist/error.d.ts +132 -0
  45. package/dist/error.js +178 -0
  46. package/dist/index.d.ts +53 -0
  47. package/dist/index.js +40 -0
  48. package/dist/plugins/batch.d.ts +185 -0
  49. package/dist/plugins/batch.js +401 -0
  50. package/dist/plugins/cookie-jar.d.ts +82 -0
  51. package/dist/plugins/cookie-jar.js +268 -0
  52. package/dist/plugins/dedupe.d.ts +64 -0
  53. package/dist/plugins/dedupe.js +226 -0
  54. package/dist/plugins/index.d.ts +28 -0
  55. package/dist/plugins/index.js +23 -0
  56. package/dist/plugins/request-compression.d.ts +44 -0
  57. package/dist/plugins/request-compression.js +178 -0
  58. package/dist/plugins/response-compression.d.ts +28 -0
  59. package/dist/plugins/response-compression.js +91 -0
  60. package/dist/plugins/retry-after.d.ts +50 -0
  61. package/dist/plugins/retry-after.js +88 -0
  62. package/dist/plugins/retry.d.ts +84 -0
  63. package/dist/plugins/retry.js +140 -0
  64. package/dist/plugins/timeout.d.ts +25 -0
  65. package/dist/plugins/timeout.js +37 -0
  66. package/dist/rpc-json-serializer.d.ts +99 -0
  67. package/dist/rpc-json-serializer.js +392 -0
  68. package/dist/rpc-serializer.d.ts +32 -0
  69. package/dist/rpc-serializer.js +130 -0
  70. package/dist/types.d.ts +97 -0
  71. package/dist/utils.d.ts +47 -0
  72. package/dist/utils.js +51 -0
  73. package/package.json +43 -45
  74. package/dist/adapters/fetch/index.d.mts +0 -2
  75. package/dist/adapters/fetch/index.mjs +0 -2
  76. package/dist/adapters/fetch/rpc-link.d.mts +0 -13
  77. package/dist/adapters/fetch/rpc-link.mjs +0 -10
  78. package/dist/adapters/fetch/transport.d.mts +0 -31
  79. package/dist/adapters/fetch/transport.mjs +0 -65
  80. package/dist/adapters/message-port/index.d.mts +0 -3
  81. package/dist/adapters/message-port/index.mjs +0 -3
  82. package/dist/adapters/message-port/message-port.d.mts +0 -29
  83. package/dist/adapters/message-port/message-port.mjs +0 -43
  84. package/dist/adapters/message-port/rpc-link.d.mts +0 -14
  85. package/dist/adapters/message-port/rpc-link.mjs +0 -10
  86. package/dist/adapters/message-port/transport.d.mts +0 -35
  87. package/dist/adapters/message-port/transport.mjs +0 -47
  88. package/dist/adapters/standard/codec.d.mts +0 -14
  89. package/dist/adapters/standard/index.d.mts +0 -5
  90. package/dist/adapters/standard/index.mjs +0 -4
  91. package/dist/adapters/standard/link.d.mts +0 -40
  92. package/dist/adapters/standard/link.mjs +0 -79
  93. package/dist/adapters/standard/plugin.d.mts +0 -32
  94. package/dist/adapters/standard/plugin.mjs +0 -16
  95. package/dist/adapters/standard/rpc-link-codec.d.mts +0 -55
  96. package/dist/adapters/standard/rpc-link-codec.mjs +0 -104
  97. package/dist/adapters/standard/transport.d.mts +0 -14
  98. package/dist/adapters/websocket/index.d.mts +0 -2
  99. package/dist/adapters/websocket/index.mjs +0 -2
  100. package/dist/adapters/websocket/rpc-link.d.mts +0 -13
  101. package/dist/adapters/websocket/rpc-link.mjs +0 -10
  102. package/dist/adapters/websocket/transport.d.mts +0 -119
  103. package/dist/adapters/websocket/transport.mjs +0 -123
  104. package/dist/async-iterator-object.d.mts +0 -7
  105. package/dist/async-iterator-object.mjs +0 -30
  106. package/dist/client-safe.d.mts +0 -16
  107. package/dist/client-safe.mjs +0 -23
  108. package/dist/client.d.mts +0 -51
  109. package/dist/client.mjs +0 -32
  110. package/dist/consts.d.mts +0 -10
  111. package/dist/consts.mjs +0 -10
  112. package/dist/dynamic-link.d.mts +0 -13
  113. package/dist/dynamic-link.mjs +0 -12
  114. package/dist/error-utils.d.mts +0 -24
  115. package/dist/error-utils.mjs +0 -44
  116. package/dist/error.d.mts +0 -138
  117. package/dist/error.mjs +0 -105
  118. package/dist/index.d.mts +0 -49
  119. package/dist/index.mjs +0 -23
  120. package/dist/plugins/batch.d.mts +0 -150
  121. package/dist/plugins/batch.mjs +0 -339
  122. package/dist/plugins/cookie-jar.d.mts +0 -82
  123. package/dist/plugins/cookie-jar.mjs +0 -229
  124. package/dist/plugins/dedupe.d.mts +0 -58
  125. package/dist/plugins/dedupe.mjs +0 -199
  126. package/dist/plugins/index.d.mts +0 -28
  127. package/dist/plugins/index.mjs +0 -17
  128. package/dist/plugins/request-compression.d.mts +0 -44
  129. package/dist/plugins/request-compression.mjs +0 -150
  130. package/dist/plugins/response-compression.d.mts +0 -28
  131. package/dist/plugins/response-compression.mjs +0 -78
  132. package/dist/plugins/retry-after.d.mts +0 -41
  133. package/dist/plugins/retry-after.mjs +0 -71
  134. package/dist/plugins/retry.d.mts +0 -82
  135. package/dist/plugins/retry.mjs +0 -127
  136. package/dist/plugins/timeout.d.mts +0 -25
  137. package/dist/plugins/timeout.mjs +0 -36
  138. package/dist/rpc-json-serializer.d.mts +0 -99
  139. package/dist/rpc-json-serializer.mjs +0 -365
  140. package/dist/rpc-serializer.d.mts +0 -32
  141. package/dist/rpc-serializer.mjs +0 -100
  142. package/dist/types.d.mts +0 -93
  143. package/dist/utils.d.mts +0 -46
  144. package/dist/utils.mjs +0 -53
  145. /package/dist/adapters/standard/{codec.mjs → codec.js} +0 -0
  146. /package/dist/adapters/standard/{transport.mjs → transport.js} +0 -0
  147. /package/dist/{types.mjs → types.js} +0 -0
@@ -1,123 +0,0 @@
1
- import { AbortError, loadBytes, promiseWithResolvers, runWithSignal, sequential, sleep, toStringOrBytes } from "@orpc/shared";
2
- import { ClientPeer, decodePeerMessage, encodePeerMessage, isServerPeerSendMessage } from "@standard-server/peer";
3
-
4
- const WEBSOCKET_CONNECTING = 0;
5
- const WEBSOCKET_OPEN = 1;
6
- export class WebSocketLinkTransport {
7
- connect;
8
- reconnectEnabled;
9
- reconnectDelay;
10
- reconnectMaxAttempt;
11
- reconnectMaxTotalAttempt;
12
- reconnectOnCloseEnabled;
13
- reconnectOnCloseDelay;
14
- encodePeerMessageOptions;
15
- decodePeerMessageOptions;
16
- constructor(options) {
17
- this.connect = options.connect;
18
- this.reconnectEnabled = options.reconnect?.enabled ?? false;
19
- this.reconnectDelay = options.reconnect?.delay ?? ((info) => info.attempt === 1 ? 0 : 2e3);
20
- this.reconnectMaxAttempt = options.reconnect?.maxAttempt ?? Infinity;
21
- this.reconnectMaxTotalAttempt = options.reconnect?.maxTotalAttempt ?? Infinity;
22
- this.reconnectOnCloseEnabled = this.reconnectEnabled && (options.reconnect?.onClose?.enabled ?? false);
23
- this.reconnectOnCloseDelay = options.reconnect?.onClose?.delay ?? 0;
24
- this.encodePeerMessageOptions = options.encodePeerMessage;
25
- this.decodePeerMessageOptions = options.decodePeerMessage;
26
- if (options.connectOnInit) {
27
- this.getConnectedPeer().catch(() => {});
28
- }
29
- }
30
- async send(standardRequest, _path, _options) {
31
- const peer = await runWithSignal(standardRequest.signal, () => this.getConnectedPeer());
32
- return peer.request(standardRequest);
33
- }
34
- totalAttempt = 0;
35
- attempt = 0;
36
- current;
37
- async getConnectedPeer() {
38
- const current = this.current;
39
- const resolved = await current;
40
- if (resolved && (!this.reconnectEnabled || resolved.websocket.readyState === WEBSOCKET_OPEN)) {
41
- return resolved.peer;
42
- }
43
- if (current !== this.current) {
44
- return this.getConnectedPeer();
45
- }
46
- if (this.totalAttempt >= this.reconnectMaxTotalAttempt) {
47
- throw new AbortError(`WebSocket reconnect stopped after ${this.totalAttempt} total attempt(s)`);
48
- }
49
- this.current = (async () => {
50
- this.totalAttempt += 1;
51
- this.attempt += 1;
52
- const info = {
53
- totalAttempt: this.totalAttempt,
54
- attempt: this.attempt
55
- };
56
- await sleep(this.reconnectDelay(info));
57
- const websocket = await this.connect(info);
58
- if (websocket.readyState !== WEBSOCKET_CONNECTING && websocket.readyState !== WEBSOCKET_OPEN) {
59
- throw new AbortError("WebSocket is already closing or closed");
60
- }
61
- let closeReason;
62
- const peer = new ClientPeer(async (message) => {
63
-
64
- if (closeReason) {
65
- throw closeReason;
66
- }
67
- const encoded = await encodePeerMessage(message, this.encodePeerMessageOptions);
68
- return websocket.send(encoded);
69
- });
70
- let connectingResolvers;
71
- if (websocket.readyState === WEBSOCKET_CONNECTING) {
72
- connectingResolvers = promiseWithResolvers();
73
- websocket.addEventListener("open", () => {
74
- connectingResolvers?.resolve();
75
- });
76
- }
77
-
78
- websocket.addEventListener("message", sequential(async (event) => {
79
-
80
- const message = event.data instanceof Blob ? await loadBytes(event.data) : toStringOrBytes(event.data);
81
- const result = decodePeerMessage(message, this.decodePeerMessageOptions);
82
- if (result.matched && isServerPeerSendMessage(result.message)) {
83
-
84
-
85
- peer.message(result.message);
86
- }
87
- }));
88
- websocket.addEventListener("close", async (event) => {
89
- closeReason = new AbortError(`WebSocket closed (code ${event.code}: ${event.reason})`);
90
- connectingResolvers?.resolve();
91
- await peer.close(closeReason);
92
- });
93
-
94
-
95
- websocket.addEventListener("error", () => {});
96
- await connectingResolvers?.promise;
97
- if (closeReason) {
98
- throw closeReason;
99
- }
100
- if (this.reconnectOnCloseEnabled) {
101
- websocket.addEventListener("close", () => {
102
- sleep(this.reconnectOnCloseDelay).then(() => this.getConnectedPeer()).catch(() => {});
103
- });
104
- }
105
- this.attempt = 0;
106
- return {
107
- websocket,
108
- peer
109
- };
110
- })().catch((error) => {
111
- if (!this.reconnectEnabled) {
112
- throw error;
113
- }
114
- if (this.attempt >= this.reconnectMaxAttempt) {
115
- const attempt = this.attempt;
116
- this.attempt = 0;
117
- this.current = undefined;
118
- throw new AbortError(`WebSocket reconnect failed after ${attempt} attempt(s)`, { cause: error });
119
- }
120
- });
121
- return this.getConnectedPeer();
122
- }
123
- }
@@ -1,7 +0,0 @@
1
- import type { AsyncIteratorClass, WrapAsyncIteratorOptions } from "@orpc/shared";
2
- export declare function wrapAsyncIteratorPreservingEventMeta<
3
- TYield,
4
- TReturn,
5
- TMappedYield = TYield,
6
- TMappedReturn = TReturn
7
- >(iterator: AsyncIterator<TYield, TReturn>, { mapResult, mapError, ...rest }: WrapAsyncIteratorOptions<TYield, TReturn, TMappedYield, TMappedReturn>): AsyncIteratorClass<TMappedYield, TMappedReturn>;
@@ -1,30 +0,0 @@
1
- import { isTypescriptObject, 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 && (async (result) => {
7
- const mapped = await mapResult(result);
8
- if (mapped.value !== result.value) {
9
- const meta = getEventMeta(result.value);
10
- if (meta && isTypescriptObject(mapped.value)) {
11
- return {
12
- done: mapped.done,
13
- value: withEventMeta(mapped.value, meta)
14
- };
15
- }
16
- }
17
- return mapped;
18
- }),
19
- mapError: mapError && (async (error) => {
20
- const mapped = await mapError(error);
21
- if (mapped !== error) {
22
- const meta = getEventMeta(error);
23
- if (meta && isTypescriptObject(mapped)) {
24
- return withEventMeta(mapped, meta);
25
- }
26
- }
27
- return mapped;
28
- })
29
- });
30
- }
@@ -1,16 +0,0 @@
1
- import type { AnyNestedClient, Client, ClientRest } from "./types.mjs";
2
- import type { SafeResult } from "./utils.mjs";
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 };
4
- /**
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 declare function createSafeClient<T extends AnyNestedClient>(client: T): SafeClient<T>;
@@ -1,23 +0,0 @@
1
- import { isTypescriptObject } from "@orpc/shared";
2
- import { RECURSIVE_CLIENT_UNWRAP_KEYS } from "./consts.mjs";
3
- import { safe } from "./utils.mjs";
4
-
5
- export function createSafeClient(client) {
6
- const cache = new Map();
7
- const proxy = new Proxy((...args) => safe(client(...args)), { get(target, prop) {
8
- if (typeof prop !== "string" || RECURSIVE_CLIENT_UNWRAP_KEYS.has(prop)) {
9
- return Reflect.get(target, prop);
10
- }
11
- let safeClient = cache.get(prop);
12
- if (safeClient === undefined) {
13
- const value = client[prop];
14
- if (!isTypescriptObject(value)) {
15
- return value;
16
- }
17
- safeClient = createSafeClient(value);
18
- cache.set(prop, safeClient);
19
- }
20
- return safeClient;
21
- } });
22
- return proxy;
23
- }
package/dist/client.d.mts DELETED
@@ -1,51 +0,0 @@
1
- import type { Interceptor, PromiseWithError } from "@orpc/shared";
2
- import type { AnyNestedClient, Client, ClientContext, ClientLink, ClientOptions, InferClientContext, InferClientError } from "./types.mjs";
3
- export interface ORPCClientInterceptorOptions<
4
- TClientContext extends ClientContext,
5
- TInput
6
- > extends ClientOptions<TClientContext> {
7
- path: string[];
8
- input: TInput;
9
- }
10
- export type ORPCClientInterceptor<
11
- TClientContext extends ClientContext,
12
- TInput,
13
- TOutput,
14
- TError
15
- > = Interceptor<ORPCClientInterceptorOptions<TClientContext, TInput>, PromiseWithError<TOutput, TError>>;
16
- export interface ORPCClientScopedOptions<
17
- TClientContext extends ClientContext,
18
- TInput,
19
- TOutput,
20
- TError
21
- > {
22
- /**
23
- * Interceptors that wrap the entire client call lifecycle.
24
- */
25
- interceptors?: ORPCClientInterceptor<TClientContext, TInput, TOutput, TError>[] | undefined;
26
- }
27
- 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 };
28
- export 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[] | undefined;
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>>[] | undefined;
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> | undefined;
43
- }
44
- /**
45
- * Creates a fully typed oRPC client from a link.
46
- * The returned client mirrors the shape of your router or contract,
47
- * so calling a procedure is as simple as calling a function.
48
- *
49
- * @see {@link https://orpc.dev/docs/client/client-side | Client-Side Clients}
50
- */
51
- export declare function createORPCClient<T extends AnyNestedClient>(link: ClientLink<InferClientContext<T>>, { path, ...options }?: NoInfer<ORPCClientOptions<T>>): T;
package/dist/client.mjs DELETED
@@ -1,32 +0,0 @@
1
- import { intercept, toArray } from "@orpc/shared";
2
- import { RECURSIVE_CLIENT_UNWRAP_KEYS } from "./consts.mjs";
3
- import { resolveClientRest } from "./utils.mjs";
4
-
5
- export function createORPCClient(link, { path = [], ...options } = {}) {
6
- const procedureClient = (...rest) => {
7
- const [input, callOptions] = resolveClientRest(rest);
8
- const interceptors = [...toArray(options.interceptors), ...toArray(options.scoped?.interceptors)];
9
- return intercept(interceptors, {
10
- ...callOptions,
11
- input,
12
- path
13
- }, ({ path, input, ...callOptions }) => link.call(path, input, callOptions));
14
- };
15
- const cache = new Map();
16
- const recursive = new Proxy(procedureClient, { get(target, key) {
17
- if (typeof key !== "string" || RECURSIVE_CLIENT_UNWRAP_KEYS.has(key)) {
18
- return Reflect.get(target, key);
19
- }
20
- let client = cache.get(key);
21
- if (client === undefined) {
22
- client = createORPCClient(link, {
23
- ...options,
24
- path: [...path, key],
25
- scoped: options.scoped?.[key]
26
- });
27
- cache.set(key, client);
28
- }
29
- return client;
30
- } });
31
- return recursive;
32
- }
package/dist/consts.d.mts DELETED
@@ -1,10 +0,0 @@
1
- /**
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 declare const RECURSIVE_CLIENT_UNWRAP_KEYS: Set<PropertyKey>;
package/dist/consts.mjs DELETED
@@ -1,10 +0,0 @@
1
-
2
- export const RECURSIVE_CLIENT_UNWRAP_KEYS = /* @__PURE__ */ new Set([
3
- "then",
4
- "bind",
5
- "call",
6
- "apply",
7
- "valueOf",
8
- "toString",
9
- "toJSON"
10
- ]);
@@ -1,13 +0,0 @@
1
- import type { Promisable } from "@orpc/shared";
2
- import type { ClientContext, ClientLink, ClientOptions } from "./types.mjs";
3
- /**
4
- * DynamicLink provides a way to dynamically resolve and delegate calls to other ClientLinks
5
- * based on the request path, input, and context.
6
- *
7
- * @see {@link https://orpc.dev/docs/client/dynamic-link | DynamicLink}
8
- */
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
- }
@@ -1,12 +0,0 @@
1
-
2
- export class DynamicLink {
3
- linkResolver;
4
- constructor(linkResolver) {
5
- this.linkResolver = linkResolver;
6
- }
7
- async call(path, input, options) {
8
- const resolvedLink = await this.linkResolver(options, path, input);
9
- const output = await resolvedLink.call(path, input, options);
10
- return output;
11
- }
12
- }
@@ -1,24 +0,0 @@
1
- import type { AnyORPCError, ORPCErrorCode, ORPCErrorJSON } from "./error.mjs";
2
- import { ORPCError } from "./error.mjs";
3
- /**
4
- * Checks if an error is an `ORPCError` that matches a definition in the procedure's `.errors` map,
5
- * narrowing it so `code` and `data` are fully typed.
6
- *
7
- * @see {@link https://orpc.dev/docs/client/error-handling#using-safe-and-isdefinederror | Client Error Handling - Using safe and isDefinedError}
8
- */
9
- export declare function isDefinedError<T>(error: T): error is Extract<T, AnyORPCError>;
10
- export declare function toORPCError<T>(error: T): Extract<T, AnyORPCError> | ORPCError<"INTERNAL_SERVER_ERROR", undefined>;
11
- export declare function isORPCErrorJson(json: unknown): json is ORPCErrorJSON<ORPCErrorCode, unknown>;
12
- export declare function createORPCErrorFromJson<
13
- TCode extends ORPCErrorCode,
14
- TData
15
- >(json: ORPCErrorJSON<TCode, TData>, options?: ErrorOptions): ORPCError<TCode, TData>;
16
- /**
17
- * Clones an `ORPCError` while preserving its prototype chain, so instances of
18
- * `ORPCError` subclasses remain `instanceof` their class.
19
- *
20
- * Limitation: subclass constructors are not re-run, so private fields
21
- * (`#field`) are not carried over and subclass members that read them
22
- * will throw on the clone.
23
- */
24
- export declare function cloneORPCError<T extends AnyORPCError>(error: T): T;
@@ -1,44 +0,0 @@
1
- import { isPlainObject } from "@orpc/shared";
2
- import { ORPCError } from "./error.mjs";
3
-
4
- export function isDefinedError(error) {
5
- return error instanceof ORPCError && error.defined;
6
- }
7
- export function toORPCError(error) {
8
- return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", { cause: error });
9
- }
10
- export function isORPCErrorJson(json) {
11
- if (!isPlainObject(json)) {
12
- return false;
13
- }
14
- const validKeys = [
15
- "defined",
16
- "code",
17
- "message",
18
- "data"
19
- ];
20
- if (Object.keys(json).some((k) => !validKeys.includes(k))) {
21
- return false;
22
- }
23
- return "defined" in json && typeof json.defined === "boolean" && "code" in json && typeof json.code === "string" && "message" in json && typeof json.message === "string";
24
- }
25
- export function createORPCErrorFromJson(json, options = {}) {
26
- const error = new ORPCError(json.code, {
27
- ...json,
28
- ...options
29
- });
30
- error.defined = json.defined;
31
- return error;
32
- }
33
-
34
- export function cloneORPCError(error) {
35
- const cloned = new ORPCError(error.code, {
36
- message: error.message,
37
- data: error.data,
38
- cause: error.cause
39
- });
40
- Object.setPrototypeOf(cloned, Object.getPrototypeOf(error));
41
- Object.defineProperties(cloned, Object.getOwnPropertyDescriptors(error));
42
- cloned.stack = error.stack;
43
- return cloned;
44
- }
package/dist/error.d.mts DELETED
@@ -1,138 +0,0 @@
1
- import type { MaybeOptionalOptions, Registry } from "@orpc/shared";
2
- import type { StandardResponse } from "@standard-server/core";
3
- /**
4
- * Default mapping between common oRPC error codes and HTTP status codes.
5
- * Handlers use it to determine response status codes; spread it to build a custom `errorStatusMap`.
6
- *
7
- * @see {@link https://orpc.dev/docs/rpc/handler#custom-error-response | RPC Handler - Custom Error Response}
8
- * @see {@link https://orpc.dev/docs/openapi/handler#custom-error-response | OpenAPI Handler - Custom Error Response}
9
- */
10
- export declare const COMMON_ERROR_STATUS_MAP: {
11
- BAD_REQUEST: number;
12
- UNAUTHORIZED: number;
13
- PAYMENT_REQUIRED: number;
14
- FORBIDDEN: number;
15
- NOT_FOUND: number;
16
- METHOD_NOT_SUPPORTED: number;
17
- NOT_ACCEPTABLE: number;
18
- TIMEOUT: number;
19
- CONFLICT: number;
20
- GONE: number;
21
- LENGTH_REQUIRED: number;
22
- PRECONDITION_FAILED: number;
23
- PAYLOAD_TOO_LARGE: number;
24
- UNSUPPORTED_MEDIA_TYPE: number;
25
- UNPROCESSABLE_CONTENT: number;
26
- PRECONDITION_REQUIRED: number;
27
- TOO_MANY_REQUESTS: number;
28
- CLIENT_CLOSED_REQUEST: number;
29
- INTERNAL_SERVER_ERROR: number;
30
- NOT_IMPLEMENTED: number;
31
- BAD_GATEWAY: number;
32
- SERVICE_UNAVAILABLE: number;
33
- GATEWAY_TIMEOUT: number;
34
- };
35
- export type ORPCErrorCode = Registry extends {
36
- ORPCErrorCode: infer T extends string;
37
- } ? T : keyof typeof COMMON_ERROR_STATUS_MAP | string & {};
38
- export type ORPCErrorOptions<TData> = ErrorOptions & {
39
- message?: string | undefined;
40
- } & (undefined extends TData ? {
41
- data?: TData;
42
- } : {
43
- data: TData;
44
- });
45
- /**
46
- * Typed error carrying a `code`, a `message`, and optional `data`.
47
- * Throw it from handlers or middleware to produce typed error responses on the client.
48
- *
49
- * @see {@link https://orpc.dev/docs/error-handling#orpcerror-class | Error Handling - ORPCError Class}
50
- */
51
- export declare class ORPCError<
52
- TCode extends ORPCErrorCode,
53
- TData
54
- > extends Error {
55
- /**
56
- * @remarks
57
- * **Note**: The `__branch` property is used for type branding, helping TypeScript distinguish
58
- * an `ORPCError` instance from plain objects with a similar structure.
59
- */
60
- override readonly name: "ORPCError" & {
61
- __branch: "ORPCError";
62
- };
63
- /**
64
- * Indicates whether the error matches a definition in the procedure's `.errors` map,
65
- * which makes its type inferable on the client.
66
- */
67
- readonly defined: boolean;
68
- code: TCode;
69
- data: TData;
70
- constructor(code: TCode, ...rest: MaybeOptionalOptions<ORPCErrorOptions<TData>>);
71
- toJSON(): ORPCErrorJSON<TCode, TData>;
72
- /**
73
- * Workaround for Next.js where different contexts use separate
74
- * dependency graphs, causing multiple ORPCError constructors existing and breaking
75
- * `instanceof` checks across contexts.
76
- *
77
- * This is particularly problematic with "Optimized SSR", where orpc-client
78
- * executes in one context but is invoked from another. When an error is thrown
79
- * in the execution context, `instanceof ORPCError` checks fail in the
80
- * invocation context due to separate class constructors.
81
- *
82
- * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.
83
- */
84
- static override [Symbol.hasInstance](instance: unknown): boolean;
85
- }
86
- export interface ORPCErrorJSON<
87
- TCode extends string,
88
- TData
89
- > extends Pick<ORPCError<TCode, TData>, "code" | "message" | "data"> {
90
- /**
91
- * remove readonly
92
- */
93
- defined: boolean;
94
- }
95
- export type AnyORPCError = ORPCError<any, any>;
96
- export type AnyORPCErrorJSON = ORPCErrorJSON<any, any>;
97
- export interface ResponseErrorOptions extends ErrorOptions {
98
- /**
99
- * @default inferred from the response status
100
- */
101
- message?: string | undefined;
102
- response: StandardResponse;
103
- }
104
- /**
105
- * Error carrying the resolved response a link received. Links set it as the `cause`
106
- * of an `ORPCError` decoded from an error response, so details that are not part
107
- * of the error itself, such as its status or headers, stay available.
108
- *
109
- * @see {@link https://orpc.dev/docs/rpc/link#error-responses | RPC Link - Error Responses}
110
- * @see {@link https://orpc.dev/docs/openapi/link#error-responses | OpenAPI Link - Error Responses}
111
- */
112
- export declare class ResponseError extends Error {
113
- override readonly name: string;
114
- response: StandardResponse;
115
- constructor(options: ResponseErrorOptions);
116
- }
117
- export interface MalformedResponseErrorOptions extends ResponseErrorOptions {
118
- /**
119
- * @default inferred from the response body or status
120
- */
121
- message?: string | undefined;
122
- }
123
- /**
124
- * Error thrown by links when a response does not follow the expected oRPC format,
125
- * for example when a proxy or gateway answers instead of your handler. Extends
126
- * `ResponseError`, so it carries the resolved response. Unless overridden via
127
- * `options.message`, the message is inferred from the response body or status.
128
- *
129
- * Unlike `ORPCError`, it reaches a handler's callers as a generic `INTERNAL_SERVER_ERROR`
130
- * when thrown from the handler, so an upstream's response is not sent to them.
131
- *
132
- * @see {@link https://orpc.dev/docs/rpc/link#malformed-responses | RPC Link - Malformed Responses}
133
- * @see {@link https://orpc.dev/docs/openapi/link#malformed-responses | OpenAPI Link - Malformed Responses}
134
- */
135
- export declare class MalformedResponseError extends ResponseError {
136
- override readonly name = "MalformedResponseError";
137
- constructor(options: MalformedResponseErrorOptions);
138
- }
package/dist/error.mjs DELETED
@@ -1,105 +0,0 @@
1
- import { getConstructors, isPlainObject, resolveMaybeOptionalOptions } from "@orpc/shared";
2
-
3
- export const COMMON_ERROR_STATUS_MAP = {
4
- BAD_REQUEST: 400,
5
- UNAUTHORIZED: 401,
6
- PAYMENT_REQUIRED: 402,
7
- FORBIDDEN: 403,
8
- NOT_FOUND: 404,
9
- METHOD_NOT_SUPPORTED: 405,
10
- NOT_ACCEPTABLE: 406,
11
- TIMEOUT: 408,
12
- CONFLICT: 409,
13
- GONE: 410,
14
- LENGTH_REQUIRED: 411,
15
- PRECONDITION_FAILED: 412,
16
- PAYLOAD_TOO_LARGE: 413,
17
- UNSUPPORTED_MEDIA_TYPE: 415,
18
- UNPROCESSABLE_CONTENT: 422,
19
- PRECONDITION_REQUIRED: 428,
20
- TOO_MANY_REQUESTS: 429,
21
- CLIENT_CLOSED_REQUEST: 499,
22
- INTERNAL_SERVER_ERROR: 500,
23
- NOT_IMPLEMENTED: 501,
24
- BAD_GATEWAY: 502,
25
- SERVICE_UNAVAILABLE: 503,
26
- GATEWAY_TIMEOUT: 504
27
- };
28
- let ORPCErrorConstructors;
29
-
30
- export class ORPCError extends Error {
31
-
32
- static {
33
-
34
- const ORPC_ERROR_CONSTRUCTORS_SYMBOL = Symbol.for("ORPC_ERROR_CONSTRUCTORS");
35
- void (globalThis[ORPC_ERROR_CONSTRUCTORS_SYMBOL] ??= new WeakSet());
36
- ORPCErrorConstructors = globalThis[ORPC_ERROR_CONSTRUCTORS_SYMBOL];
37
- ORPCErrorConstructors.add(ORPCError);
38
- }
39
-
40
- name = "ORPCError";
41
-
42
- defined = false;
43
- code;
44
- data;
45
- constructor(code, ...rest) {
46
- const options = resolveMaybeOptionalOptions(rest);
47
- const message = options.message ?? codeToMessage(code);
48
- super(message, options);
49
- this.code = code;
50
- this.data = options.data;
51
- }
52
- toJSON() {
53
- return {
54
- defined: this.defined,
55
- code: this.code,
56
- message: this.message,
57
- data: this.data
58
- };
59
- }
60
-
61
- static [Symbol.hasInstance](instance) {
62
- if (!ORPCErrorConstructors.has(this)) {
63
-
64
- return super[Symbol.hasInstance](instance);
65
- }
66
- for (const constructor of getConstructors(instance)) {
67
- if (ORPCErrorConstructors.has(constructor)) {
68
- return true;
69
- }
70
- }
71
- return false;
72
- }
73
- }
74
-
75
- export class ResponseError extends Error {
76
- name = "ResponseError";
77
- response;
78
- constructor(options) {
79
- super(options.message ?? `Received a ${options.response.status} response.`, options);
80
- this.response = options.response;
81
- }
82
- }
83
-
84
- export class MalformedResponseError extends ResponseError {
85
- name = "MalformedResponseError";
86
- constructor(options) {
87
- super({
88
- ...options,
89
- message: options.message ?? inferMalformedResponseMessage(options.response)
90
- });
91
- }
92
- }
93
-
94
- const INFERRED_MESSAGE_MAX_LENGTH = 256;
95
- function inferMalformedResponseMessage(response) {
96
- const candidate = isPlainObject(response.body) ? response.body.message : response.body;
97
- if (typeof candidate === "string" && candidate.length > 0 && candidate.length <= INFERRED_MESSAGE_MAX_LENGTH) {
98
- return candidate;
99
- }
100
- const commonCode = Object.entries(COMMON_ERROR_STATUS_MAP).find(([, status]) => status === response.status)?.[0];
101
- return commonCode ? codeToMessage(commonCode) : "Malformed oRPC Response";
102
- }
103
- function codeToMessage(code) {
104
- return code.split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" ");
105
- }