@orpc/openapi-client 0.0.0-next.df024bb → 0.0.0-next.df717fa

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 CHANGED
@@ -21,28 +21,24 @@
21
21
 
22
22
  <h3 align="center">Typesafe APIs Made Simple 🪄</h3>
23
23
 
24
- **oRPC is a powerful combination of RPC and OpenAPI**, makes it easy to build APIs that are end-to-end type-safe and adhere to OpenAPI standards, ensuring a smooth and enjoyable developer experience.
24
+ **oRPC is a powerful combination of RPC and OpenAPI**, makes it easy to build APIs that are end-to-end type-safe and adhere to OpenAPI standards
25
25
 
26
26
  ---
27
27
 
28
28
  ## Highlights
29
29
 
30
- - **End-to-End Type Safety 🔒**: Ensure complete type safety from inputs to outputs and errors, bridging server and client seamlessly.
31
- - **First-Class OpenAPI 📄**: Adheres to the OpenAPI standard out of the box, ensuring seamless integration and comprehensive API documentation.
32
- - **Contract-First Development 📜**: (Optional) Define your API contract upfront and implement it with confidence.
33
- - **Exceptional Developer Experience ✨**: Enjoy a streamlined workflow with robust typing and clear, in-code documentation.
34
- - **Multi-Runtime Support 🌍**: Run your code seamlessly on Cloudflare, Deno, Bun, Node.js, and more.
35
- - **Framework Integrations 🧩**: Supports Tanstack Query (React, Vue), Pinia Colada, and more.
36
- - **Server Actions ⚡️**: Fully compatible with React Server Actions on Next.js, TanStack Start, and more.
37
- - **Standard Schema Support 🗂️**: Effortlessly work with Zod, Valibot, ArkType, and others right out of the box.
38
- - **Fast & Lightweight 💨**: Built on native APIs across all runtimes – optimized for speed and efficiency.
39
- - **Native Types 📦**: Enjoy built-in support for Date, File, Blob, BigInt, URL and more with no extra setup.
40
- - **Lazy Router ⏱️**: Improve cold start times with our lazy routing feature.
41
- - **SSE & Streaming 📡**: Provides SSE and streaming features – perfect for real-time notifications and AI-powered streaming responses.
42
- - **Reusability 🔄**: Write once and reuse your code across multiple purposes effortlessly.
43
- - **Extendability 🔌**: Easily enhance oRPC with plugins, middleware, and interceptors.
44
- - **Reliability 🛡️**: Well-tested, fully TypeScript, production-ready, and MIT licensed for peace of mind.
45
- - **Simplicity 💡**: Enjoy straightforward, clean code with no hidden magic.
30
+ - **🔗 End-to-End Type Safety**: Ensure type-safe inputs, outputs, and errors from client to server.
31
+ - **📘 First-Class OpenAPI**: Built-in support that fully adheres to the OpenAPI standard.
32
+ - **📝 Contract-First Development**: Optionally define your API contract before implementation.
33
+ - **⚙️ Framework Integrations**: Seamlessly integrate with TanStack Query (React, Vue, Solid, Svelte, Angular), Pinia Colada, and more.
34
+ - **🚀 Server Actions**: Fully compatible with React Server Actions on Next.js, TanStack Start, and other platforms.
35
+ - **🔠 Standard Schema Support**: Works out of the box with Zod, Valibot, ArkType, and other schema validators.
36
+ - **🗃️ Native Types**: Supports native types like Date, File, Blob, BigInt, URL, and more.
37
+ - **⏱️ Lazy Router**: Enhance cold start times with our lazy routing feature.
38
+ - **📡 SSE & Streaming**: Enjoy full type-safe support for SSE and streaming.
39
+ - **🌍 Multi-Runtime Support**: Fast and lightweight on Cloudflare, Deno, Bun, Node.js, and beyond.
40
+ - **🔌 Extendability**: Easily extend functionality with plugins, middleware, and interceptors.
41
+ - **🛡️ Reliability**: Well-tested, TypeScript-based, production-ready, and MIT licensed.
46
42
 
47
43
  ## Documentation
48
44
 
