@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.
- package/README.md +139 -102
- package/dist/adapters/fetch/index.d.ts +3 -65
- package/dist/adapters/fetch/index.js +2 -0
- package/dist/adapters/fetch/rpc-link.d.ts +14 -0
- package/dist/adapters/fetch/rpc-link.js +17 -0
- package/dist/adapters/fetch/transport.d.ts +32 -0
- package/dist/adapters/fetch/transport.js +51 -0
- package/dist/adapters/message-port/index.d.ts +4 -75
- package/dist/adapters/message-port/index.js +3 -0
- package/dist/adapters/message-port/message-port.d.ts +29 -0
- package/dist/adapters/message-port/message-port.js +38 -0
- package/dist/adapters/message-port/rpc-link.d.ts +15 -0
- package/dist/adapters/message-port/rpc-link.js +18 -0
- package/dist/adapters/message-port/transport.d.ts +35 -0
- package/dist/adapters/message-port/transport.js +38 -0
- package/dist/adapters/standard/codec.d.ts +14 -0
- package/dist/adapters/standard/index.d.ts +6 -61
- package/dist/adapters/standard/index.js +2 -0
- package/dist/adapters/standard/link.d.ts +40 -0
- package/dist/adapters/standard/link.js +101 -0
- package/dist/adapters/standard/plugin.d.ts +26 -0
- package/dist/adapters/standard/plugin.js +14 -0
- package/dist/adapters/standard/rpc-link-codec.d.ts +56 -0
- package/dist/adapters/standard/rpc-link-codec.js +100 -0
- package/dist/adapters/standard/transport.d.ts +14 -0
- package/dist/adapters/websocket/index.d.ts +3 -121
- package/dist/adapters/websocket/index.js +2 -0
- package/dist/adapters/websocket/rpc-link.d.ts +14 -0
- package/dist/adapters/websocket/rpc-link.js +17 -0
- package/dist/adapters/websocket/transport.d.ts +116 -0
- package/dist/adapters/websocket/transport.js +105 -0
- package/dist/async-iterator-object.d.ts +2 -0
- package/dist/async-iterator-object.js +28 -0
- package/dist/client-safe.d.ts +17 -0
- package/dist/client-safe.js +31 -0
- package/dist/client.d.ts +39 -0
- package/dist/client.js +37 -0
- package/dist/consts.d.ts +10 -0
- package/dist/consts.js +20 -0
- package/dist/dynamic-link.d.ts +13 -0
- package/dist/dynamic-link.js +17 -0
- package/dist/error-utils.d.ts +20 -0
- package/dist/error-utils.js +54 -0
- package/dist/error.d.ts +141 -0
- package/dist/error.js +166 -0
- package/dist/index.d.ts +14 -155
- package/dist/index.js +12 -0
- package/dist/plugins/batch.d.ts +152 -0
- package/dist/plugins/batch.js +330 -0
- package/dist/plugins/cookie-jar.d.ts +85 -0
- package/dist/plugins/cookie-jar.js +231 -0
- package/dist/plugins/dedupe.d.ts +60 -0
- package/dist/plugins/dedupe.js +183 -0
- package/dist/plugins/index.d.ts +9 -242
- package/dist/plugins/index.js +8 -0
- package/dist/plugins/request-compression.d.ts +47 -0
- package/dist/plugins/request-compression.js +132 -0
- package/dist/plugins/response-compression.d.ts +31 -0
- package/dist/plugins/response-compression.js +67 -0
- package/dist/plugins/retry-after.d.ts +43 -0
- package/dist/plugins/retry-after.js +63 -0
- package/dist/plugins/retry.d.ts +84 -0
- package/dist/plugins/retry.js +121 -0
- package/dist/plugins/timeout.d.ts +27 -0
- package/dist/plugins/timeout.js +42 -0
- package/dist/rpc-json-serializer.d.ts +99 -0
- package/dist/rpc-json-serializer.js +347 -0
- package/dist/rpc-serializer.d.ts +31 -0
- package/dist/rpc-serializer.js +102 -0
- package/dist/types.d.ts +91 -0
- package/dist/utils.d.ts +36 -0
- package/dist/utils.js +67 -0
- package/package.json +47 -35
- package/dist/adapters/fetch/index.d.mts +0 -65
- package/dist/adapters/fetch/index.mjs +0 -68
- package/dist/adapters/message-port/index.d.mts +0 -75
- package/dist/adapters/message-port/index.mjs +0 -91
- package/dist/adapters/standard/index.d.mts +0 -61
- package/dist/adapters/standard/index.mjs +0 -6
- package/dist/adapters/websocket/index.d.mts +0 -121
- package/dist/adapters/websocket/index.mjs +0 -110
- package/dist/index.d.mts +0 -155
- package/dist/index.mjs +0 -154
- package/dist/plugins/index.d.mts +0 -242
- package/dist/plugins/index.mjs +0 -574
- package/dist/shared/client.8ug8I-zu.d.mts +0 -167
- package/dist/shared/client.8ug8I-zu.d.ts +0 -167
- package/dist/shared/client.BdItY5DT.d.mts +0 -111
- package/dist/shared/client.BdItY5DT.d.ts +0 -111
- package/dist/shared/client.CPF3hX6O.d.ts +0 -96
- package/dist/shared/client.Cby_-GGh.d.mts +0 -96
- package/dist/shared/client.DMXKFDyV.mjs +0 -343
- package/dist/shared/client.DXhchJ84.mjs +0 -174
- package/dist/shared/client.Dnfj8jnT.mjs +0 -92
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { MalformedResponseError, ResponseError } from "../../error.js";
|
|
2
|
+
import { createORPCErrorFromJson, isORPCErrorJson } from "../../error-utils.js";
|
|
3
|
+
import { RPCSerializer } from "../../rpc-serializer.js";
|
|
4
|
+
import { isAsyncIteratorObject, mergeHttpPath, pathToHttpPath, stringifyJSON, value } from "@orpc/shared";
|
|
5
|
+
import { mergeStandardHeaders, parseStandardUrl } from "@standard-server/core";
|
|
6
|
+
import { toStandardHeaders } from "@standard-server/fetch";
|
|
7
|
+
// src/adapters/standard/rpc-link-codec.ts
|
|
8
|
+
var RPCLinkCodec = class {
|
|
9
|
+
baseUrl;
|
|
10
|
+
maxUrlLength;
|
|
11
|
+
fallbackMethod;
|
|
12
|
+
expectedMethod;
|
|
13
|
+
headers;
|
|
14
|
+
serializer;
|
|
15
|
+
constructor(options) {
|
|
16
|
+
this.baseUrl = options.url ?? "/";
|
|
17
|
+
this.maxUrlLength = options.maxUrlLength ?? 2083;
|
|
18
|
+
this.fallbackMethod = options.fallbackMethod ?? "POST";
|
|
19
|
+
this.expectedMethod = options.method ?? this.fallbackMethod;
|
|
20
|
+
this.headers = options.headers ?? {};
|
|
21
|
+
this.serializer = options.serializer ?? new RPCSerializer();
|
|
22
|
+
}
|
|
23
|
+
async encodeInput(input, path, options) {
|
|
24
|
+
let headers = toResolvedStandardHeaders(await value(this.headers, options, path, input));
|
|
25
|
+
if (options.lastEventId !== void 0) headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
|
|
26
|
+
const expectedMethod = await value(this.expectedMethod, options, path, input);
|
|
27
|
+
const baseUrl = await value(this.baseUrl, options, path, input);
|
|
28
|
+
const [pathname, search, hash] = parseStandardUrl(baseUrl);
|
|
29
|
+
const newPathname = mergeHttpPath(pathname, pathToHttpPath(path));
|
|
30
|
+
const serialized = this.serializer.serialize(input);
|
|
31
|
+
if (expectedMethod === "GET" && !(serialized instanceof Blob) && !(serialized instanceof ReadableStream) && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
|
|
32
|
+
const maxUrlLength = await value(this.maxUrlLength, options, path, input);
|
|
33
|
+
const mergedSearch = new URLSearchParams(search);
|
|
34
|
+
mergedSearch.append("data", stringifyJSON(serialized) ?? "");
|
|
35
|
+
const url = `${newPathname}?${mergedSearch}${hash ?? ""}`;
|
|
36
|
+
if (url.length <= maxUrlLength) return {
|
|
37
|
+
body: void 0,
|
|
38
|
+
method: expectedMethod,
|
|
39
|
+
headers,
|
|
40
|
+
url,
|
|
41
|
+
signal: options.signal
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
url: `${newPathname}${search ?? ""}${hash ?? ""}`,
|
|
46
|
+
method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod,
|
|
47
|
+
headers,
|
|
48
|
+
body: serialized,
|
|
49
|
+
signal: options.signal
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
async decodeResponse(response) {
|
|
53
|
+
const isOk = response.status < 400;
|
|
54
|
+
const body = await response.resolveBody();
|
|
55
|
+
const deserialized = await (async () => {
|
|
56
|
+
try {
|
|
57
|
+
return this.serializer.deserialize(body);
|
|
58
|
+
} catch (cause) {
|
|
59
|
+
throw new MalformedResponseError({
|
|
60
|
+
message: isOk ? "Invalid RPC response format." : void 0,
|
|
61
|
+
response: {
|
|
62
|
+
status: response.status,
|
|
63
|
+
headers: response.headers,
|
|
64
|
+
body
|
|
65
|
+
},
|
|
66
|
+
cause
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
})();
|
|
70
|
+
if (!isOk) {
|
|
71
|
+
if (isORPCErrorJson(deserialized)) return {
|
|
72
|
+
kind: "error",
|
|
73
|
+
error: createORPCErrorFromJson(deserialized, { cause: new ResponseError({ response: {
|
|
74
|
+
status: response.status,
|
|
75
|
+
headers: response.headers,
|
|
76
|
+
body
|
|
77
|
+
} }) })
|
|
78
|
+
};
|
|
79
|
+
throw new MalformedResponseError({ response: {
|
|
80
|
+
headers: response.headers,
|
|
81
|
+
status: response.status,
|
|
82
|
+
body
|
|
83
|
+
} });
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
kind: "output",
|
|
87
|
+
output: deserialized
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
function toResolvedStandardHeaders(headers) {
|
|
92
|
+
/**
|
|
93
|
+
* Headers class might not be available in some environments,
|
|
94
|
+
* so we check for the existence of `forEach` and `get`
|
|
95
|
+
* methods to determine if it's a Headers instance.
|
|
96
|
+
*/
|
|
97
|
+
if (typeof headers.forEach === "function") return toStandardHeaders(headers);
|
|
98
|
+
return headers;
|
|
99
|
+
}
|
|
100
|
+
export { RPCLinkCodec };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { ClientContext, ClientOptions } from "../../types.js";
|
|
2
|
+
import { StandardLazyResponse, StandardRequest } from "@standard-server/core";
|
|
3
|
+
/**
|
|
4
|
+
* Handles the transport layer for sending requests and receiving responses.
|
|
5
|
+
*
|
|
6
|
+
* Implementations are responsible for the actual network communication,
|
|
7
|
+
* such as HTTP fetch, WebSocket, or other transport mechanisms.
|
|
8
|
+
*/
|
|
9
|
+
export interface StandardLinkTransport<T extends ClientContext> {
|
|
10
|
+
/**
|
|
11
|
+
* @throws Transport-level errors (network failures, timeouts, etc.)
|
|
12
|
+
*/
|
|
13
|
+
send(request: StandardRequest, path: string[], options: ClientOptions<T>): Promise<StandardLazyResponse>;
|
|
14
|
+
}
|
|
@@ -1,121 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
import { EncodePeerMessageOptions, DecodePeerMessageOptions } from '@standardserver/peer';
|
|
5
|
-
import { S as StandardLinkTransport, a as StandardLink, b as StandardLinkOptions } from '../../shared/client.CPF3hX6O.js';
|
|
6
|
-
import { RPCLinkCodecOptions } from '../standard/index.js';
|
|
7
|
-
import '../../shared/client.BdItY5DT.js';
|
|
8
|
-
|
|
9
|
-
type WebSocketLike = Pick<WebSocket, 'addEventListener' | 'removeEventListener' | 'send' | 'readyState'>;
|
|
10
|
-
interface WebsocketLinkTransportAttemptInfo {
|
|
11
|
-
/**
|
|
12
|
-
* Total number of connection attempts for this transport's lifetime.
|
|
13
|
-
* Starts at 1 on the first attempt, increments on every subsequent
|
|
14
|
-
* attempt, and never resets.
|
|
15
|
-
*/
|
|
16
|
-
totalAttempt: number;
|
|
17
|
-
/**
|
|
18
|
-
* Attempt number within the current (re)connect cycle.
|
|
19
|
-
* Starts at 1, increments on each consecutive failure, and resets to 1
|
|
20
|
-
* once a connection succeeds. Use this for backoff calculations.
|
|
21
|
-
*/
|
|
22
|
-
attempt: number;
|
|
23
|
-
}
|
|
24
|
-
interface WebsocketLinkTransportReconnectOptions {
|
|
25
|
-
/**
|
|
26
|
-
* Whether to automatically reconnect when the connection is lost.
|
|
27
|
-
*
|
|
28
|
-
* @default false
|
|
29
|
-
*/
|
|
30
|
-
enabled: boolean;
|
|
31
|
-
/**
|
|
32
|
-
* Delay before a (re)connect attempt, in milliseconds.
|
|
33
|
-
*
|
|
34
|
-
* @default info => info.attempt === 1 ? 0 : 2_000
|
|
35
|
-
*/
|
|
36
|
-
delay?: undefined | ((info: WebsocketLinkTransportAttemptInfo) => number);
|
|
37
|
-
/**
|
|
38
|
-
* Maximum number of consecutive failed attempts before giving up.
|
|
39
|
-
* When exceeded, `getConnectedPeer` throws instead of retrying.
|
|
40
|
-
* Should greater than 1
|
|
41
|
-
*
|
|
42
|
-
* @default Infinity
|
|
43
|
-
*/
|
|
44
|
-
maxAttempt?: undefined | number;
|
|
45
|
-
/**
|
|
46
|
-
* Whether to proactively reconnect right after the socket closes,
|
|
47
|
-
* rather than waiting for the next call to trigger reconnection.
|
|
48
|
-
* Reduces latency for the next request.
|
|
49
|
-
*
|
|
50
|
-
* @default { enabled: false }
|
|
51
|
-
*/
|
|
52
|
-
onClose?: undefined | {
|
|
53
|
-
/**
|
|
54
|
-
* Whether to proactively reconnect right after the socket closes,
|
|
55
|
-
* rather than waiting for the next call to trigger reconnection.
|
|
56
|
-
* Reduces latency for the next request.
|
|
57
|
-
*
|
|
58
|
-
* @default false
|
|
59
|
-
*/
|
|
60
|
-
enabled: boolean;
|
|
61
|
-
/**
|
|
62
|
-
* Delay before reconnecting after the socket closes, in milliseconds.
|
|
63
|
-
*
|
|
64
|
-
* @default 0
|
|
65
|
-
*/
|
|
66
|
-
delay?: number;
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
interface WebsocketLinkTransportOptions<_T extends ClientContext> {
|
|
70
|
-
/**
|
|
71
|
-
* Returns a WebSocket instance for peer communication.
|
|
72
|
-
* Can be async for lazy resolution.
|
|
73
|
-
*/
|
|
74
|
-
connect: (info: WebsocketLinkTransportAttemptInfo) => Promisable<WebSocketLike>;
|
|
75
|
-
/**
|
|
76
|
-
* Whether to connect immediately on initialization, instead of waiting
|
|
77
|
-
* for the first call. Reduces latency for the first request.
|
|
78
|
-
*
|
|
79
|
-
* @default false
|
|
80
|
-
*/
|
|
81
|
-
connectOnInit?: undefined | boolean;
|
|
82
|
-
/**
|
|
83
|
-
* Reconnection behavior when the connection is lost.
|
|
84
|
-
*
|
|
85
|
-
* @default { enabled: false }
|
|
86
|
-
*/
|
|
87
|
-
reconnect?: undefined | WebsocketLinkTransportReconnectOptions;
|
|
88
|
-
/**
|
|
89
|
-
* Options for encoding peer messages. such as `prefix` for distinguishing messages on the same channel..
|
|
90
|
-
*/
|
|
91
|
-
encodePeerMessage?: EncodePeerMessageOptions | undefined;
|
|
92
|
-
/**
|
|
93
|
-
* Options for decoding peer messages. such as `prefix` for distinguishing messages on the same channel..
|
|
94
|
-
*/
|
|
95
|
-
decodePeerMessage?: DecodePeerMessageOptions | undefined;
|
|
96
|
-
}
|
|
97
|
-
declare class WebsocketLinkTransport<T extends ClientContext> implements StandardLinkTransport<T> {
|
|
98
|
-
private readonly connect;
|
|
99
|
-
private readonly reconnectEnabled;
|
|
100
|
-
private readonly reconnectDelay;
|
|
101
|
-
private readonly reconnectMaxAttempt;
|
|
102
|
-
private readonly reconnectOnCloseEnabled;
|
|
103
|
-
private readonly reconnectOnCloseDelay;
|
|
104
|
-
private readonly encodePeerMessageOptions;
|
|
105
|
-
private readonly decodePeerMessageOptions;
|
|
106
|
-
constructor(options: WebsocketLinkTransportOptions<T>);
|
|
107
|
-
send(standardRequest: StandardRequest, _path: string[], _options: ClientOptions<T>): Promise<StandardLazyResponse>;
|
|
108
|
-
private totalAttempt;
|
|
109
|
-
private attempt;
|
|
110
|
-
private current;
|
|
111
|
-
private getConnectedPeer;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
interface RPCLinkOptions<T extends ClientContext> extends StandardLinkOptions<T>, WebsocketLinkTransportOptions<T>, RPCLinkCodecOptions<T> {
|
|
115
|
-
}
|
|
116
|
-
declare class RPCLink<T extends ClientContext> extends StandardLink<T> {
|
|
117
|
-
constructor(options: RPCLinkOptions<T>);
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
export { RPCLink, WebsocketLinkTransport };
|
|
121
|
-
export type { RPCLinkOptions, WebSocketLike, WebsocketLinkTransportAttemptInfo, WebsocketLinkTransportOptions, WebsocketLinkTransportReconnectOptions };
|
|
1
|
+
import { RPCLink, RPCLinkOptions } from "./rpc-link.js";
|
|
2
|
+
import { WebSocketLike, WebSocketLinkTransport, WebSocketLinkTransportAttemptInfo, WebSocketLinkTransportOptions, WebSocketLinkTransportReconnectOnCloseOptions, WebSocketLinkTransportReconnectOptions } from "./transport.js";
|
|
3
|
+
export { RPCLink, RPCLinkOptions, WebSocketLike, WebSocketLinkTransport, WebSocketLinkTransportAttemptInfo, WebSocketLinkTransportOptions, WebSocketLinkTransportReconnectOnCloseOptions, WebSocketLinkTransportReconnectOptions };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { ClientContext } from "../../types.js";
|
|
2
|
+
import { StandardLink, StandardLinkOptions } from "../standard/link.js";
|
|
3
|
+
import { RPCLinkCodecOptions } from "../standard/rpc-link-codec.js";
|
|
4
|
+
import "../standard/index.js";
|
|
5
|
+
import { WebSocketLinkTransportOptions } from "./transport.js";
|
|
6
|
+
export interface RPCLinkOptions<T extends ClientContext> extends StandardLinkOptions<T>, WebSocketLinkTransportOptions<T>, RPCLinkCodecOptions<T> {}
|
|
7
|
+
/**
|
|
8
|
+
* Client link that communicates with an RPC Handler over a WebSocket connection.
|
|
9
|
+
*
|
|
10
|
+
* @see {@link https://orpc.dev/docs/adapters/websocket | WebSocket Adapters}
|
|
11
|
+
*/
|
|
12
|
+
export declare class RPCLink<T extends ClientContext> extends StandardLink<T> {
|
|
13
|
+
constructor(options: RPCLinkOptions<T>);
|
|
14
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { RPCLinkCodec } from "../standard/rpc-link-codec.js";
|
|
2
|
+
import { StandardLink } from "../standard/link.js";
|
|
3
|
+
import { WebSocketLinkTransport } from "./transport.js";
|
|
4
|
+
// src/adapters/websocket/rpc-link.ts
|
|
5
|
+
/**
|
|
6
|
+
* Client link that communicates with an RPC Handler over a WebSocket connection.
|
|
7
|
+
*
|
|
8
|
+
* @see {@link https://orpc.dev/docs/adapters/websocket | WebSocket Adapters}
|
|
9
|
+
*/
|
|
10
|
+
var RPCLink = class extends StandardLink {
|
|
11
|
+
constructor(options) {
|
|
12
|
+
const codec = new RPCLinkCodec(options);
|
|
13
|
+
const transport = new WebSocketLinkTransport(options);
|
|
14
|
+
super(codec, transport, options);
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
export { RPCLink };
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { ClientContext, ClientOptions } from "../../types.js";
|
|
2
|
+
import { StandardLinkTransport } from "../standard/transport.js";
|
|
3
|
+
import "../standard/index.js";
|
|
4
|
+
import { Promisable } from "@orpc/shared";
|
|
5
|
+
import { StandardLazyResponse, StandardRequest } from "@standard-server/core";
|
|
6
|
+
import { DecodePeerMessageOptions, EncodePeerMessageOptions } from "@standard-server/peer";
|
|
7
|
+
export type WebSocketLike = Pick<WebSocket, "addEventListener" | "removeEventListener" | "send" | "readyState">;
|
|
8
|
+
export interface WebSocketLinkTransportAttemptInfo {
|
|
9
|
+
/**
|
|
10
|
+
* Total number of connection attempts for this transport's lifetime.
|
|
11
|
+
* Starts at 1 on the first attempt, increments on every subsequent
|
|
12
|
+
* attempt, and never resets.
|
|
13
|
+
*/
|
|
14
|
+
totalAttempt: number;
|
|
15
|
+
/**
|
|
16
|
+
* Attempt number within the current (re)connect cycle.
|
|
17
|
+
* Starts at 1, increments on each consecutive failure, and resets to 1
|
|
18
|
+
* once a connection succeeds or the cycle gives up. Use this for backoff calculations.
|
|
19
|
+
*/
|
|
20
|
+
attempt: number;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Reconnection behavior when the connection is lost. Passing it enables reconnection.
|
|
24
|
+
*/
|
|
25
|
+
export interface WebSocketLinkTransportReconnectOptions {
|
|
26
|
+
/**
|
|
27
|
+
* Delay before a (re)connect attempt, in milliseconds.
|
|
28
|
+
*
|
|
29
|
+
* @default info => info.attempt === 1 ? 0 : 2_000
|
|
30
|
+
*/
|
|
31
|
+
delay?: ((info: WebSocketLinkTransportAttemptInfo) => number) | undefined;
|
|
32
|
+
/**
|
|
33
|
+
* Maximum number of consecutive failed attempts before giving up.
|
|
34
|
+
* When reached, calls waiting for the connection fail, and the next
|
|
35
|
+
* call starts a new reconnect cycle.
|
|
36
|
+
* Should greater than 1
|
|
37
|
+
*
|
|
38
|
+
* @default Infinity
|
|
39
|
+
*/
|
|
40
|
+
maxAttempt?: number | undefined;
|
|
41
|
+
/**
|
|
42
|
+
* Maximum number of connection attempts over the transport's lifetime,
|
|
43
|
+
* successful ones included (see `totalAttempt`).
|
|
44
|
+
* When reached, calls that need a new connection fail instead of connecting.
|
|
45
|
+
*
|
|
46
|
+
* @default Infinity
|
|
47
|
+
*/
|
|
48
|
+
maxTotalAttempt?: number | undefined;
|
|
49
|
+
/**
|
|
50
|
+
* Whether to proactively reconnect right after the socket closes,
|
|
51
|
+
* rather than waiting for the next call to trigger reconnection.
|
|
52
|
+
* Reduces latency for the next request.
|
|
53
|
+
*
|
|
54
|
+
* `true` enables it, {@link WebSocketLinkTransportReconnectOnCloseOptions} enables and customizes it.
|
|
55
|
+
*
|
|
56
|
+
* @default false
|
|
57
|
+
*/
|
|
58
|
+
onClose?: boolean | WebSocketLinkTransportReconnectOnCloseOptions | undefined;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Proactive reconnection right after the socket closes. Passing it enables it.
|
|
62
|
+
*/
|
|
63
|
+
export interface WebSocketLinkTransportReconnectOnCloseOptions {
|
|
64
|
+
/**
|
|
65
|
+
* Delay before reconnecting after the socket closes, in milliseconds.
|
|
66
|
+
*
|
|
67
|
+
* @default 0
|
|
68
|
+
*/
|
|
69
|
+
delay?: number | undefined;
|
|
70
|
+
}
|
|
71
|
+
export interface WebSocketLinkTransportOptions<_T extends ClientContext> {
|
|
72
|
+
/**
|
|
73
|
+
* Returns a WebSocket instance for peer communication.
|
|
74
|
+
* Can be async for lazy resolution.
|
|
75
|
+
*/
|
|
76
|
+
connect: (info: WebSocketLinkTransportAttemptInfo) => Promisable<WebSocketLike>;
|
|
77
|
+
/**
|
|
78
|
+
* Whether to connect immediately on initialization, instead of waiting
|
|
79
|
+
* for the first call. Reduces latency for the first request.
|
|
80
|
+
*
|
|
81
|
+
* @default false
|
|
82
|
+
*/
|
|
83
|
+
connectOnInit?: boolean | undefined;
|
|
84
|
+
/**
|
|
85
|
+
* Reconnection when the connection is lost. `true` enables it,
|
|
86
|
+
* {@link WebSocketLinkTransportReconnectOptions} enables and customizes it.
|
|
87
|
+
*
|
|
88
|
+
* @default false
|
|
89
|
+
*/
|
|
90
|
+
reconnect?: boolean | WebSocketLinkTransportReconnectOptions | undefined;
|
|
91
|
+
/**
|
|
92
|
+
* Options for encoding peer messages. such as `prefix` for distinguishing messages on the same channel..
|
|
93
|
+
*/
|
|
94
|
+
encodePeerMessage?: EncodePeerMessageOptions | undefined;
|
|
95
|
+
/**
|
|
96
|
+
* Options for decoding peer messages. such as `prefix` for distinguishing messages on the same channel..
|
|
97
|
+
*/
|
|
98
|
+
decodePeerMessage?: DecodePeerMessageOptions | undefined;
|
|
99
|
+
}
|
|
100
|
+
export declare class WebSocketLinkTransport<T extends ClientContext> implements StandardLinkTransport<T> {
|
|
101
|
+
private readonly connect;
|
|
102
|
+
private readonly reconnectEnabled;
|
|
103
|
+
private readonly reconnectDelay;
|
|
104
|
+
private readonly reconnectMaxAttempt;
|
|
105
|
+
private readonly reconnectMaxTotalAttempt;
|
|
106
|
+
private readonly reconnectOnCloseEnabled;
|
|
107
|
+
private readonly reconnectOnCloseDelay;
|
|
108
|
+
private readonly encodePeerMessageOptions;
|
|
109
|
+
private readonly decodePeerMessageOptions;
|
|
110
|
+
constructor(options: WebSocketLinkTransportOptions<T>);
|
|
111
|
+
send(standardRequest: StandardRequest, _path: string[], _options: ClientOptions<T>): Promise<StandardLazyResponse>;
|
|
112
|
+
private totalAttempt;
|
|
113
|
+
private attempt;
|
|
114
|
+
private current;
|
|
115
|
+
private getConnectedPeer;
|
|
116
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
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
|
|
4
|
+
/**
|
|
5
|
+
* Some env maybe not available WebSocket global, like node 20
|
|
6
|
+
*/
|
|
7
|
+
const WEBSOCKET_CONNECTING = 0;
|
|
8
|
+
const WEBSOCKET_OPEN = 1;
|
|
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 };
|
|
@@ -0,0 +1,2 @@
|
|
|
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>;
|
|
@@ -0,0 +1,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
|
+
});
|
|
27
|
+
}
|
|
28
|
+
export { wrapAsyncIteratorPreservingEventMeta };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { AnyNestedClient, Client, ClientRest } from "./types.js";
|
|
2
|
+
import { SafeResult } from "./utils.js";
|
|
3
|
+
export type SafeClient<T extends AnyNestedClient> = SafeClientInternal<T>;
|
|
4
|
+
export type SafeClientInternal<T> = T extends Client<infer UContext, infer UInput, infer UOutput, infer UError> ? (...rest: ClientRest<UContext, UInput>) => Promise<SafeResult<UOutput, UError>> : { [K in keyof T]: SafeClientInternal<T[K] & {}>; };
|
|
5
|
+
/**
|
|
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
|
+
export declare function createSafeClient<T extends AnyNestedClient>(client: T): SafeClient<T>;
|
|
@@ -0,0 +1,31 @@
|
|
|
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
|
|
5
|
+
/**
|
|
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
|
+
} });
|
|
30
|
+
}
|
|
31
|
+
export { createSafeClient };
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { AnyNestedClient, Client, ClientContext, ClientLink, ClientOptions, InferClientContext, InferClientError } from "./types.js";
|
|
2
|
+
import { Interceptor, PromiseWithError } from "@orpc/shared";
|
|
3
|
+
export interface ORPCClientInterceptorOptions<TClientContext extends ClientContext, TInput> extends ClientOptions<TClientContext> {
|
|
4
|
+
path: string[];
|
|
5
|
+
input: TInput;
|
|
6
|
+
}
|
|
7
|
+
export type ORPCClientInterceptor<TClientContext extends ClientContext, TInput, TOutput, TError> = Interceptor<ORPCClientInterceptorOptions<TClientContext, TInput>, PromiseWithError<TOutput, TError>>;
|
|
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;
|
|
13
|
+
}
|
|
14
|
+
export type ORPCClientScoped<T extends AnyNestedClient> = ORPCClientScopedInternal<T>;
|
|
15
|
+
export type ORPCClientScopedInternal<T> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? ORPCClientScopedOptions<UClientContext, UInput, UOutput, UError> : { [K in keyof T]?: ORPCClientScopedInternal<T[K] & {}> | undefined; };
|
|
16
|
+
export interface ORPCClientOptions<T extends AnyNestedClient> {
|
|
17
|
+
/**
|
|
18
|
+
* Use as base path for all procedure, useful when you only want to call a subset of the procedure.
|
|
19
|
+
*/
|
|
20
|
+
path?: string[] | undefined;
|
|
21
|
+
/**
|
|
22
|
+
* Interceptors that wrap the entire client call lifecycle, applied to every procedure call.
|
|
23
|
+
*/
|
|
24
|
+
interceptors?: ORPCClientInterceptor<InferClientContext<T>, unknown, unknown, InferClientError<T>>[] | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* Per-procedure options following the shape of the router.
|
|
27
|
+
* Allows fine-grained configuration (e.g. additional interceptors) for individual procedures
|
|
28
|
+
* without affecting the rest of the router.
|
|
29
|
+
*/
|
|
30
|
+
scoped?: ORPCClientScoped<T> | undefined;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Creates a fully typed oRPC client from a link.
|
|
34
|
+
* The returned client mirrors the shape of your router or contract,
|
|
35
|
+
* so calling a procedure is as simple as calling a function.
|
|
36
|
+
*
|
|
37
|
+
* @see {@link https://orpc.dev/docs/client/client-side | Client-Side Clients}
|
|
38
|
+
*/
|
|
39
|
+
export declare function createORPCClient<T extends AnyNestedClient>(link: ClientLink<InferClientContext<T>>, { path, ...options }?: NoInfer<ORPCClientOptions<T>>): T;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
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
|
|
5
|
+
/**
|
|
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
|
+
} });
|
|
36
|
+
}
|
|
37
|
+
export { createORPCClient };
|
package/dist/consts.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
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>;
|