@orpc/client 0.0.0-next.d137cdf → 0.0.0-next.d16a1b6

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.
@@ -0,0 +1,321 @@
1
+ import { intercept, isAsyncIteratorObject, value, isObject, stringifyJSON, trim } from '@orpc/shared';
2
+ import { c as createAutoRetryEventIterator, m as mapEventIterator, t as toORPCError, O as ORPCError } from './client.DcaJQZfy.mjs';
3
+ import { ErrorEvent } from '@orpc/standard-server';
4
+
5
+ class InvalidEventIteratorRetryResponse extends Error {
6
+ }
7
+ class StandardLink {
8
+ constructor(codec, sender, options) {
9
+ this.codec = codec;
10
+ this.sender = sender;
11
+ this.eventIteratorMaxRetries = options.eventIteratorMaxRetries ?? 5;
12
+ this.eventIteratorRetryDelay = options.eventIteratorRetryDelay ?? ((o) => o.lastRetry ?? 1e3 * 2 ** o.retryTimes);
13
+ this.eventIteratorShouldRetry = options.eventIteratorShouldRetry ?? true;
14
+ this.interceptors = options.interceptors ?? [];
15
+ this.clientInterceptors = options.clientInterceptors ?? [];
16
+ }
17
+ eventIteratorMaxRetries;
18
+ eventIteratorRetryDelay;
19
+ eventIteratorShouldRetry;
20
+ interceptors;
21
+ clientInterceptors;
22
+ call(path, input, options) {
23
+ return intercept(this.interceptors, { path, input, options }, async ({ path: path2, input: input2, options: options2 }) => {
24
+ const output = await this.#call(path2, input2, options2);
25
+ if (!isAsyncIteratorObject(output)) {
26
+ return output;
27
+ }
28
+ return createAutoRetryEventIterator(output, async (reconnectOptions) => {
29
+ const maxRetries = await value(this.eventIteratorMaxRetries, reconnectOptions, options2, path2, input2);
30
+ if (options2.signal?.aborted || reconnectOptions.retryTimes > maxRetries) {
31
+ return null;
32
+ }
33
+ const shouldRetry = await value(this.eventIteratorShouldRetry, reconnectOptions, options2, path2, input2);
34
+ if (!shouldRetry) {
35
+ return null;
36
+ }
37
+ const retryDelay = await value(this.eventIteratorRetryDelay, reconnectOptions, options2, path2, input2);
38
+ await new Promise((resolve) => setTimeout(resolve, retryDelay));
39
+ const updatedOptions = { ...options2, lastEventId: reconnectOptions.lastEventId };
40
+ const maybeIterator = await this.#call(path2, input2, updatedOptions);
41
+ if (!isAsyncIteratorObject(maybeIterator)) {
42
+ throw new InvalidEventIteratorRetryResponse("Invalid EventSource retry response");
43
+ }
44
+ return maybeIterator;
45
+ }, options2.lastEventId);
46
+ });
47
+ }
48
+ async #call(path, input, options) {
49
+ const request = await this.codec.encode(path, input, options);
50
+ const response = await intercept(
51
+ this.clientInterceptors,
52
+ { request },
53
+ ({ request: request2 }) => this.sender.call(request2, options, path, input)
54
+ );
55
+ const output = await this.codec.decode(response, options, path, input);
56
+ return output;
57
+ }
58
+ }
59
+
60
+ class RPCJsonSerializer {
61
+ serialize(data, segments = [], meta = [], maps = [], blobs = []) {
62
+ if (data instanceof Blob) {
63
+ maps.push(segments);
64
+ blobs.push(data);
65
+ return [data, meta, maps, blobs];
66
+ }
67
+ if (typeof data === "bigint") {
68
+ meta.push([0, segments]);
69
+ return [data.toString(), meta, maps, blobs];
70
+ }
71
+ if (data instanceof Date) {
72
+ meta.push([1, segments]);
73
+ if (Number.isNaN(data.getTime())) {
74
+ return [null, meta, maps, blobs];
75
+ }
76
+ return [data.toISOString(), meta, maps, blobs];
77
+ }
78
+ if (Number.isNaN(data)) {
79
+ meta.push([2, segments]);
80
+ return [null, meta, maps, blobs];
81
+ }
82
+ if (data instanceof URL) {
83
+ meta.push([4, segments]);
84
+ return [data.toString(), meta, maps, blobs];
85
+ }
86
+ if (data instanceof RegExp) {
87
+ meta.push([5, segments]);
88
+ return [data.toString(), meta, maps, blobs];
89
+ }
90
+ if (data instanceof Set) {
91
+ const result = this.serialize(Array.from(data), segments, meta, maps, blobs);
92
+ meta.push([6, segments]);
93
+ return result;
94
+ }
95
+ if (data instanceof Map) {
96
+ const result = this.serialize(Array.from(data.entries()), segments, meta, maps, blobs);
97
+ meta.push([7, segments]);
98
+ return result;
99
+ }
100
+ if (Array.isArray(data)) {
101
+ const json = data.map((v, i) => {
102
+ if (v === void 0) {
103
+ meta.push([3, [...segments, i]]);
104
+ return v;
105
+ }
106
+ return this.serialize(v, [...segments, i], meta, maps, blobs)[0];
107
+ });
108
+ return [json, meta, maps, blobs];
109
+ }
110
+ if (isObject(data)) {
111
+ const json = {};
112
+ for (const k in data) {
113
+ json[k] = this.serialize(data[k], [...segments, k], meta, maps, blobs)[0];
114
+ }
115
+ return [json, meta, maps, blobs];
116
+ }
117
+ return [data, meta, maps, blobs];
118
+ }
119
+ deserialize(json, meta, maps, getBlob) {
120
+ const ref = { data: json };
121
+ if (maps && getBlob) {
122
+ maps.forEach((segments, i) => {
123
+ let currentRef = ref;
124
+ let preSegment = "data";
125
+ segments.forEach((segment) => {
126
+ currentRef = currentRef[preSegment];
127
+ preSegment = segment;
128
+ });
129
+ currentRef[preSegment] = getBlob(i);
130
+ });
131
+ }
132
+ for (const [type, segments] of meta) {
133
+ let currentRef = ref;
134
+ let preSegment = "data";
135
+ segments.forEach((segment) => {
136
+ currentRef = currentRef[preSegment];
137
+ preSegment = segment;
138
+ });
139
+ switch (type) {
140
+ case 0:
141
+ currentRef[preSegment] = BigInt(currentRef[preSegment]);
142
+ break;
143
+ case 1:
144
+ currentRef[preSegment] = new Date(currentRef[preSegment] ?? "Invalid Date");
145
+ break;
146
+ case 2:
147
+ currentRef[preSegment] = Number.NaN;
148
+ break;
149
+ case 3:
150
+ currentRef[preSegment] = void 0;
151
+ break;
152
+ case 4:
153
+ currentRef[preSegment] = new URL(currentRef[preSegment]);
154
+ break;
155
+ case 5: {
156
+ const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
157
+ currentRef[preSegment] = new RegExp(pattern, flags);
158
+ break;
159
+ }
160
+ case 6:
161
+ currentRef[preSegment] = new Set(currentRef[preSegment]);
162
+ break;
163
+ case 7:
164
+ currentRef[preSegment] = new Map(currentRef[preSegment]);
165
+ break;
166
+ }
167
+ }
168
+ return ref.data;
169
+ }
170
+ }
171
+
172
+ class RPCSerializer {
173
+ constructor(jsonSerializer = new RPCJsonSerializer()) {
174
+ this.jsonSerializer = jsonSerializer;
175
+ }
176
+ serialize(data) {
177
+ if (isAsyncIteratorObject(data)) {
178
+ return mapEventIterator(data, {
179
+ value: async (value) => this.#serialize(value, false),
180
+ error: async (e) => {
181
+ return new ErrorEvent({
182
+ data: this.#serialize(toORPCError(e).toJSON(), false),
183
+ cause: e
184
+ });
185
+ }
186
+ });
187
+ }
188
+ return this.#serialize(data, true);
189
+ }
190
+ #serialize(data, enableFormData) {
191
+ if (data === void 0 || data instanceof Blob) {
192
+ return data;
193
+ }
194
+ const [json, meta_, maps, blobs] = this.jsonSerializer.serialize(data);
195
+ const meta = meta_.length === 0 ? void 0 : meta_;
196
+ if (!enableFormData || blobs.length === 0) {
197
+ return {
198
+ json,
199
+ meta
200
+ };
201
+ }
202
+ const form = new FormData();
203
+ form.set("data", stringifyJSON({ json, meta, maps }));
204
+ blobs.forEach((blob, i) => {
205
+ form.set(i.toString(), blob);
206
+ });
207
+ return form;
208
+ }
209
+ deserialize(data) {
210
+ if (isAsyncIteratorObject(data)) {
211
+ return mapEventIterator(data, {
212
+ value: async (value) => this.#deserialize(value),
213
+ error: async (e) => {
214
+ if (!(e instanceof ErrorEvent)) {
215
+ return e;
216
+ }
217
+ const deserialized = this.#deserialize(e.data);
218
+ if (ORPCError.isValidJSON(deserialized)) {
219
+ return ORPCError.fromJSON(deserialized, { cause: e });
220
+ }
221
+ return new ErrorEvent({
222
+ data: deserialized,
223
+ cause: e
224
+ });
225
+ }
226
+ });
227
+ }
228
+ return this.#deserialize(data);
229
+ }
230
+ #deserialize(data) {
231
+ if (data === void 0 || data instanceof Blob) {
232
+ return data;
233
+ }
234
+ if (!(data instanceof FormData)) {
235
+ return this.jsonSerializer.deserialize(data.json, data.meta ?? []);
236
+ }
237
+ const serialized = JSON.parse(data.get("data"));
238
+ return this.jsonSerializer.deserialize(
239
+ serialized.json,
240
+ serialized.meta ?? [],
241
+ serialized.maps,
242
+ (i) => data.get(i.toString())
243
+ );
244
+ }
245
+ }
246
+
247
+ class StandardRPCLinkCodec {
248
+ baseUrl;
249
+ maxUrlLength;
250
+ fallbackMethod;
251
+ expectedMethod;
252
+ headers;
253
+ rpcSerializer;
254
+ constructor(options) {
255
+ this.baseUrl = options.url;
256
+ this.maxUrlLength = options.maxUrlLength ?? 2083;
257
+ this.fallbackMethod = options.fallbackMethod ?? "POST";
258
+ this.expectedMethod = options.method ?? this.fallbackMethod;
259
+ this.headers = options.headers ?? {};
260
+ this.rpcSerializer = options.rpcSerializer ?? new RPCSerializer();
261
+ }
262
+ async encode(path, input, options) {
263
+ const expectedMethod = await value(this.expectedMethod, options, path, input);
264
+ const headers = await value(this.headers, options, path, input);
265
+ const baseUrl = await value(this.baseUrl, options, path, input);
266
+ const url = new URL(`${trim(baseUrl.toString(), "/")}/${path.map(encodeURIComponent).join("/")}`);
267
+ const serialized = this.rpcSerializer.serialize(input);
268
+ if (expectedMethod === "GET" && !(serialized instanceof FormData) && !(serialized instanceof Blob) && !isAsyncIteratorObject(serialized)) {
269
+ const maxUrlLength = await value(this.maxUrlLength, options, path, input);
270
+ const getUrl = new URL(url);
271
+ getUrl.searchParams.append("data", stringifyJSON(serialized) ?? "");
272
+ if (getUrl.toString().length <= maxUrlLength) {
273
+ return {
274
+ body: void 0,
275
+ method: expectedMethod,
276
+ headers,
277
+ url: getUrl,
278
+ signal: options.signal
279
+ };
280
+ }
281
+ }
282
+ return {
283
+ url,
284
+ method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod,
285
+ headers,
286
+ body: serialized,
287
+ signal: options.signal
288
+ };
289
+ }
290
+ async decode(response) {
291
+ const isOk = response.status >= 200 && response.status < 300;
292
+ const deserialized = await (async () => {
293
+ let isBodyOk = false;
294
+ try {
295
+ const body = await response.body();
296
+ isBodyOk = true;
297
+ return this.rpcSerializer.deserialize(body);
298
+ } catch (error) {
299
+ if (!isBodyOk) {
300
+ throw new Error("Cannot parse response body, please check the response body and content-type.", {
301
+ cause: error
302
+ });
303
+ }
304
+ throw new Error("Invalid RPC response format.", {
305
+ cause: error
306
+ });
307
+ }
308
+ })();
309
+ if (!isOk) {
310
+ if (ORPCError.isValidJSON(deserialized)) {
311
+ throw ORPCError.fromJSON(deserialized);
312
+ }
313
+ throw new Error("Invalid RPC error response format.", {
314
+ cause: deserialized
315
+ });
316
+ }
317
+ return deserialized;
318
+ }
319
+ }
320
+
321
+ export { InvalidEventIteratorRetryResponse as I, RPCJsonSerializer as R, StandardLink as S, StandardRPCLinkCodec as a, RPCSerializer as b };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/client",
3
3
  "type": "module",