@@ -53,16 +49,28 @@ You can find the full documentation [here](https://orpc.unnoq.com).
53
49
  - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
54
50
  - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
55
51
  - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
56
- - [@orpc/react-query](https://www.npmjs.com/package/@orpc/react-query): Integration with [React Query](https://tanstack.com/query/latest/docs/framework/react/overview).
57
- - [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
58
- - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
59
52
  - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
53
+ - [@orpc/nest](https://www.npmjs.com/package/@orpc/nest): Deeply integrate oRPC with [NestJS](https://nestjs.com/).
54
+ - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
55
+ - [@orpc/tanstack-query](https://www.npmjs.com/package/@orpc/tanstack-query): [TanStack Query](https://tanstack.com/query/latest) integration.
56
+ - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
57
+ - [@orpc/hey-api](https://www.npmjs.com/package/@orpc/hey-api): [Hey API](https://heyapi.dev/) integration.
60
58
  - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
59
+ - [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/).
60
+ - [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/).
61
61
 
62
62
  ## `@orpc/openapi-client`
63
63
 
64
64
  Provides core serializer for OpenAPI requests and responses.
65
65
 
66
+ ## Sponsors
67
+
68
+ <p align="center">
69
+ <a href="https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg">
70
+ <img src='https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg'/>
71
+ </a>
72
+ </p>
73
+
66
74
  ## License
67
75
 
68
76
  Distributed under the MIT License. See [LICENSE](https://github.com/unnoq/orpc/blob/main/LICENSE) for more information.
@@ -0,0 +1,22 @@
1
+ import { ClientContext } from '@orpc/client';
2
+ import { LinkFetchClientOptions } from '@orpc/client/fetch';
3
+ import { AnyContractRouter } from '@orpc/contract';
4
+ import { g as StandardOpenAPILinkOptions, h as StandardOpenAPILink } from '../../shared/openapi-client.f2unmElJ.mjs';
5
+ import '@orpc/client/standard';
6
+ import '@orpc/shared';
7
+ import '@orpc/standard-server';
8
+
9
+ interface OpenAPILinkOptions<T extends ClientContext> extends StandardOpenAPILinkOptions<T>, LinkFetchClientOptions<T> {
10
+ }
11
+ /**
12
+ * The OpenAPI Link for fetch runtime communicates with the server that follow the OpenAPI specification.
13
+ *
14
+ * @see {@link https://orpc.unnoq.com/docs/openapi/client/openapi-link OpenAPI Link Docs}
15
+ * @see {@link https://swagger.io/specification/ OpenAPI Specification}
16
+ */
17
+ declare class OpenAPILink<T extends ClientContext> extends StandardOpenAPILink<T> {
18
+ constructor(contract: AnyContractRouter, options: OpenAPILinkOptions<T>);
19
+ }
20
+
21
+ export { OpenAPILink };
22
+ export type { OpenAPILinkOptions };
@@ -0,0 +1,22 @@
1
+ import { ClientContext } from '@orpc/client';
2
+ import { LinkFetchClientOptions } from '@orpc/client/fetch';
3
+ import { AnyContractRouter } from '@orpc/contract';
4
+ import { g as StandardOpenAPILinkOptions, h as StandardOpenAPILink } from '../../shared/openapi-client.f2unmElJ.js';
5
+ import '@orpc/client/standard';
6
+ import '@orpc/shared';
7
+ import '@orpc/standard-server';
8
+
9
+ interface OpenAPILinkOptions<T extends ClientContext> extends StandardOpenAPILinkOptions<T>, LinkFetchClientOptions<T> {
10
+ }
11
+ /**
12
+ * The OpenAPI Link for fetch runtime communicates with the server that follow the OpenAPI specification.
13
+ *
14
+ * @see {@link https://orpc.unnoq.com/docs/openapi/client/openapi-link OpenAPI Link Docs}
15
+ * @see {@link https://swagger.io/specification/ OpenAPI Specification}
16
+ */
17
+ declare class OpenAPILink<T extends ClientContext> extends StandardOpenAPILink<T> {
18
+ constructor(contract: AnyContractRouter, options: OpenAPILinkOptions<T>);
19
+ }
20
+
21
+ export { OpenAPILink };
22
+ export type { OpenAPILinkOptions };
@@ -0,0 +1,16 @@
1
+ import { LinkFetchClient } from '@orpc/client/fetch';
2
+ import '@orpc/shared';
3
+ import '@orpc/contract';
4
+ import { b as StandardOpenAPILink } from '../../shared/openapi-client.D3eD5ojB.mjs';
5
+ import '@orpc/client';
6
+ import '@orpc/client/standard';
7
+ import '@orpc/standard-server';
8
+
9
+ class OpenAPILink extends StandardOpenAPILink {
10
+ constructor(contract, options) {
11
+ const linkClient = new LinkFetchClient(options);
12
+ super(contract, linkClient, options);
13
+ }
14
+ }
15
+
16
+ export { OpenAPILink };
@@ -1,27 +1,73 @@
1
- import { Segment } from '@orpc/shared';
1
+ export { S as StandardBracketNotationSerialized, b as StandardBracketNotationSerializer, a as StandardBracketNotationSerializerOptions, d as StandardOpenAPICustomJsonSerializer, c as StandardOpenAPIJsonSerialized, f as StandardOpenAPIJsonSerializer, e as StandardOpenAPIJsonSerializerOptions, h as StandardOpenAPILink, g as StandardOpenAPILinkOptions, k as StandardOpenAPISerializeOptions, l as StandardOpenAPISerializer, j as StandardOpenapiLinkCodec, i as StandardOpenapiLinkCodecOptions } from '../../shared/openapi-client.f2unmElJ.mjs';
2
+ import { HTTPPath } from '@orpc/client';
3
+ import '@orpc/client/standard';
4
+ import '@orpc/contract';
5
+ import '@orpc/shared';
6
+ import '@orpc/standard-server';
2
7
 
3
- type BracketNotationSerialized = [string, unknown][];
4
- declare class BracketNotationSerializer {
5
- serialize(data: unknown, segments?: Segment[], result?: BracketNotationSerialized): BracketNotationSerialized;
6
- deserialize(serialized: BracketNotationSerialized): Record<string, unknown> | unknown[];
7
- stringifyPath(segments: readonly Segment[]): string;
8
- parsePath(path: string): string[];
9
- }
8
+ /**
9
+ * parse a form data with bracket notation
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * const form = new FormData()
14
+ * form.append('a', '1')
15
+ * form.append('user[name]', 'John')
16
+ * form.append('user[age]', '20')
17
+ * form.append('user[friends][]', 'Bob')
18
+ * form.append('user[friends][]', 'Alice')
19
+ * form.append('user[friends][]', 'Charlie')
20
+ * form.append('thumb', new Blob(['hello']), 'thumb.png')
21
+ *
22
+ * parseFormData(form)
23
+ * // {
24
+ * // a: '1',
25
+ * // user: {
26
+ * // name: 'John',
27
+ * // age: '20',
28
+ * // friends: ['Bob', 'Alice', 'Charlie'],
29
+ * // },
30
+ * // thumb: form.get('thumb'),
31
+ * // }
32
+ * ```
33
+ *
34
+ * @see {@link https://orpc.unnoq.com/docs/openapi/bracket-notation Bracket Notation Docs}
35
+ */
36
+ declare function parseFormData(form: FormData): any;
37
+ /**
38
+ * Get the issue message from the error.
39
+ *
40
+ * @param error - The error (can be anything) can contain `data.issues` (standard schema issues)
41
+ * @param path - The path of the field that has the issue follow [bracket notation](https://orpc.unnoq.com/docs/openapi/bracket-notation)
42
+ *
43
+ * @example
44
+ * ```tsx
45
+ * const { error, data, execute } = useServerAction(someAction)
46
+ *
47
+ * return <form action={(form) => execute(parseFormData(form))}>
48
+ * <input name="user[name]" type="text" />
49
+ * <p>{getIssueMessage(error, 'user[name]')}</p>
50
+ *
51
+ * <input name="user[age]" type="number" />
52
+ * <p>{getIssueMessage(error, 'user[age]')}</p>
53
+ *
54
+ * <input name="images[]" type="file" />
55
+ * <p>{getIssueMessage(error, 'images[]')}</p>
56
+ * </form>
57
+ *
58
+ */
59
+ declare function getIssueMessage(error: unknown, path: string): string | undefined;
10
60
 
11
- type OpenAPIJsonSerialized = [json: unknown, hasBlob: boolean];
12
- declare class OpenAPIJsonSerializer {
13
- serialize(data: unknown, hasBlobRef?: {
14
- value: boolean;
15
- }): OpenAPIJsonSerialized;
16
- }
61
+ /**
62
+ * @internal
63
+ */
64
+ declare function standardizeHTTPPath(path: HTTPPath): HTTPPath;
65
+ /**
66
+ * @internal
67
+ */
68
+ declare function getDynamicParams(path: HTTPPath | undefined): {
69
+ raw: string;
70
+ name: string;
71
+ }[] | undefined;
17
72
 
18
- declare class OpenAPISerializer {
19
- #private;
20
- private readonly jsonSerializer;
21
- private readonly bracketNotation;
22
- constructor(jsonSerializer?: OpenAPIJsonSerializer, bracketNotation?: BracketNotationSerializer);
23
- serialize(data: unknown): unknown;
24
- deserialize(data: unknown): unknown;
25
- }
26
-
27
- export { type BracketNotationSerialized, BracketNotationSerializer, type OpenAPIJsonSerialized, OpenAPIJsonSerializer, OpenAPISerializer };
73
+ export { getDynamicParams, getIssueMessage, parseFormData, standardizeHTTPPath };
@@ -1,27 +1,73 @@
1
- import { Segment } from '@orpc/shared';
1
+ export { S as StandardBracketNotationSerialized, b as StandardBracketNotationSerializer, a as StandardBracketNotationSerializerOptions, d as StandardOpenAPICustomJsonSerializer, c as StandardOpenAPIJsonSerialized, f as StandardOpenAPIJsonSerializer, e as StandardOpenAPIJsonSerializerOptions, h as StandardOpenAPILink, g as StandardOpenAPILinkOptions, k as StandardOpenAPISerializeOptions, l as StandardOpenAPISerializer, j as StandardOpenapiLinkCodec, i as StandardOpenapiLinkCodecOptions } from '../../shared/openapi-client.f2unmElJ.js';
2
+ import { HTTPPath } from '@orpc/client';
3
+ import '@orpc/client/standard';
4
+ import '@orpc/contract';
5
+ import '@orpc/shared';
6
+ import '@orpc/standard-server';
2
7
 
3
- type BracketNotationSerialized = [string, unknown][];
4
- declare class BracketNotationSerializer {
5
- serialize(data: unknown, segments?: Segment[], result?: BracketNotationSerialized): BracketNotationSerialized;
6
- deserialize(serialized: BracketNotationSerialized): Record<string, unknown> | unknown[];
7
- stringifyPath(segments: readonly Segment[]): string;
8
- parsePath(path: string): string[];
9
- }
8
+ /**
9
+ * parse a form data with bracket notation
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * const form = new FormData()
14
+ * form.append('a', '1')
15
+ * form.append('user[name]', 'John')
16
+ * form.append('user[age]', '20')
17
+ * form.append('user[friends][]', 'Bob')
18
+ * form.append('user[friends][]', 'Alice')
19
+ * form.append('user[friends][]', 'Charlie')
20
+ * form.append('thumb', new Blob(['hello']), 'thumb.png')
21
+ *
22
+ * parseFormData(form)
23
+ * // {
24
+ * // a: '1',
25
+ * // user: {
26
+ * // name: 'John',
27
+ * // age: '20',
28
+ * // friends: ['Bob', 'Alice', 'Charlie'],
29
+ * // },
30
+ * // thumb: form.get('thumb'),
31
+ * // }
32
+ * ```
33
+ *
34
+ * @see {@link https://orpc.unnoq.com/docs/openapi/bracket-notation Bracket Notation Docs}
35
+ */
36
+ declare function parseFormData(form: FormData): any;
37
+ /**
38
+ * Get the issue message from the error.
39
+ *
40
+ * @param error - The error (can be anything) can contain `data.issues` (standard schema issues)
41
+ * @param path - The path of the field that has the issue follow [bracket notation](https://orpc.unnoq.com/docs/openapi/bracket-notation)
42
+ *
43
+ * @example
44
+ * ```tsx
45
+ * const { error, data, execute } = useServerAction(someAction)
46
+ *
47
+ * return <form action={(form) => execute(parseFormData(form))}>
48
+ * <input name="user[name]" type="text" />
49
+ * <p>{getIssueMessage(error, 'user[name]')}</p>
50
+ *
51
+ * <input name="user[age]" type="number" />
52
+ * <p>{getIssueMessage(error, 'user[age]')}</p>
53
+ *
54
+ * <input name="images[]" type="file" />
55
+ * <p>{getIssueMessage(error, 'images[]')}</p>
56
+ * </form>
57
+ *
58
+ */
59
+ declare function getIssueMessage(error: unknown, path: string): string | undefined;
10
60
 
11
- type OpenAPIJsonSerialized = [json: unknown, hasBlob: boolean];
12
- declare class OpenAPIJsonSerializer {
13
- serialize(data: unknown, hasBlobRef?: {
14
- value: boolean;
15
- }): OpenAPIJsonSerialized;
16
- }
61
+ /**
62
+ * @internal
63
+ */
64
+ declare function standardizeHTTPPath(path: HTTPPath): HTTPPath;
65
+ /**
66
+ * @internal
67
+ */
68
+ declare function getDynamicParams(path: HTTPPath | undefined): {
69
+ raw: string;
70
+ name: string;
71
+ }[] | undefined;
17
72
 
18
- declare class OpenAPISerializer {
19
- #private;
20
- private readonly jsonSerializer;
21
- private readonly bracketNotation;
22
- constructor(jsonSerializer?: OpenAPIJsonSerializer, bracketNotation?: BracketNotationSerializer);
23
- serialize(data: unknown): unknown;
24
- deserialize(data: unknown): unknown;
25
- }
26
-
27
- export { type BracketNotationSerialized, BracketNotationSerializer, type OpenAPIJsonSerialized, OpenAPIJsonSerializer, OpenAPISerializer };
73
+ export { getDynamicParams, getIssueMessage, parseFormData, standardizeHTTPPath };
@@ -1,216 +1,43 @@
1
- import { isObject, isAsyncIteratorObject } from '@orpc/shared';
2
- import { mapEventIterator, toORPCError, ORPCError } from '@orpc/client';
3
- import { ErrorEvent } from '@orpc/standard-server';
1
+ import { S as StandardBracketNotationSerializer } from '../../shared/openapi-client.D3eD5ojB.mjs';
2
+ export { a as StandardOpenAPIJsonSerializer, b as StandardOpenAPILink, d as StandardOpenAPISerializer, c as StandardOpenapiLinkCodec, g as getDynamicParams, s as standardizeHTTPPath } from '../../shared/openapi-client.D3eD5ojB.mjs';
3
+ import { isSchemaIssue } from '@orpc/contract';
4
+ import { isTypescriptObject } from '@orpc/shared';
5
+ import '@orpc/client/standard';
6
+ import '@orpc/client';
7
+ import '@orpc/standard-server';
4
8
 
5
- class BracketNotationSerializer {
6
- serialize(data, segments = [], result = []) {
7
- if (Array.isArray(data)) {
8
- data.forEach((item, i) => {
9
- this.serialize(item, [...segments, i], result);
10
- });
11
- } else if (isObject(data)) {
12
- for (const key in data) {
13
- this.serialize(data[key], [...segments, key], result);
14
- }
15
- } else {
16
- result.push([this.stringifyPath(segments), data]);
17
- }
18
- return result;
19
- }
20
- deserialize(serialized) {
21
- if (serialized.length === 0) {
22
- return {};
23
- }
24
- const arrayPushStyles = /* @__PURE__ */ new WeakSet();
25
- const ref = { value: [] };
26
- for (const [path, value] of serialized) {
27
- const segments = this.parsePath(path);
28
- let currentRef = ref;
29
- let nextSegment = "value";
30
- segments.forEach((segment, i) => {
31
- if (!Array.isArray(currentRef[nextSegment]) && !isObject(currentRef[nextSegment])) {
32
- currentRef[nextSegment] = [];
33
- }
34
- if (i !== segments.length - 1) {
35
- if (Array.isArray(currentRef[nextSegment]) && !isValidArrayIndex(segment)) {
36
- currentRef[nextSegment] = { ...currentRef[nextSegment] };
37
- }
38
- } else {
39
- if (Array.isArray(currentRef[nextSegment])) {
40
- if (segment === "") {
41
- if (currentRef[nextSegment].length && !arrayPushStyles.has(currentRef[nextSegment])) {
42
- currentRef[nextSegment] = { ...currentRef[nextSegment] };
43
- }
44
- } else {
45
- if (arrayPushStyles.has(currentRef[nextSegment])) {
46
- currentRef[nextSegment] = { "": currentRef[nextSegment].at(-1) };
47
- } else if (!isValidArrayIndex(segment)) {
48
- currentRef[nextSegment] = { ...currentRef[nextSegment] };
49
- }
50
- }
51
- }
52
- }
53
- currentRef = currentRef[nextSegment];
54
- nextSegment = segment;
55
- });
56
- if (Array.isArray(currentRef)) {
57
- if (nextSegment === "") {
58
- arrayPushStyles.add(currentRef);
59
- currentRef.push(value);
60
- } else {
61
- currentRef[Number(nextSegment)] = value;
62
- }
63
- } else {
64
- currentRef[nextSegment] = value;
65
- }
66
- }
67
- return ref.value;
68
- }
69
- stringifyPath(segments) {
70
- return segments.map((segment) => {
71
- return segment.toString().replace(/[\\[\]]/g, (match) => {
72
- switch (match) {
73
- case "\\":
74
- return "\\\\";
75
- case "[":
76
- return "\\[";
77
- case "]":
78
- return "\\]";
79
- /* v8 ignore next 2 */
80
- default:
81
- return match;
82
- }
83
- });
84
- }).reduce((result, segment, i) => {
85
- if (i === 0) {
86
- return segment;
87
- }
88
- return `${result}[${segment}]`;
89
- }, "");
90
- }
91
- parsePath(path) {
92
- const segments = [];
93
- let inBrackets = false;
94
- let currentSegment = "";
95
- let backslashCount = 0;
96
- for (let i = 0; i < path.length; i++) {
97
- const char = path[i];
98
- const nextChar = path[i + 1];
99
- if (inBrackets && char === "]" && (nextChar === void 0 || nextChar === "[") && backslashCount % 2 === 0) {
100
- if (nextChar === void 0) {
101
- inBrackets = false;
102
- }
103
- segments.push(currentSegment);
104
- currentSegment = "";
105
- i++;
106
- } else if (segments.length === 0 && char === "[" && backslashCount % 2 === 0) {
107
- inBrackets = true;
108
- segments.push(currentSegment);
109
- currentSegment = "";
110
- } else if (char === "\\") {
111
- backslashCount++;
112
- } else {
113
- currentSegment += "\\".repeat(backslashCount / 2) + char;
114
- backslashCount = 0;
115
- }
116
- }
117
- return inBrackets || segments.length === 0 ? [path] : segments;
118
- }
9
+ function parseFormData(form) {
10
+ const serializer = new StandardBracketNotationSerializer();
11
+ return serializer.deserialize(Array.from(form.entries()));
119
12
  }
120
- function isValidArrayIndex(value) {
121
- return /^0$|^[1-9]\d*$/.test(value);
122
- }
123
-
124
- class OpenAPIJsonSerializer {
125
- serialize(data, hasBlobRef = { value: false }) {
126
- if (data instanceof Blob) {
127
- hasBlobRef.value = true;
128
- return [data, hasBlobRef.value];
129
- }
130
- if (data instanceof Set) {
131
- return this.serialize(Array.from(data), hasBlobRef);
132
- }
133
- if (data instanceof Map) {
134
- return this.serialize(Array.from(data.entries()), hasBlobRef);
135
- }
136
- if (Array.isArray(data)) {
137
- const json = data.map((v) => v === void 0 ? null : this.serialize(v, hasBlobRef)[0]);
138
- return [json, hasBlobRef.value];
139
- }
140
- if (isObject(data)) {
141
- const json = {};
142
- for (const k in data) {
143
- json[k] = this.serialize(data[k], hasBlobRef)[0];
13
+ function getIssueMessage(error, path) {
14
+ if (!isTypescriptObject(error) || !isTypescriptObject(error.data) || !Array.isArray(error.data.issues)) {
15
+ return void 0;
16
+ }
17
+ const serializer = new StandardBracketNotationSerializer();
18
+ for (const issue of error.data.issues) {
19
+ if (!isSchemaIssue(issue)) {
20
+ continue;
21
+ }
22
+ if (issue.path === void 0) {
23
+ if (path === "") {
24
+ return issue.message;
144
25
  }
145
- return [json, hasBlobRef.value];
146
- }
147
- if (typeof data === "bigint" || data instanceof RegExp || data instanceof URL) {
148
- return [data.toString(), hasBlobRef.value];
149
- }
150
- if (data instanceof Date) {
151
- return [Number.isNaN(data.getTime()) ? null : data.toISOString(), hasBlobRef.value];
26
+ continue;
152
27
  }
153
- if (Number.isNaN(data)) {
154
- return [null, hasBlobRef.value];
28
+ const issuePath = serializer.stringifyPath(
29
+ issue.path.map((segment) => typeof segment === "object" ? segment.key.toString() : segment.toString())
30
+ );
31
+ if (issuePath === path) {
32
+ return issue.message;
155
33
  }
156
- return [data, hasBlobRef.value];
157
- }
158
- }
159
-
160
- class OpenAPISerializer {
161
- constructor(jsonSerializer = new OpenAPIJsonSerializer(), bracketNotation = new BracketNotationSerializer()) {
162
- this.jsonSerializer = jsonSerializer;
163
- this.bracketNotation = bracketNotation;
164
- }
165
- serialize(data) {
166
- if (isAsyncIteratorObject(data)) {
167
- return mapEventIterator(data, {
168
- value: async (value) => this.#serialize(value, false),
169
- error: async (e) => {
170
- return new ErrorEvent({
171
- data: this.#serialize(toORPCError(e).toJSON(), false),
172
- cause: e
173
- });
174
- }
175
- });
176
- }
177
- return this.#serialize(data, true);
178
- }
179
- #serialize(data, enableFormData) {
180
- if (data instanceof Blob || data === void 0) {
181
- return data;
182
- }
183
- const [json, hasBlob] = this.jsonSerializer.serialize(data);
184
- if (!enableFormData || !hasBlob) {
185
- return json;
186
- }
187
- const form = new FormData();
188
- for (const [path, value] of this.bracketNotation.serialize(json)) {
189
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
190
- form.append(path, value.toString());
191
- } else if (value instanceof Blob) {
192
- form.append(path, value);
193
- }
194
- }
195
- return form;
196
- }
197
- deserialize(data) {
198
- if (data instanceof URLSearchParams || data instanceof FormData) {
199
- return this.bracketNotation.deserialize(Array.from(data.entries()));
34
+ if (path.endsWith("[]") && issuePath.replace(/\[(?:0|[1-9]\d*)\]$/, "[]") === path) {
35
+ return issue.message;
200
36
  }
201
- if (isAsyncIteratorObject(data)) {
202
- return mapEventIterator(data, {
203
- value: async (value) => value,
204
- error: async (e) => {
205
- if (e instanceof ErrorEvent && ORPCError.isValidJSON(e.data)) {
206
- return ORPCError.fromJSON(e.data, { cause: e });
207
- }
208
- return e;
209
- }
210
- });
37
+ if (path === "" && issuePath.match(/(?:0|[1-9]\d*)$/)) {
38
+ return issue.message;
211
39
  }
212
- return data;
213
40
  }
214
41
  }
215
42
 
216
- export { BracketNotationSerializer, OpenAPIJsonSerializer, OpenAPISerializer };
43
+ export { StandardBracketNotationSerializer, getIssueMessage, parseFormData };
package/dist/index.d.mts CHANGED
@@ -1,2 +1,16 @@
1
+ import { NestedClient, Client, ORPCError } from '@orpc/client';
1
2
 
2
- export { }
3
+ type JsonifiedValue<T> = T extends string ? T : T extends number ? T : T extends boolean ? T : T extends null ? T : T extends undefined ? T : T extends Array<unknown> ? JsonifiedArray<T> : T extends Record<string, unknown> ? {
4
+ [K in keyof T]: JsonifiedValue<T[K]>;
5
+ } : T extends Date ? string : T extends bigint ? string : T extends File ? File : T extends Blob ? Blob : T extends RegExp ? string : T extends URL ? string : T extends Map<infer K, infer V> ? JsonifiedArray<[K, V][]> : T extends Set<infer U> ? JsonifiedArray<U[]> : T extends AsyncIteratorObject<infer U, infer V> ? AsyncIteratorObject<JsonifiedValue<U>, JsonifiedValue<V>> : unknown;
6
+ type JsonifiedArray<T extends Array<unknown>> = T extends readonly [] ? [] : T extends readonly [infer U, ...infer V] ? [U extends undefined ? null : JsonifiedValue<U>, ...JsonifiedArray<V>] : T extends Array<infer U> ? Array<JsonifiedValue<U>> : unknown;
7
+ /**
8
+ * Convert types that JSON not support to corresponding json types
9
+ *
10
+ * @see {@link https://orpc.unnoq.com/docs/openapi/client/openapi-link OpenAPI Link Docs}
11
+ */
12
+ type JsonifiedClient<T extends NestedClient<any>> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? Client<UClientContext, UInput, JsonifiedValue<UOutput>, UError extends ORPCError<infer UCode, infer UData> ? ORPCError<UCode, JsonifiedValue<UData>> : UError> : {
13
+ [K in keyof T]: T[K] extends NestedClient<any> ? JsonifiedClient<T[K]> : T[K];
14
+ };
15
+
16
+ export type { JsonifiedArray, JsonifiedClient, JsonifiedValue };
package/dist/index.d.ts CHANGED
@@ -1,2 +1,16 @@
1
+ import { NestedClient, Client, ORPCError } from '@orpc/client';
1
2
 
2
- export { }
3
+ type JsonifiedValue<T> = T extends string ? T : T extends number ? T : T extends boolean ? T : T extends null ? T : T extends undefined ? T : T extends Array<unknown> ? JsonifiedArray<T> : T extends Record<string, unknown> ? {
4
+ [K in keyof T]: JsonifiedValue<T[K]>;
5
+ } : T extends Date ? string : T extends bigint ? string : T extends File ? File : T extends Blob ? Blob : T extends RegExp ? string : T extends URL ? string : T extends Map<infer K, infer V> ? JsonifiedArray<[K, V][]> : T extends Set<infer U> ? JsonifiedArray<U[]> : T extends AsyncIteratorObject<infer U, infer V> ? AsyncIteratorObject<JsonifiedValue<U>, JsonifiedValue<V>> : unknown;
6
+ type JsonifiedArray<T extends Array<unknown>> = T extends readonly [] ? [] : T extends readonly [infer U, ...infer V] ? [U extends undefined ? null : JsonifiedValue<U>, ...JsonifiedArray<V>] : T extends Array<infer U> ? Array<JsonifiedValue<U>> : unknown;
7
+ /**
8
+ * Convert types that JSON not support to corresponding json types
9
+ *
10
+ * @see {@link https://orpc.unnoq.com/docs/openapi/client/openapi-link OpenAPI Link Docs}
11
+ */
12
+ type JsonifiedClient<T extends NestedClient<any>> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? Client<UClientContext, UInput, JsonifiedValue<UOutput>, UError extends ORPCError<infer UCode, infer UData> ? ORPCError<UCode, JsonifiedValue<UData>> : UError> : {
13
+ [K in keyof T]: T[K] extends NestedClient<any> ? JsonifiedClient<T[K]> : T[K];
14
+ };
15
+
16
+ export type { JsonifiedArray, JsonifiedClient, JsonifiedValue };
@@ -0,0 +1,438 @@
1
+ import { toHttpPath, getMalformedResponseErrorCode, StandardLink } from '@orpc/client/standard';
2
+ import { isObject, NullProtoObj, value, get, isAsyncIteratorObject } from '@orpc/shared';
3
+ import { isORPCErrorStatus, isORPCErrorJson, createORPCErrorFromJson, mapEventIterator, toORPCError } from '@orpc/client';
4
+ import { isContractProcedure, fallbackContractConfig, ORPCError } from '@orpc/contract';
5
+ import { mergeStandardHeaders, ErrorEvent } from '@orpc/standard-server';
6
+
7
+ class StandardBracketNotationSerializer {
8
+ maxArrayIndex;
9
+ constructor(options = {}) {
10
+ this.maxArrayIndex = options.maxBracketNotationArrayIndex ?? 9999;
11
+ }
12
+ serialize(data, segments = [], result = []) {
13
+ if (Array.isArray(data)) {
14
+ data.forEach((item, i) => {
15
+ this.serialize(item, [...segments, i], result);
16
+ });
17
+ } else if (isObject(data)) {
18
+ for (const key in data) {
19
+ this.serialize(data[key], [...segments, key], result);
20
+ }
21
+ } else {
22
+ result.push([this.stringifyPath(segments), data]);
23
+ }
24
+ return result;
25
+ }
26
+ deserialize(serialized) {
27
+ if (serialized.length === 0) {
28
+ return {};
29
+ }
30
+ const arrayPushStyles = /* @__PURE__ */ new WeakSet();
31
+ const ref = { value: [] };
32
+ for (const [path, value] of serialized) {
33
+ const segments = this.parsePath(path);
34
+ let currentRef = ref;
35
+ let nextSegment = "value";
36
+ segments.forEach((segment, i) => {
37
+ if (!Array.isArray(currentRef[nextSegment]) && !isObject(currentRef[nextSegment])) {
38
+ currentRef[nextSegment] = [];
39
+ }
40
+ if (i !== segments.length - 1) {
41
+ if (Array.isArray(currentRef[nextSegment]) && !isValidArrayIndex(segment, this.maxArrayIndex)) {
42
+ if (arrayPushStyles.has(currentRef[nextSegment])) {
43
+ arrayPushStyles.delete(currentRef[nextSegment]);
44
+ currentRef[nextSegment] = pushStyleArrayToObject(currentRef[nextSegment]);
45
+ } else {
46
+ currentRef[nextSegment] = arrayToObject(currentRef[nextSegment]);
47
+ }
48
+ }
49
+ } else {
50
+ if (Array.isArray(currentRef[nextSegment])) {
51
+ if (segment === "") {
52
+ if (currentRef[nextSegment].length && !arrayPushStyles.has(currentRef[nextSegment])) {
53
+ currentRef[nextSegment] = arrayToObject(currentRef[nextSegment]);
54
+ }
55
+ } else {
56
+ if (arrayPushStyles.has(currentRef[nextSegment])) {
57
+ arrayPushStyles.delete(currentRef[nextSegment]);
58
+ currentRef[nextSegment] = pushStyleArrayToObject(currentRef[nextSegment]);
59
+ } else if (!isValidArrayIndex(segment, this.maxArrayIndex)) {
60
+ currentRef[nextSegment] = arrayToObject(currentRef[nextSegment]);
61
+ }
62
+ }
63
+ }
64
+ }
65
+ currentRef = currentRef[nextSegment];
66
+ nextSegment = segment;
67
+ });
68
+ if (Array.isArray(currentRef) && nextSegment === "") {
69
+ arrayPushStyles.add(currentRef);
70
+ currentRef.push(value);
71
+ } else if (nextSegment in currentRef) {
72
+ if (Array.isArray(currentRef[nextSegment])) {
73
+ currentRef[nextSegment].push(value);
74
+ } else {
75
+ currentRef[nextSegment] = [currentRef[nextSegment], value];
76
+ }
77
+ } else {
78
+ currentRef[nextSegment] = value;
79
+ }
80
+ }
81
+ return ref.value;
82
+ }
83
+ stringifyPath(segments) {
84
+ return segments.map((segment) => {
85
+ return segment.toString().replace(/[\\[\]]/g, (match) => {
86
+ switch (match) {
87
+ case "\\":
88
+ return "\\\\";
89
+ case "[":
90
+ return "\\[";
91
+ case "]":
92
+ return "\\]";
93
+ /* v8 ignore next 2 */
94
+ default:
95
+ return match;
96
+ }
97
+ });
98
+ }).reduce((result, segment, i) => {
99
+ if (i === 0) {
100
+ return segment;
101
+ }
102
+ return `${result}[${segment}]`;
103
+ }, "");
104
+ }
105
+ parsePath(path) {
106
+ const segments = [];
107
+ let inBrackets = false;
108
+ let currentSegment = "";
109
+ let backslashCount = 0;
110
+ for (let i = 0; i < path.length; i++) {
111
+ const char = path[i];
112
+ const nextChar = path[i + 1];
113
+ if (inBrackets && char === "]" && (nextChar === void 0 || nextChar === "[") && backslashCount % 2 === 0) {
114
+ if (nextChar === void 0) {
115
+ inBrackets = false;
116
+ }
117
+ segments.push(currentSegment);
118
+ currentSegment = "";
119
+ i++;
120
+ } else if (segments.length === 0 && char === "[" && backslashCount % 2 === 0) {
121
+ inBrackets = true;
122
+ segments.push(currentSegment);
123
+ currentSegment = "";
124
+ } else if (char === "\\") {
125
+ backslashCount++;
126
+ } else {
127
+ currentSegment += "\\".repeat(backslashCount / 2) + char;
128
+ backslashCount = 0;
129
+ }
130
+ }
131
+ return inBrackets || segments.length === 0 ? [path] : segments;
132
+ }
133
+ }
134
+ function isValidArrayIndex(value, maxIndex) {
135
+ return /^0$|^[1-9]\d*$/.test(value) && Number(value) <= maxIndex;
136
+ }
137
+ function arrayToObject(array) {
138
+ const obj = new NullProtoObj();
139
+ array.forEach((item, i) => {
140
+ obj[i] = item;
141
+ });
142
+ return obj;
143
+ }
144
+ function pushStyleArrayToObject(array) {
145
+ const obj = new NullProtoObj();
146
+ obj[""] = array.length === 1 ? array[0] : array;
147
+ return obj;
148
+ }
149
+
150
+ class StandardOpenAPIJsonSerializer {
151
+ customSerializers;
152
+ constructor(options = {}) {
153
+ this.customSerializers = options.customJsonSerializers ?? [];
154
+ }
155
+ serialize(data, hasBlobRef = { value: false }) {
156
+ for (const custom of this.customSerializers) {
157
+ if (custom.condition(data)) {
158
+ const result = this.serialize(custom.serialize(data), hasBlobRef);
159
+ return result;
160
+ }
161
+ }
162
+ if (data instanceof Blob) {
163
+ hasBlobRef.value = true;
164
+ return [data, hasBlobRef.value];
165
+ }
166
+ if (data instanceof Set) {
167
+ return this.serialize(Array.from(data), hasBlobRef);
168
+ }
169
+ if (data instanceof Map) {
170
+ return this.serialize(Array.from(data.entries()), hasBlobRef);
171
+ }
172
+ if (Array.isArray(data)) {
173
+ const json = data.map((v) => v === void 0 ? null : this.serialize(v, hasBlobRef)[0]);
174
+ return [json, hasBlobRef.value];
175
+ }
176
+ if (isObject(data)) {
177
+ const json = {};
178
+ for (const k in data) {
179
+ if (k === "toJSON" && typeof data[k] === "function") {
180
+ continue;
181
+ }
182
+ json[k] = this.serialize(data[k], hasBlobRef)[0];
183
+ }
184
+ return [json, hasBlobRef.value];
185
+ }
186
+ if (typeof data === "bigint" || data instanceof RegExp || data instanceof URL) {
187
+ return [data.toString(), hasBlobRef.value];
188
+ }
189
+ if (data instanceof Date) {
190
+ return [Number.isNaN(data.getTime()) ? null : data.toISOString(), hasBlobRef.value];
191
+ }
192
+ if (Number.isNaN(data)) {
193
+ return [null, hasBlobRef.value];
194
+ }
195
+ return [data, hasBlobRef.value];
196
+ }
197
+ }
198
+
199
+ function standardizeHTTPPath(path) {
200
+ return `/${path.replace(/\/{2,}/g, "/").replace(/^\/|\/$/g, "")}`;
201
+ }
202
+ function getDynamicParams(path) {
203
+ return path ? standardizeHTTPPath(path).match(/\/\{[^}]+\}/g)?.map((v) => ({
204
+ raw: v,
205
+ name: v.match(/\{\+?([^}]+)\}/)[1]
206
+ })) : void 0;
207
+ }
208
+
209
+ class StandardOpenapiLinkCodec {
210
+ constructor(contract, serializer, options) {
211
+ this.contract = contract;
212
+ this.serializer = serializer;
213
+ this.baseUrl = options.url;
214
+ this.headers = options.headers ?? {};
215
+ }
216
+ baseUrl;
217
+ headers;
218
+ async encode(path, input, options) {
219
+ const baseUrl = await value(this.baseUrl, options, path, input);
220
+ let headers = await value(this.headers, options, path, input);
221
+ if (options.lastEventId !== void 0) {
222
+ headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
223
+ }
224
+ const procedure = get(this.contract, path);
225
+ if (!isContractProcedure(procedure)) {
226
+ throw new Error(`[StandardOpenapiLinkCodec] expect a contract procedure at ${path.join(".")}`);
227
+ }
228
+ const inputStructure = fallbackContractConfig("defaultInputStructure", procedure["~orpc"].route.inputStructure);
229
+ return inputStructure === "compact" ? this.#encodeCompact(procedure, path, input, options, baseUrl, headers) : this.#encodeDetailed(procedure, path, input, options, baseUrl, headers);
230
+ }
231
+ #encodeCompact(procedure, path, input, options, baseUrl, headers) {
232
+ let httpPath = standardizeHTTPPath(procedure["~orpc"].route.path ?? toHttpPath(path));
233
+ let httpBody = input;
234
+ const dynamicParams = getDynamicParams(httpPath);
235
+ if (dynamicParams?.length) {
236
+ if (!isObject(input)) {
237
+ throw new TypeError(`[StandardOpenapiLinkCodec] Invalid input shape for "compact" structure when has dynamic params at ${path.join(".")}.`);
238
+ }
239
+ const body = { ...input };
240
+ for (const param of dynamicParams) {
241
+ const value2 = input[param.name];
242
+ httpPath = httpPath.replace(param.raw, `/${encodeURIComponent(`${this.serializer.serialize(value2)}`)}`);
243
+ delete body[param.name];
244
+ }
245
+ httpBody = Object.keys(body).length ? body : void 0;
246
+ }
247
+ const method = fallbackContractConfig("defaultMethod", procedure["~orpc"].route.method);
248
+ const url = new URL(baseUrl);
249
+ url.pathname = `${url.pathname.replace(/\/$/, "")}${httpPath}`;
250
+ if (method === "GET") {
251
+ const serialized = this.serializer.serialize(httpBody, { outputFormat: "URLSearchParams" });
252
+ for (const [key, value2] of serialized) {
253
+ url.searchParams.append(key, value2);
254
+ }
255
+ return {
256
+ url,
257
+ method,
258
+ headers,
259
+ body: void 0,
260
+ signal: options.signal
261
+ };
262
+ }
263
+ return {
264
+ url,
265
+ method,
266
+ headers,
267
+ body: this.serializer.serialize(httpBody),
268
+ signal: options.signal
269
+ };
270
+ }
271
+ #encodeDetailed(procedure, path, input, options, baseUrl, headers) {
272
+ let httpPath = standardizeHTTPPath(procedure["~orpc"].route.path ?? toHttpPath(path));
273
+ const dynamicParams = getDynamicParams(httpPath);
274
+ if (!isObject(input) && input !== void 0) {
275
+ throw new TypeError(`[StandardOpenapiLinkCodec] Invalid input shape for "detailed" structure at ${path.join(".")}.`);
276
+ }
277
+ if (dynamicParams?.length) {
278
+ if (!isObject(input?.params)) {
279
+ throw new TypeError(`[StandardOpenapiLinkCodec] Invalid input.params shape for "detailed" structure when has dynamic params at ${path.join(".")}.`);
280
+ }
281
+ for (const param of dynamicParams) {
282
+ const value2 = input.params[param.name];
283
+ httpPath = httpPath.replace(param.raw, `/${encodeURIComponent(`${this.serializer.serialize(value2)}`)}`);
284
+ }
285
+ }
286
+ let mergedHeaders = headers;
287
+ if (input?.headers !== void 0) {
288
+ if (!isObject(input.headers)) {
289
+ throw new TypeError(`[StandardOpenapiLinkCodec] Invalid input.headers shape for "detailed" structure at ${path.join(".")}.`);
290
+ }
291
+ mergedHeaders = mergeStandardHeaders(input.headers, headers);
292
+ }
293
+ const method = fallbackContractConfig("defaultMethod", procedure["~orpc"].route.method);
294
+ const url = new URL(baseUrl);
295
+ url.pathname = `${url.pathname.replace(/\/$/, "")}${httpPath}`;
296
+ if (input?.query !== void 0) {
297
+ const query = this.serializer.serialize(input.query, { outputFormat: "URLSearchParams" });
298
+ for (const [key, value2] of query) {
299
+ url.searchParams.append(key, value2);
300
+ }
301
+ }
302
+ if (method === "GET") {
303
+ return {
304
+ url,
305
+ method,
306
+ headers: mergedHeaders,
307
+ body: void 0,
308
+ signal: options.signal
309
+ };
310
+ }
311
+ return {
312
+ url,
313
+ method,
314
+ headers: mergedHeaders,
315
+ body: this.serializer.serialize(input?.body),
316
+ signal: options.signal
317
+ };
318
+ }
319
+ async decode(response, _options, path) {
320
+ const isOk = !isORPCErrorStatus(response.status);
321
+ const deserialized = await (async () => {
322
+ let isBodyOk = false;
323
+ try {
324
+ const body = await response.body();
325
+ isBodyOk = true;
326
+ return this.serializer.deserialize(body);
327
+ } catch (error) {
328
+ if (!isBodyOk) {
329
+ throw new Error("Cannot parse response body, please check the response body and content-type.", {
330
+ cause: error
331
+ });
332
+ }
333
+ throw new Error("Invalid OpenAPI response format.", {
334
+ cause: error
335
+ });
336
+ }
337
+ })();
338
+ if (!isOk) {
339
+ if (isORPCErrorJson(deserialized)) {
340
+ throw createORPCErrorFromJson(deserialized);
341
+ }
342
+ throw new ORPCError(getMalformedResponseErrorCode(response.status), {
343
+ status: response.status,
344
+ data: { ...response, body: deserialized }
345
+ });
346
+ }
347
+ const procedure = get(this.contract, path);
348
+ if (!isContractProcedure(procedure)) {
349
+ throw new Error(`[StandardOpenapiLinkCodec] expect a contract procedure at ${path.join(".")}`);
350
+ }
351
+ const outputStructure = fallbackContractConfig("defaultOutputStructure", procedure["~orpc"].route.outputStructure);
352
+ if (outputStructure === "compact") {
353
+ return deserialized;
354
+ }
355
+ return {
356
+ status: response.status,
357
+ headers: response.headers,
358
+ body: deserialized
359
+ };
360
+ }
361
+ }
362
+
363
+ class StandardOpenAPISerializer {
364
+ constructor(jsonSerializer, bracketNotation) {
365
+ this.jsonSerializer = jsonSerializer;
366
+ this.bracketNotation = bracketNotation;
367
+ }
368
+ serialize(data, options = {}) {
369
+ if (isAsyncIteratorObject(data) && !options.outputFormat) {
370
+ return mapEventIterator(data, {
371
+ value: async (value) => this.#serialize(value, { outputFormat: "plain" }),
372
+ error: async (e) => {
373
+ return new ErrorEvent({
374
+ data: this.#serialize(toORPCError(e).toJSON(), { outputFormat: "plain" }),
375
+ cause: e
376
+ });
377
+ }
378
+ });
379
+ }
380
+ return this.#serialize(data, options);
381
+ }
382
+ #serialize(data, options) {
383
+ const [json, hasBlob] = this.jsonSerializer.serialize(data);
384
+ if (options.outputFormat === "plain") {
385
+ return json;
386
+ }
387
+ if (options.outputFormat === "URLSearchParams") {
388
+ const params = new URLSearchParams();
389
+ for (const [path, value] of this.bracketNotation.serialize(json)) {
390
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
391
+ params.append(path, value.toString());
392
+ }
393
+ }
394
+ return params;
395
+ }
396
+ if (json instanceof Blob || json === void 0 || !hasBlob) {
397
+ return json;
398
+ }
399
+ const form = new FormData();
400
+ for (const [path, value] of this.bracketNotation.serialize(json)) {
401
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
402
+ form.append(path, value.toString());
403
+ } else if (value instanceof Blob) {
404
+ form.append(path, value);
405
+ }
406
+ }
407
+ return form;
408
+ }
409
+ deserialize(data) {
410
+ if (data instanceof URLSearchParams || data instanceof FormData) {
411
+ return this.bracketNotation.deserialize(Array.from(data.entries()));
412
+ }
413
+ if (isAsyncIteratorObject(data)) {
414
+ return mapEventIterator(data, {
415
+ value: async (value) => value,
416
+ error: async (e) => {
417
+ if (e instanceof ErrorEvent && isORPCErrorJson(e.data)) {
418
+ return createORPCErrorFromJson(e.data, { cause: e });
419
+ }
420
+ return e;
421
+ }
422
+ });
423
+ }
424
+ return data;
425
+ }
426
+ }
427
+
428
+ class StandardOpenAPILink extends StandardLink {
429
+ constructor(contract, linkClient, options) {
430
+ const jsonSerializer = new StandardOpenAPIJsonSerializer(options);
431
+ const bracketNotationSerializer = new StandardBracketNotationSerializer({ maxBracketNotationArrayIndex: 4294967294 });
432
+ const serializer = new StandardOpenAPISerializer(jsonSerializer, bracketNotationSerializer);
433
+ const linkCodec = new StandardOpenapiLinkCodec(contract, serializer, options);
434
+ super(linkCodec, linkClient, options);
435
+ }
436
+ }
437
+
438
+ export { StandardBracketNotationSerializer as S, StandardOpenAPIJsonSerializer as a, StandardOpenAPILink as b, StandardOpenapiLinkCodec as c, StandardOpenAPISerializer as d, getDynamicParams as g, standardizeHTTPPath as s };
@@ -0,0 +1,97 @@
1
+ import { ClientContext, ClientOptions } from '@orpc/client';
2
+ import { StandardLinkCodec, StandardLinkOptions, StandardLink, StandardLinkClient } from '@orpc/client/standard';
3
+ import { AnyContractRouter } from '@orpc/contract';
4
+ import { Segment, Value, Promisable } from '@orpc/shared';
5
+ import { StandardHeaders, StandardRequest, StandardLazyResponse } from '@orpc/standard-server';
6
+
7
+ type StandardBracketNotationSerialized = [string, unknown][];
8
+ interface StandardBracketNotationSerializerOptions {
9
+ /**
10
+ * Maximum allowed array index for bracket notation deserialization.
11
+ *
12
+ * This helps protect against memory exhaustion attacks where malicious input
13
+ * uses extremely large array indices (e.g., `?arr[4294967296]=value`).
14
+ *
15
+ * While bracket notation creates sparse arrays that handle large indices efficiently,
16
+ * downstream code might inadvertently convert these sparse arrays to dense arrays,
17
+ * potentially creating millions of undefined elements and causing memory issues.
18
+ *
19
+ * @note Only applies to deserialization.
20
+ * @default 9_999 (array with 10,000 elements)
21
+ */
22
+ maxBracketNotationArrayIndex?: number;
23
+ }
24
+ declare class StandardBracketNotationSerializer {
25
+ private readonly maxArrayIndex;
26
+ constructor(options?: StandardBracketNotationSerializerOptions);
27
+ serialize(data: unknown, segments?: Segment[], result?: StandardBracketNotationSerialized): StandardBracketNotationSerialized;
28
+ deserialize(serialized: StandardBracketNotationSerialized): Record<string, unknown> | unknown[];
29
+ stringifyPath(segments: readonly Segment[]): string;
30
+ parsePath(path: string): string[];
31
+ }
32
+
33
+ type StandardOpenAPIJsonSerialized = [json: unknown, hasBlob: boolean];
34
+ interface StandardOpenAPICustomJsonSerializer {
35
+ condition(data: unknown): boolean;
36
+ serialize(data: any): unknown;
37
+ }
38
+ interface StandardOpenAPIJsonSerializerOptions {
39
+ customJsonSerializers?: readonly StandardOpenAPICustomJsonSerializer[];
40
+ }
41
+ declare class StandardOpenAPIJsonSerializer {
42
+ private readonly customSerializers;
43
+ constructor(options?: StandardOpenAPIJsonSerializerOptions);
44
+ serialize(data: unknown, hasBlobRef?: {
45
+ value: boolean;
46
+ }): StandardOpenAPIJsonSerialized;
47
+ }
48
+
49
+ interface StandardOpenAPISerializeOptions {
50
+ outputFormat?: 'plain' | 'URLSearchParams';
51
+ }
52
+ declare class StandardOpenAPISerializer {
53
+ #private;
54
+ private readonly jsonSerializer;
55
+ private readonly bracketNotation;
56
+ constructor(jsonSerializer: StandardOpenAPIJsonSerializer, bracketNotation: StandardBracketNotationSerializer);
57
+ serialize(data: unknown, options?: StandardOpenAPISerializeOptions): unknown;
58
+ deserialize(data: unknown): unknown;
59
+ }
60
+
61
+ interface StandardOpenapiLinkCodecOptions<T extends ClientContext> {
62
+ /**
63
+ * Base url for all requests.
64
+ */
65
+ url: Value<Promisable<string | URL>, [
66
+ options: ClientOptions<T>,
67
+ path: readonly string[],
68
+ input: unknown
69
+ ]>;
70
+ /**
71
+ * Inject headers to the request.
72
+ */
73
+ headers?: Value<Promisable<StandardHeaders>, [
74
+ options: ClientOptions<T>,
75
+ path: readonly string[],
76
+ input: unknown
77
+ ]>;
78
+ }
79
+ declare class StandardOpenapiLinkCodec<T extends ClientContext> implements StandardLinkCodec<T> {
80
+ #private;
81
+ private readonly contract;
82
+ private readonly serializer;
83
+ private readonly baseUrl;
84
+ private readonly headers;
85
+ constructor(contract: AnyContractRouter, serializer: StandardOpenAPISerializer, options: StandardOpenapiLinkCodecOptions<T>);
86
+ encode(path: readonly string[], input: unknown, options: ClientOptions<T>): Promise<StandardRequest>;
87
+ decode(response: StandardLazyResponse, _options: ClientOptions<T>, path: readonly string[]): Promise<unknown>;
88
+ }
89
+
90
+ interface StandardOpenAPILinkOptions<T extends ClientContext> extends StandardLinkOptions<T>, StandardOpenapiLinkCodecOptions<T>, StandardOpenAPIJsonSerializerOptions {
91
+ }
92
+ declare class StandardOpenAPILink<T extends ClientContext> extends StandardLink<T> {
93
+ constructor(contract: AnyContractRouter, linkClient: StandardLinkClient<T>, options: StandardOpenAPILinkOptions<T>);
94
+ }
95
+
96
+ export { StandardBracketNotationSerializer as b, StandardOpenAPIJsonSerializer as f, StandardOpenAPILink as h, StandardOpenapiLinkCodec as j, StandardOpenAPISerializer as l };
97
+ export type { StandardBracketNotationSerialized as S, StandardBracketNotationSerializerOptions as a, StandardOpenAPIJsonSerialized as c, StandardOpenAPICustomJsonSerializer as d, StandardOpenAPIJsonSerializerOptions as e, StandardOpenAPILinkOptions as g, StandardOpenapiLinkCodecOptions as i, StandardOpenAPISerializeOptions as k };
@@ -0,0 +1,97 @@
1
+ import { ClientContext, ClientOptions } from '@orpc/client';
2
+ import { StandardLinkCodec, StandardLinkOptions, StandardLink, StandardLinkClient } from '@orpc/client/standard';
3
+ import { AnyContractRouter } from '@orpc/contract';
4
+ import { Segment, Value, Promisable } from '@orpc/shared';
5
+ import { StandardHeaders, StandardRequest, StandardLazyResponse } from '@orpc/standard-server';
6
+
7
+ type StandardBracketNotationSerialized = [string, unknown][];
8
+ interface StandardBracketNotationSerializerOptions {
9
+ /**
10
+ * Maximum allowed array index for bracket notation deserialization.
11
+ *
12
+ * This helps protect against memory exhaustion attacks where malicious input
13
+ * uses extremely large array indices (e.g., `?arr[4294967296]=value`).
14
+ *
15
+ * While bracket notation creates sparse arrays that handle large indices efficiently,
16
+ * downstream code might inadvertently convert these sparse arrays to dense arrays,
17
+ * potentially creating millions of undefined elements and causing memory issues.
18
+ *
19
+ * @note Only applies to deserialization.
20
+ * @default 9_999 (array with 10,000 elements)
21
+ */
22
+ maxBracketNotationArrayIndex?: number;
23
+ }
24
+ declare class StandardBracketNotationSerializer {
25
+ private readonly maxArrayIndex;
26
+ constructor(options?: StandardBracketNotationSerializerOptions);
27
+ serialize(data: unknown, segments?: Segment[], result?: StandardBracketNotationSerialized): StandardBracketNotationSerialized;
28
+ deserialize(serialized: StandardBracketNotationSerialized): Record<string, unknown> | unknown[];
29
+ stringifyPath(segments: readonly Segment[]): string;
30
+ parsePath(path: string): string[];
31
+ }
32
+
33
+ type StandardOpenAPIJsonSerialized = [json: unknown, hasBlob: boolean];
34
+ interface StandardOpenAPICustomJsonSerializer {
35
+ condition(data: unknown): boolean;
36
+ serialize(data: any): unknown;
37
+ }
38
+ interface StandardOpenAPIJsonSerializerOptions {
39
+ customJsonSerializers?: readonly StandardOpenAPICustomJsonSerializer[];
40
+ }
41
+ declare class StandardOpenAPIJsonSerializer {
42
+ private readonly customSerializers;
43
+ constructor(options?: StandardOpenAPIJsonSerializerOptions);
44
+ serialize(data: unknown, hasBlobRef?: {
45
+ value: boolean;
46
+ }): StandardOpenAPIJsonSerialized;
47
+ }
48
+
49
+ interface StandardOpenAPISerializeOptions {
50
+ outputFormat?: 'plain' | 'URLSearchParams';
51
+ }
52
+ declare class StandardOpenAPISerializer {
53
+ #private;
54
+ private readonly jsonSerializer;
55
+ private readonly bracketNotation;
56
+ constructor(jsonSerializer: StandardOpenAPIJsonSerializer, bracketNotation: StandardBracketNotationSerializer);
57
+ serialize(data: unknown, options?: StandardOpenAPISerializeOptions): unknown;
58
+ deserialize(data: unknown): unknown;
59
+ }
60
+
61
+ interface StandardOpenapiLinkCodecOptions<T extends ClientContext> {
62
+ /**
63
+ * Base url for all requests.
64
+ */
65
+ url: Value<Promisable<string | URL>, [
66
+ options: ClientOptions<T>,
67
+ path: readonly string[],
68
+ input: unknown
69
+ ]>;
70
+ /**
71
+ * Inject headers to the request.
72
+ */
73
+ headers?: Value<Promisable<StandardHeaders>, [
74
+ options: ClientOptions<T>,
75
+ path: readonly string[],
76
+ input: unknown
77
+ ]>;
78
+ }
79
+ declare class StandardOpenapiLinkCodec<T extends ClientContext> implements StandardLinkCodec<T> {
80
+ #private;
81
+ private readonly contract;
82
+ private readonly serializer;
83
+ private readonly baseUrl;
84
+ private readonly headers;
85
+ constructor(contract: AnyContractRouter, serializer: StandardOpenAPISerializer, options: StandardOpenapiLinkCodecOptions<T>);
86
+ encode(path: readonly string[], input: unknown, options: ClientOptions<T>): Promise<StandardRequest>;
87
+ decode(response: StandardLazyResponse, _options: ClientOptions<T>, path: readonly string[]): Promise<unknown>;
88
+ }
89
+
90
+ interface StandardOpenAPILinkOptions<T extends ClientContext> extends StandardLinkOptions<T>, StandardOpenapiLinkCodecOptions<T>, StandardOpenAPIJsonSerializerOptions {
91
+ }
92
+ declare class StandardOpenAPILink<T extends ClientContext> extends StandardLink<T> {
93
+ constructor(contract: AnyContractRouter, linkClient: StandardLinkClient<T>, options: StandardOpenAPILinkOptions<T>);
94
+ }
95
+
96
+ export { StandardBracketNotationSerializer as b, StandardOpenAPIJsonSerializer as f, StandardOpenAPILink as h, StandardOpenapiLinkCodec as j, StandardOpenAPISerializer as l };
97
+ export type { StandardBracketNotationSerialized as S, StandardBracketNotationSerializerOptions as a, StandardOpenAPIJsonSerialized as c, StandardOpenAPICustomJsonSerializer as d, StandardOpenAPIJsonSerializerOptions as e, StandardOpenAPILinkOptions as g, StandardOpenapiLinkCodecOptions as i, StandardOpenAPISerializeOptions as k };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/openapi-client",
3
3
  "type": "module",
4
- "version": "0.0.0-next.df024bb",
4
+ "version": "0.0.0-next.df717fa",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -23,15 +23,24 @@
23
23
  "types": "./dist/adapters/standard/index.d.mts",
24
24
  "import": "./dist/adapters/standard/index.mjs",
25
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"
26
31
  }
27
32
  },
28
33
  "files": [
29
34
  "dist"
30
35
  ],
31
36
  "dependencies": {
32
- "@orpc/shared": "0.0.0-next.df024bb",
33
- "@orpc/standard-server": "0.0.0-next.df024bb",
34
- "@orpc/client": "0.0.0-next.df024bb"
37
+ "@orpc/client": "0.0.0-next.df717fa",
38
+ "@orpc/standard-server": "0.0.0-next.df717fa",
39
+ "@orpc/contract": "0.0.0-next.df717fa",
40
+ "@orpc/shared": "0.0.0-next.df717fa"
41
+ },
42
+ "devDependencies": {
43
+ "@orpc/server": "0.0.0-next.df717fa"
35
44
  },
36
45
  "scripts": {
37
46
  "build": "unbuild",