4
- "version": "0.0.0-next.d137cdf",
4
+ "version": "0.0.0-next.d16a1b6",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -15,33 +15,34 @@
15
15
  ],
16
16
  "exports": {
17
17
  ".": {
18
- "types": "./dist/src/index.d.ts",
19
- "import": "./dist/index.js",
20
- "default": "./dist/index.js"
18
+ "types": "./dist/index.d.mts",
19
+ "import": "./dist/index.mjs",
20
+ "default": "./dist/index.mjs"
21
21
  },
22
- "./🔒/*": {
23
- "types": "./dist/src/*.d.ts"
22
+ "./standard": {
23
+ "types": "./dist/adapters/standard/index.d.mts",
24
+ "import": "./dist/adapters/standard/index.mjs",
25
+ "default": "./dist/adapters/standard/index.mjs"
26
+ },
27
+ "./fetch": {
28
+ "types": "./dist/adapters/fetch/index.d.mts",
29
+ "import": "./dist/adapters/fetch/index.mjs",
30
+ "default": "./dist/adapters/fetch/index.mjs"
24
31
  }
25
32
  },
26
33
  "files": [
27
- "!**/*.map",
28
- "!**/*.tsbuildinfo",
29
34
  "dist"
30
35
  ],
31
- "peerDependencies": {
32
- "@orpc/server": "0.0.0-next.d137cdf",
33
- "@orpc/contract": "0.0.0-next.d137cdf"
34
- },
35
36
  "dependencies": {
36
- "@orpc/shared": "0.0.0-next.d137cdf",
37
- "@orpc/transformer": "0.0.0-next.d137cdf"
37
+ "@orpc/shared": "0.0.0-next.d16a1b6",
38
+ "@orpc/standard-server": "0.0.0-next.d16a1b6",
39
+ "@orpc/standard-server-fetch": "0.0.0-next.d16a1b6"
38
40
  },
39
41
  "devDependencies": {
40
- "zod": "^3.23.8",
41
- "@orpc/openapi": "0.0.0-next.d137cdf"
42
+ "zod": "^3.24.1"
42
43
  },
43
44
  "scripts": {
44
- "build": "tsup --clean --sourcemap --entry.index=src/index.ts --format=esm --onSuccess='tsc -b --noCheck'",
45
+ "build": "unbuild",
45
46
  "build:watch": "pnpm run build --watch",
46
47
  "type:check": "tsc -b"
47
48
  }
package/dist/index.js DELETED
@@ -1,83 +0,0 @@
1
- // src/procedure.ts
2
- import {
3
- ORPC_HEADER,
4
- ORPC_HEADER_VALUE
5
- } from "@orpc/contract";
6
- import { trim } from "@orpc/shared";
7
- import { ORPCError } from "@orpc/shared/error";
8
- import { ORPCDeserializer, ORPCSerializer } from "@orpc/transformer";
9
- function createProcedureClient(options) {
10
- const serializer = new ORPCSerializer();
11
- const deserializer = new ORPCDeserializer();
12
- const client = async (input) => {
13
- const fetch_ = options.fetch ?? fetch;
14
- const url = `${trim(options.baseURL, "/")}/${options.path.map(encodeURIComponent).join("/")}`;
15
- let headers = await options.headers?.(input);
16
- headers = headers instanceof Headers ? headers : new Headers(headers);
17
- const { body, headers: headers_ } = serializer.serialize(input);
18
- for (const [key, value] of headers_.entries()) {
19
- headers.set(key, value);
20
- }
21
- headers.set(ORPC_HEADER, ORPC_HEADER_VALUE);
22
- const response = await fetch_(url, {
23
- method: "POST",
24
- headers,
25
- body
26
- });
27
- const json = await (async () => {
28
- try {
29
- return await deserializer.deserialize(response);
30
- } catch (e) {
31
- throw new ORPCError({
32
- code: "INTERNAL_SERVER_ERROR",
33
- message: "Cannot parse response.",
34
- cause: e
35
- });
36
- }
37
- })();
38
- if (!response.ok) {
39
- throw ORPCError.fromJSON(json) ?? new ORPCError({
40
- status: response.status,
41
- code: "INTERNAL_SERVER_ERROR",
42
- message: "Internal server error"
43
- });
44
- }
45
- return json;
46
- };
47
- return client;
48
- }
49
-
50
- // src/router.ts
51
- function createRouterClient(options) {
52
- const path = options?.path ?? [];
53
- const client = new Proxy(
54
- createProcedureClient({
55
- baseURL: options.baseURL,
56
- fetch: options.fetch,
57
- headers: options.headers,
58
- path
59
- }),
60
- {
61
- get(target, key) {
62
- if (typeof key !== "string") {
63
- return Reflect.get(target, key);
64
- }
65
- return createRouterClient({
66
- ...options,
67
- path: [...path, key]
68
- });
69
- }
70
- }
71
- );
72
- return client;
73
- }
74
-
75
- // src/index.ts
76
- export * from "@orpc/shared/error";
77
- var createORPCClient = createRouterClient;
78
- export {
79
- createORPCClient,
80
- createProcedureClient,
81
- createRouterClient
82
- };
83
- //# sourceMappingURL=index.js.map
@@ -1,7 +0,0 @@
1
- /** unnoq */
2
- import { createRouterClient } from './router';
3
- export * from './procedure';
4
- export * from './router';
5
- export * from '@orpc/shared/error';
6
- export declare const createORPCClient: typeof createRouterClient;
7
- //# sourceMappingURL=index.d.ts.map
@@ -1,27 +0,0 @@
1
- import type { Promisable } from '@orpc/shared';
2
- import { type Schema, type SchemaInput, type SchemaOutput } from '@orpc/contract';
3
- export interface ProcedureClient<TInputSchema extends Schema, TOutputSchema extends Schema, TFuncOutput extends SchemaOutput<TOutputSchema>> {
4
- (input: SchemaInput<TInputSchema>): Promise<SchemaOutput<TOutputSchema, TFuncOutput>>;
5
- }
6
- export interface CreateProcedureClientOptions {
7
- /**
8
- * The base url of the server.
9
- */
10
- baseURL: string;
11
- /**
12
- * The fetch function used to make the request.
13
- * @default global fetch
14
- */
15
- fetch?: typeof fetch;
16
- /**
17
- * The headers used to make the request.
18
- * Invoked before the request is made.
19
- */
20
- headers?: (input: unknown) => Promisable<Headers | Record<string, string>>;
21
- /**
22
- * The path of the procedure on server.
23
- */
24
- path: string[];
25
- }
26
- export declare function createProcedureClient<TInputSchema extends Schema, TOutputSchema extends Schema, TFuncOutput extends SchemaOutput<TOutputSchema>>(options: CreateProcedureClientOptions): ProcedureClient<TInputSchema, TOutputSchema, TFuncOutput>;
27
- //# sourceMappingURL=procedure.d.ts.map
@@ -1,34 +0,0 @@
1
- import type { ContractProcedure, ContractRouter, SchemaOutput } from '@orpc/contract';
2
- import type { Lazy, Procedure, Router } from '@orpc/server';
3
- import type { Promisable } from '@orpc/shared';
4
- import { type ProcedureClient } from './procedure';
5
- export type RouterClientWithContractRouter<TRouter extends ContractRouter> = {
6
- [K in keyof TRouter]: TRouter[K] extends ContractProcedure<infer UInputSchema, infer UOutputSchema> ? ProcedureClient<UInputSchema, UOutputSchema, SchemaOutput<UOutputSchema>> : TRouter[K] extends ContractRouter ? RouterClientWithContractRouter<TRouter[K]> : never;
7
- };
8
- export type RouterClientWithRouter<TRouter extends Router<any>> = {
9
- [K in keyof TRouter]: TRouter[K] extends Procedure<any, any, infer UInputSchema, infer UOutputSchema, infer UFuncOutput> | Lazy<Procedure<any, any, infer UInputSchema, infer UOutputSchema, infer UFuncOutput>> ? ProcedureClient<UInputSchema, UOutputSchema, UFuncOutput> : TRouter[K] extends Router<any> ? RouterClientWithRouter<TRouter[K]> : never;
10
- };
11
- export interface CreateRouterClientOptions {
12
- /**
13
- * The base url of the server.
14
- */
15
- baseURL: string;
16
- /**
17
- * The fetch function used to make the request.
18
- * @default global fetch
19
- */
20
- fetch?: typeof fetch;
21
- /**
22
- * The headers used to make the request.
23
- * Invoked before the request is made.
24
- */
25
- headers?: (input: unknown) => Promisable<Headers | Record<string, string>>;
26
- /**
27
- * This used for internal purpose only.
28
- *
29
- * @internal
30
- */
31
- path?: string[];
32
- }
33
- export declare function createRouterClient<TRouter extends Router<any> | ContractRouter>(options: CreateRouterClientOptions): TRouter extends Router<any> ? RouterClientWithRouter<TRouter> : TRouter extends ContractRouter ? RouterClientWithContractRouter<TRouter> : never;
34
- //# sourceMappingURL=router.d.ts.map