@orpc/contract 0.0.0-next.ee0aeaf → 0.0.0-next.ee46dab

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 ADDED
@@ -0,0 +1,114 @@
1
+ <div align="center">
2
+ <image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 alt="oRPC logo" />
3
+ </div>
4
+
5
+ <h1></h1>
6
+
7
+ <div align="center">
8
+ <a href="https://codecov.io/gh/unnoq/orpc">
9
+ <img alt="codecov" src="https://codecov.io/gh/unnoq/orpc/branch/main/graph/badge.svg">
10
+ </a>
11
+ <a href="https://www.npmjs.com/package/@orpc/contract">
12
+ <img alt="weekly downloads" src="https://img.shields.io/npm/dw/%40orpc%2Fcontract?logo=npm" />
13
+ </a>
14
+ <a href="https://github.com/unnoq/orpc/blob/main/LICENSE">
15
+ <img alt="MIT License" src="https://img.shields.io/github/license/unnoq/orpc?logo=open-source-initiative" />
16
+ </a>
17
+ <a href="https://discord.gg/TXEbwRBvQn">
18
+ <img alt="Discord" src="https://img.shields.io/discord/1308966753044398161?color=7389D8&label&logo=discord&logoColor=ffffff" />
19
+ </a>
20
+ </div>
21
+
22
+ <h3 align="center">Typesafe APIs Made Simple 🪄</h3>
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.
25
+
26
+ ---
27
+
28
+ ## Highlights
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, Solid, Svelte), 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.
46
+
47
+ ## Documentation
48
+
49
+ You can find the full documentation [here](https://orpc.unnoq.com).
50
+
51
+ ## Packages
52
+
53
+ - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
54
+ - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
55
+ - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
56
+ - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
57
+ - [@orpc/react-query](https://www.npmjs.com/package/@orpc/react-query): Integration with [React Query](https://tanstack.com/query/latest/docs/framework/react/overview).
58
+ - [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
59
+ - [@orpc/solid-query](https://www.npmjs.com/package/@orpc/solid-query): Integration with [Solid Query](https://tanstack.com/query/latest/docs/framework/solid/overview).
60
+ - [@orpc/svelte-query](https://www.npmjs.com/package/@orpc/svelte-query): Integration with [Svelte Query](https://tanstack.com/query/latest/docs/framework/svelte/overview).
61
+ - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
62
+ - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
63
+ - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
64
+ - [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/).
65
+ - [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/).
66
+
67
+ ## `@orpc/contract`
68
+
69
+ Build your API contract. Read the [documentation](https://orpc.unnoq.com/docs/contract-first/define-contract) for more information.
70
+
71
+ ```ts
72
+ export const PlanetSchema = z.object({
73
+ id: z.number().int().min(1),
74
+ name: z.string(),
75
+ description: z.string().optional(),
76
+ })
77
+
78
+ export const listPlanetContract = oc
79
+ .input(
80
+ z.object({
81
+ limit: z.number().int().min(1).max(100).optional(),
82
+ cursor: z.number().int().min(0).default(0),
83
+ }),
84
+ )
85
+ .output(z.array(PlanetSchema))
86
+
87
+ export const findPlanetContract = oc
88
+ .input(PlanetSchema.pick({ id: true }))
89
+ .output(PlanetSchema)
90
+
91
+ export const createPlanetContract = oc
92
+ .input(PlanetSchema.omit({ id: true }))
93
+ .output(PlanetSchema)
94
+
95
+ export const contract = {
96
+ planet: {
97
+ list: listPlanetContract,
98
+ find: findPlanetContract,
99
+ create: createPlanetContract,
100
+ },
101
+ }
102
+ ```
103
+
104
+ ## Sponsors
105
+
106
+ <p align="center">
107
+ <a href="https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg">
108
+ <img src='https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg'/>
109
+ </a>
110
+ </p>
111
+
112
+ ## License
113
+
114
+ Distributed under the MIT License. See [LICENSE](https://github.com/unnoq/orpc/blob/main/LICENSE) for more information.
@@ -0,0 +1,234 @@
1
+ import { ORPCErrorCode, ORPCError, HTTPMethod, HTTPPath, ClientContext, Client } from '@orpc/client';
2
+ export { HTTPMethod, HTTPPath, ORPCError } from '@orpc/client';
3
+ import { Promisable, IsEqual, ThrowableError } from '@orpc/shared';
4
+ export { Registry, ThrowableError } from '@orpc/shared';
5
+ import { StandardSchemaV1 } from '@standard-schema/spec';
6
+
7
+ type Schema<TInput, TOutput> = StandardSchemaV1<TInput, TOutput>;
8
+ type AnySchema = Schema<any, any>;
9
+ type SchemaIssue = StandardSchemaV1.Issue;
10
+ type InferSchemaInput<T extends AnySchema> = T extends StandardSchemaV1<infer UInput, any> ? UInput : never;
11
+ type InferSchemaOutput<T extends AnySchema> = T extends StandardSchemaV1<any, infer UOutput> ? UOutput : never;
12
+ type TypeRest<TInput, TOutput> = [map: (input: TInput) => Promisable<TOutput>] | (IsEqual<TInput, TOutput> extends true ? [] : never);
13
+ declare function type<TInput, TOutput = TInput>(...[map]: TypeRest<TInput, TOutput>): Schema<TInput, TOutput>;
14
+
15
+ interface ValidationErrorOptions extends ErrorOptions {
16
+ message: string;
17
+ issues: readonly SchemaIssue[];
18
+ }
19
+ declare class ValidationError extends Error {
20
+ readonly issues: readonly SchemaIssue[];
21
+ constructor(options: ValidationErrorOptions);
22
+ }
23
+ interface ErrorMapItem<TDataSchema extends AnySchema> {
24
+ status?: number;
25
+ message?: string;
26
+ data?: TDataSchema;
27
+ }
28
+ type ErrorMap = {
29
+ [key in ORPCErrorCode]?: ErrorMapItem<AnySchema>;
30
+ };
31
+ type MergedErrorMap<T1 extends ErrorMap, T2 extends ErrorMap> = Omit<T1, keyof T2> & T2;
32
+ declare function mergeErrorMap<T1 extends ErrorMap, T2 extends ErrorMap>(errorMap1: T1, errorMap2: T2): MergedErrorMap<T1, T2>;
33
+ type ORPCErrorFromErrorMap<TErrorMap extends ErrorMap> = {
34
+ [K in keyof TErrorMap]: K extends string ? TErrorMap[K] extends ErrorMapItem<infer TDataSchema extends Schema<unknown, unknown>> ? ORPCError<K, InferSchemaOutput<TDataSchema>> : never : never;
35
+ }[keyof TErrorMap];
36
+ type ErrorFromErrorMap<TErrorMap extends ErrorMap> = ORPCErrorFromErrorMap<TErrorMap> | ThrowableError;
37
+
38
+ type Meta = Record<string, any>;
39
+ declare function mergeMeta<T extends Meta>(meta1: T, meta2: T): T;
40
+
41
+ type InputStructure = 'compact' | 'detailed';
42
+ type OutputStructure = 'compact' | 'detailed';
43
+ interface Route {
44
+ method?: HTTPMethod;
45
+ path?: HTTPPath;
46
+ summary?: string;
47
+ description?: string;
48
+ deprecated?: boolean;
49
+ tags?: readonly string[];
50
+ /**
51
+ * The status code of the response when the procedure is successful.
52
+ *
53
+ * @default 200
54
+ */
55
+ successStatus?: number;
56
+ /**
57
+ * The description of the response when the procedure is successful.
58
+ *
59
+ * @default 'OK'
60
+ */
61
+ successDescription?: string;
62
+ /**
63
+ * Determines how the input should be structured based on `params`, `query`, `headers`, and `body`.
64
+ *
65
+ * @option 'compact'
66
+ * Combines `params` and either `query` or `body` (depending on the HTTP method) into a single object.
67
+ *
68
+ * @option 'detailed'
69
+ * Keeps each part of the request (`params`, `query`, `headers`, and `body`) as separate fields in the input object.
70
+ *
71
+ * Example:
72
+ * ```ts
73
+ * const input = {
74
+ * params: { id: 1 },
75
+ * query: { search: 'hello' },
76
+ * headers: { 'Content-Type': 'application/json' },
77
+ * body: { name: 'John' },
78
+ * }
79
+ * ```
80
+ *
81
+ * @default 'compact'
82
+ */
83
+ inputStructure?: InputStructure;
84
+ /**
85
+ * Determines how the response should be structured based on the output.
86
+ *
87
+ * @option 'compact'
88
+ * Includes only the body data, encoded directly in the response.
89
+ *
90
+ * @option 'detailed'
91
+ * Separates the output into `headers` and `body` fields.
92
+ * - `headers`: Custom headers to merge with the response headers.
93
+ * - `body`: The response data.
94
+ *
95
+ * Example:
96
+ * ```ts
97
+ * const output = {
98
+ * headers: { 'x-custom-header': 'value' },
99
+ * body: { message: 'Hello, world!' },
100
+ * };
101
+ * ```
102
+ *
103
+ * @default 'compact'
104
+ */
105
+ outputStructure?: OutputStructure;
106
+ }
107
+ declare function mergeRoute(a: Route, b: Route): Route;
108
+ declare function prefixRoute(route: Route, prefix: HTTPPath): Route;
109
+ declare function unshiftTagRoute(route: Route, tags: readonly string[]): Route;
110
+ declare function mergePrefix(a: HTTPPath | undefined, b: HTTPPath): HTTPPath;
111
+ declare function mergeTags(a: readonly string[] | undefined, b: readonly string[]): readonly string[];
112
+ interface EnhanceRouteOptions {
113
+ prefix?: HTTPPath;
114
+ tags?: readonly string[];
115
+ }
116
+ declare function enhanceRoute(route: Route, options: EnhanceRouteOptions): Route;
117
+
118
+ interface ContractProcedureDef<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> {
119
+ meta: TMeta;
120
+ route: Route;
121
+ inputSchema?: TInputSchema;
122
+ outputSchema?: TOutputSchema;
123
+ errorMap: TErrorMap;
124
+ }
125
+ declare class ContractProcedure<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> {
126
+ '~orpc': ContractProcedureDef<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
127
+ constructor(def: ContractProcedureDef<TInputSchema, TOutputSchema, TErrorMap, TMeta>);
128
+ }
129
+ type AnyContractProcedure = ContractProcedure<any, any, any, any>;
130
+ declare function isContractProcedure(item: unknown): item is AnyContractProcedure;
131
+
132
+ type ContractRouter<TMeta extends Meta> = ContractProcedure<any, any, any, TMeta> | {
133
+ [k: string]: ContractRouter<TMeta>;
134
+ };
135
+ type AnyContractRouter = ContractRouter<any>;
136
+ type InferContractRouterInputs<T extends AnyContractRouter> = T extends ContractProcedure<infer UInputSchema, any, any, any> ? InferSchemaInput<UInputSchema> : {
137
+ [K in keyof T]: T[K] extends AnyContractRouter ? InferContractRouterInputs<T[K]> : never;
138
+ };
139
+ type InferContractRouterOutputs<T extends AnyContractRouter> = T extends ContractProcedure<any, infer UOutputSchema, any, any> ? InferSchemaOutput<UOutputSchema> : {
140
+ [K in keyof T]: T[K] extends AnyContractRouter ? InferContractRouterOutputs<T[K]> : never;
141
+ };
142
+ type InferContractRouterErrorMap<T extends AnyContractRouter> = T extends ContractProcedure<any, any, infer UErrorMap, any> ? UErrorMap : {
143
+ [K in keyof T]: T[K] extends AnyContractRouter ? InferContractRouterErrorMap<T[K]> : never;
144
+ }[keyof T];
145
+ type InferContractRouterMeta<T extends AnyContractRouter> = T extends ContractRouter<infer UMeta> ? UMeta : never;
146
+
147
+ declare function getContractRouter(router: AnyContractRouter, path: readonly string[]): AnyContractRouter | undefined;
148
+ type EnhancedContractRouter<T extends AnyContractRouter, TErrorMap extends ErrorMap> = T extends ContractProcedure<infer UInputSchema, infer UOutputSchema, infer UErrors, infer UMeta> ? ContractProcedure<UInputSchema, UOutputSchema, MergedErrorMap<TErrorMap, UErrors>, UMeta> : {
149
+ [K in keyof T]: T[K] extends AnyContractRouter ? EnhancedContractRouter<T[K], TErrorMap> : never;
150
+ };
151
+ interface EnhanceContractRouterOptions<TErrorMap extends ErrorMap> extends EnhanceRouteOptions {
152
+ errorMap: TErrorMap;
153
+ }
154
+ declare function enhanceContractRouter<T extends AnyContractRouter, TErrorMap extends ErrorMap>(router: T, options: EnhanceContractRouterOptions<TErrorMap>): EnhancedContractRouter<T, TErrorMap>;
155
+
156
+ interface ContractProcedureBuilder<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> extends ContractProcedure<TInputSchema, TOutputSchema, TErrorMap, TMeta> {
157
+ errors<U extends ErrorMap>(errors: U): ContractProcedureBuilder<TInputSchema, TOutputSchema, MergedErrorMap<TErrorMap, U>, TMeta>;
158
+ meta(meta: TMeta): ContractProcedureBuilder<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
159
+ route(route: Route): ContractProcedureBuilder<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
160
+ input<U extends AnySchema>(schema: U): ContractProcedureBuilderWithInput<U, TOutputSchema, TErrorMap, TMeta>;
161
+ output<U extends AnySchema>(schema: U): ContractProcedureBuilderWithOutput<TInputSchema, U, TErrorMap, TMeta>;
162
+ }
163
+ interface ContractProcedureBuilderWithInput<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> extends ContractProcedure<TInputSchema, TOutputSchema, TErrorMap, TMeta> {
164
+ errors<U extends ErrorMap>(errors: U): ContractProcedureBuilderWithInput<TInputSchema, TOutputSchema, MergedErrorMap<TErrorMap, U>, TMeta>;
165
+ meta(meta: TMeta): ContractProcedureBuilderWithInput<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
166
+ route(route: Route): ContractProcedureBuilderWithInput<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
167
+ output<U extends AnySchema>(schema: U): ContractProcedureBuilderWithInputOutput<TInputSchema, U, TErrorMap, TMeta>;
168
+ }
169
+ interface ContractProcedureBuilderWithOutput<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> extends ContractProcedure<TInputSchema, TOutputSchema, TErrorMap, TMeta> {
170
+ errors<U extends ErrorMap>(errors: U): ContractProcedureBuilderWithOutput<TInputSchema, TOutputSchema, MergedErrorMap<TErrorMap, U>, TMeta>;
171
+ meta(meta: TMeta): ContractProcedureBuilderWithOutput<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
172
+ route(route: Route): ContractProcedureBuilderWithOutput<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
173
+ input<U extends AnySchema>(schema: U): ContractProcedureBuilderWithInputOutput<U, TOutputSchema, TErrorMap, TMeta>;
174
+ }
175
+ interface ContractProcedureBuilderWithInputOutput<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> extends ContractProcedure<TInputSchema, TOutputSchema, TErrorMap, TMeta> {
176
+ errors<U extends ErrorMap>(errors: U): ContractProcedureBuilderWithInputOutput<TInputSchema, TOutputSchema, MergedErrorMap<TErrorMap, U>, TMeta>;
177
+ meta(meta: TMeta): ContractProcedureBuilderWithInputOutput<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
178
+ route(route: Route): ContractProcedureBuilderWithInputOutput<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
179
+ }
180
+ interface ContractRouterBuilder<TErrorMap extends ErrorMap, TMeta extends Meta> {
181
+ '~orpc': EnhanceContractRouterOptions<TErrorMap>;
182
+ 'errors'<U extends ErrorMap>(errors: U): ContractRouterBuilder<MergedErrorMap<TErrorMap, U>, TMeta>;
183
+ 'prefix'(prefix: HTTPPath): ContractRouterBuilder<TErrorMap, TMeta>;
184
+ 'tag'(...tags: string[]): ContractRouterBuilder<TErrorMap, TMeta>;
185
+ 'router'<T extends ContractRouter<TMeta>>(router: T): EnhancedContractRouter<T, TErrorMap>;
186
+ }
187
+
188
+ interface ContractBuilderDef<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> extends ContractProcedureDef<TInputSchema, TOutputSchema, TErrorMap, TMeta>, EnhanceContractRouterOptions<TErrorMap> {
189
+ }
190
+ declare class ContractBuilder<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> extends ContractProcedure<TInputSchema, TOutputSchema, TErrorMap, TMeta> {
191
+ '~orpc': ContractBuilderDef<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
192
+ constructor(def: ContractBuilderDef<TInputSchema, TOutputSchema, TErrorMap, TMeta>);
193
+ /**
194
+ * Reset initial meta
195
+ */
196
+ $meta<U extends Meta>(initialMeta: U): ContractBuilder<TInputSchema, TOutputSchema, TErrorMap, U & Record<never, never>>;
197
+ /**
198
+ * Reset initial route
199
+ */
200
+ $route(initialRoute: Route): ContractBuilder<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
201
+ errors<U extends ErrorMap>(errors: U): ContractBuilder<TInputSchema, TOutputSchema, MergedErrorMap<TErrorMap, U>, TMeta>;
202
+ meta(meta: TMeta): ContractProcedureBuilder<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
203
+ route(route: Route): ContractProcedureBuilder<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
204
+ input<U extends AnySchema>(schema: U): ContractProcedureBuilderWithInput<U, TOutputSchema, TErrorMap, TMeta>;
205
+ output<U extends AnySchema>(schema: U): ContractProcedureBuilderWithOutput<TInputSchema, U, TErrorMap, TMeta>;
206
+ prefix(prefix: HTTPPath): ContractRouterBuilder<TErrorMap, TMeta>;
207
+ tag(...tags: string[]): ContractRouterBuilder<TErrorMap, TMeta>;
208
+ router<T extends ContractRouter<TMeta>>(router: T): EnhancedContractRouter<T, TErrorMap>;
209
+ }
210
+ declare const oc: ContractBuilder<Schema<unknown, unknown>, Schema<unknown, unknown>, Record<never, never>, Record<never, never>>;
211
+
212
+ interface ContractConfig {
213
+ defaultMethod: HTTPMethod;
214
+ defaultSuccessStatus: number;
215
+ defaultSuccessDescription: string;
216
+ defaultInputStructure: InputStructure;
217
+ defaultOutputStructure: OutputStructure;
218
+ }
219
+ declare function fallbackContractConfig<T extends keyof ContractConfig>(key: T, value: ContractConfig[T] | undefined): ContractConfig[T];
220
+
221
+ interface EventIteratorSchemaDetails {
222
+ yields: AnySchema;
223
+ returns?: AnySchema;
224
+ }
225
+ declare function eventIterator<TYieldIn, TYieldOut, TReturnIn = unknown, TReturnOut = unknown>(yields: Schema<TYieldIn, TYieldOut>, returns?: Schema<TReturnIn, TReturnOut>): Schema<AsyncIteratorObject<TYieldIn, TReturnIn, void>, AsyncIteratorObject<TYieldOut, TReturnOut, void>>;
226
+ declare function getEventIteratorSchemaDetails(schema: AnySchema | undefined): undefined | EventIteratorSchemaDetails;
227
+
228
+ type ContractProcedureClient<TClientContext extends ClientContext, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> = Client<TClientContext, InferSchemaInput<TInputSchema>, InferSchemaOutput<TOutputSchema>, ErrorFromErrorMap<TErrorMap>>;
229
+
230
+ type ContractRouterClient<TRouter extends AnyContractRouter, TClientContext extends ClientContext = Record<never, never>> = TRouter extends ContractProcedure<infer UInputSchema, infer UOutputSchema, infer UErrorMap, any> ? ContractProcedureClient<TClientContext, UInputSchema, UOutputSchema, UErrorMap> : {
231
+ [K in keyof TRouter]: TRouter[K] extends AnyContractRouter ? ContractRouterClient<TRouter[K], TClientContext> : never;
232
+ };
233
+
234
+ export { type AnyContractProcedure, type AnyContractRouter, type AnySchema, ContractBuilder, type ContractBuilderDef, type ContractConfig, ContractProcedure, type ContractProcedureBuilder, type ContractProcedureBuilderWithInput, type ContractProcedureBuilderWithInputOutput, type ContractProcedureBuilderWithOutput, type ContractProcedureClient, type ContractProcedureDef, type ContractRouter, type ContractRouterBuilder, type ContractRouterClient, type EnhanceContractRouterOptions, type EnhanceRouteOptions, type EnhancedContractRouter, type ErrorFromErrorMap, type ErrorMap, type ErrorMapItem, type EventIteratorSchemaDetails, type InferContractRouterErrorMap, type InferContractRouterInputs, type InferContractRouterMeta, type InferContractRouterOutputs, type InferSchemaInput, type InferSchemaOutput, type InputStructure, type MergedErrorMap, type Meta, type ORPCErrorFromErrorMap, type OutputStructure, type Route, type Schema, type SchemaIssue, type TypeRest, ValidationError, type ValidationErrorOptions, enhanceContractRouter, enhanceRoute, eventIterator, fallbackContractConfig, getContractRouter, getEventIteratorSchemaDetails, isContractProcedure, mergeErrorMap, mergeMeta, mergePrefix, mergeRoute, mergeTags, oc, prefixRoute, type, unshiftTagRoute };
@@ -0,0 +1,234 @@
1
+ import { ORPCErrorCode, ORPCError, HTTPMethod, HTTPPath, ClientContext, Client } from '@orpc/client';
2
+ export { HTTPMethod, HTTPPath, ORPCError } from '@orpc/client';
3
+ import { Promisable, IsEqual, ThrowableError } from '@orpc/shared';
4
+ export { Registry, ThrowableError } from '@orpc/shared';
5
+ import { StandardSchemaV1 } from '@standard-schema/spec';
6
+
7
+ type Schema<TInput, TOutput> = StandardSchemaV1<TInput, TOutput>;
8
+ type AnySchema = Schema<any, any>;
9
+ type SchemaIssue = StandardSchemaV1.Issue;
10
+ type InferSchemaInput<T extends AnySchema> = T extends StandardSchemaV1<infer UInput, any> ? UInput : never;
11
+ type InferSchemaOutput<T extends AnySchema> = T extends StandardSchemaV1<any, infer UOutput> ? UOutput : never;
12
+ type TypeRest<TInput, TOutput> = [map: (input: TInput) => Promisable<TOutput>] | (IsEqual<TInput, TOutput> extends true ? [] : never);
13
+ declare function type<TInput, TOutput = TInput>(...[map]: TypeRest<TInput, TOutput>): Schema<TInput, TOutput>;
14
+
15
+ interface ValidationErrorOptions extends ErrorOptions {
16
+ message: string;
17
+ issues: readonly SchemaIssue[];
18
+ }
19
+ declare class ValidationError extends Error {
20
+ readonly issues: readonly SchemaIssue[];
21
+ constructor(options: ValidationErrorOptions);
22
+ }
23
+ interface ErrorMapItem<TDataSchema extends AnySchema> {
24
+ status?: number;
25
+ message?: string;
26
+ data?: TDataSchema;
27
+ }
28
+ type ErrorMap = {
29
+ [key in ORPCErrorCode]?: ErrorMapItem<AnySchema>;
30
+ };
31
+ type MergedErrorMap<T1 extends ErrorMap, T2 extends ErrorMap> = Omit<T1, keyof T2> & T2;
32
+ declare function mergeErrorMap<T1 extends ErrorMap, T2 extends ErrorMap>(errorMap1: T1, errorMap2: T2): MergedErrorMap<T1, T2>;
33
+ type ORPCErrorFromErrorMap<TErrorMap extends ErrorMap> = {
34
+ [K in keyof TErrorMap]: K extends string ? TErrorMap[K] extends ErrorMapItem<infer TDataSchema extends Schema<unknown, unknown>> ? ORPCError<K, InferSchemaOutput<TDataSchema>> : never : never;
35
+ }[keyof TErrorMap];
36
+ type ErrorFromErrorMap<TErrorMap extends ErrorMap> = ORPCErrorFromErrorMap<TErrorMap> | ThrowableError;
37
+
38
+ type Meta = Record<string, any>;
39
+ declare function mergeMeta<T extends Meta>(meta1: T, meta2: T): T;
40
+
41
+ type InputStructure = 'compact' | 'detailed';
42
+ type OutputStructure = 'compact' | 'detailed';
43
+ interface Route {
44
+ method?: HTTPMethod;
45
+ path?: HTTPPath;
46
+ summary?: string;
47
+ description?: string;
48
+ deprecated?: boolean;
49
+ tags?: readonly string[];
50
+ /**
51
+ * The status code of the response when the procedure is successful.
52
+ *
53
+ * @default 200
54
+ */
55
+ successStatus?: number;
56
+ /**
57
+ * The description of the response when the procedure is successful.
58
+ *
59
+ * @default 'OK'
60
+ */
61
+ successDescription?: string;
62
+ /**
63
+ * Determines how the input should be structured based on `params`, `query`, `headers`, and `body`.
64
+ *
65
+ * @option 'compact'
66
+ * Combines `params` and either `query` or `body` (depending on the HTTP method) into a single object.
67
+ *
68
+ * @option 'detailed'
69
+ * Keeps each part of the request (`params`, `query`, `headers`, and `body`) as separate fields in the input object.
70
+ *
71
+ * Example:
72
+ * ```ts
73
+ * const input = {
74
+ * params: { id: 1 },
75
+ * query: { search: 'hello' },
76
+ * headers: { 'Content-Type': 'application/json' },
77
+ * body: { name: 'John' },
78
+ * }
79
+ * ```
80
+ *
81
+ * @default 'compact'
82
+ */
83
+ inputStructure?: InputStructure;
84
+ /**
85
+ * Determines how the response should be structured based on the output.
86
+ *
87
+ * @option 'compact'
88
+ * Includes only the body data, encoded directly in the response.
89
+ *
90
+ * @option 'detailed'
91
+ * Separates the output into `headers` and `body` fields.
92
+ * - `headers`: Custom headers to merge with the response headers.
93
+ * - `body`: The response data.
94
+ *
95
+ * Example:
96
+ * ```ts
97
+ * const output = {
98
+ * headers: { 'x-custom-header': 'value' },
99
+ * body: { message: 'Hello, world!' },
100
+ * };
101
+ * ```
102
+ *
103
+ * @default 'compact'
104
+ */
105
+ outputStructure?: OutputStructure;
106
+ }
107
+ declare function mergeRoute(a: Route, b: Route): Route;
108
+ declare function prefixRoute(route: Route, prefix: HTTPPath): Route;
109
+ declare function unshiftTagRoute(route: Route, tags: readonly string[]): Route;
110
+ declare function mergePrefix(a: HTTPPath | undefined, b: HTTPPath): HTTPPath;
111
+ declare function mergeTags(a: readonly string[] | undefined, b: readonly string[]): readonly string[];
112
+ interface EnhanceRouteOptions {
113
+ prefix?: HTTPPath;
114
+ tags?: readonly string[];
115
+ }
116
+ declare function enhanceRoute(route: Route, options: EnhanceRouteOptions): Route;
117
+
118
+ interface ContractProcedureDef<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> {
119
+ meta: TMeta;
120
+ route: Route;
121
+ inputSchema?: TInputSchema;
122
+ outputSchema?: TOutputSchema;
123
+ errorMap: TErrorMap;
124
+ }
125
+ declare class ContractProcedure<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> {
126
+ '~orpc': ContractProcedureDef<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
127
+ constructor(def: ContractProcedureDef<TInputSchema, TOutputSchema, TErrorMap, TMeta>);
128
+ }
129
+ type AnyContractProcedure = ContractProcedure<any, any, any, any>;
130
+ declare function isContractProcedure(item: unknown): item is AnyContractProcedure;
131
+
132
+ type ContractRouter<TMeta extends Meta> = ContractProcedure<any, any, any, TMeta> | {
133
+ [k: string]: ContractRouter<TMeta>;
134
+ };
135
+ type AnyContractRouter = ContractRouter<any>;
136
+ type InferContractRouterInputs<T extends AnyContractRouter> = T extends ContractProcedure<infer UInputSchema, any, any, any> ? InferSchemaInput<UInputSchema> : {
137
+ [K in keyof T]: T[K] extends AnyContractRouter ? InferContractRouterInputs<T[K]> : never;
138
+ };
139
+ type InferContractRouterOutputs<T extends AnyContractRouter> = T extends ContractProcedure<any, infer UOutputSchema, any, any> ? InferSchemaOutput<UOutputSchema> : {
140
+ [K in keyof T]: T[K] extends AnyContractRouter ? InferContractRouterOutputs<T[K]> : never;
141
+ };
142
+ type InferContractRouterErrorMap<T extends AnyContractRouter> = T extends ContractProcedure<any, any, infer UErrorMap, any> ? UErrorMap : {
143
+ [K in keyof T]: T[K] extends AnyContractRouter ? InferContractRouterErrorMap<T[K]> : never;
144
+ }[keyof T];
145
+ type InferContractRouterMeta<T extends AnyContractRouter> = T extends ContractRouter<infer UMeta> ? UMeta : never;
146
+
147
+ declare function getContractRouter(router: AnyContractRouter, path: readonly string[]): AnyContractRouter | undefined;
148
+ type EnhancedContractRouter<T extends AnyContractRouter, TErrorMap extends ErrorMap> = T extends ContractProcedure<infer UInputSchema, infer UOutputSchema, infer UErrors, infer UMeta> ? ContractProcedure<UInputSchema, UOutputSchema, MergedErrorMap<TErrorMap, UErrors>, UMeta> : {
149
+ [K in keyof T]: T[K] extends AnyContractRouter ? EnhancedContractRouter<T[K], TErrorMap> : never;
150
+ };
151
+ interface EnhanceContractRouterOptions<TErrorMap extends ErrorMap> extends EnhanceRouteOptions {
152
+ errorMap: TErrorMap;
153
+ }
154
+ declare function enhanceContractRouter<T extends AnyContractRouter, TErrorMap extends ErrorMap>(router: T, options: EnhanceContractRouterOptions<TErrorMap>): EnhancedContractRouter<T, TErrorMap>;
155
+
156
+ interface ContractProcedureBuilder<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> extends ContractProcedure<TInputSchema, TOutputSchema, TErrorMap, TMeta> {
157
+ errors<U extends ErrorMap>(errors: U): ContractProcedureBuilder<TInputSchema, TOutputSchema, MergedErrorMap<TErrorMap, U>, TMeta>;
158
+ meta(meta: TMeta): ContractProcedureBuilder<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
159
+ route(route: Route): ContractProcedureBuilder<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
160
+ input<U extends AnySchema>(schema: U): ContractProcedureBuilderWithInput<U, TOutputSchema, TErrorMap, TMeta>;
161
+ output<U extends AnySchema>(schema: U): ContractProcedureBuilderWithOutput<TInputSchema, U, TErrorMap, TMeta>;
162
+ }
163
+ interface ContractProcedureBuilderWithInput<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> extends ContractProcedure<TInputSchema, TOutputSchema, TErrorMap, TMeta> {
164
+ errors<U extends ErrorMap>(errors: U): ContractProcedureBuilderWithInput<TInputSchema, TOutputSchema, MergedErrorMap<TErrorMap, U>, TMeta>;
165
+ meta(meta: TMeta): ContractProcedureBuilderWithInput<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
166
+ route(route: Route): ContractProcedureBuilderWithInput<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
167
+ output<U extends AnySchema>(schema: U): ContractProcedureBuilderWithInputOutput<TInputSchema, U, TErrorMap, TMeta>;
168
+ }
169
+ interface ContractProcedureBuilderWithOutput<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> extends ContractProcedure<TInputSchema, TOutputSchema, TErrorMap, TMeta> {
170
+ errors<U extends ErrorMap>(errors: U): ContractProcedureBuilderWithOutput<TInputSchema, TOutputSchema, MergedErrorMap<TErrorMap, U>, TMeta>;
171
+ meta(meta: TMeta): ContractProcedureBuilderWithOutput<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
172
+ route(route: Route): ContractProcedureBuilderWithOutput<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
173
+ input<U extends AnySchema>(schema: U): ContractProcedureBuilderWithInputOutput<U, TOutputSchema, TErrorMap, TMeta>;
174
+ }
175
+ interface ContractProcedureBuilderWithInputOutput<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> extends ContractProcedure<TInputSchema, TOutputSchema, TErrorMap, TMeta> {
176
+ errors<U extends ErrorMap>(errors: U): ContractProcedureBuilderWithInputOutput<TInputSchema, TOutputSchema, MergedErrorMap<TErrorMap, U>, TMeta>;
177
+ meta(meta: TMeta): ContractProcedureBuilderWithInputOutput<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
178
+ route(route: Route): ContractProcedureBuilderWithInputOutput<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
179
+ }
180
+ interface ContractRouterBuilder<TErrorMap extends ErrorMap, TMeta extends Meta> {
181
+ '~orpc': EnhanceContractRouterOptions<TErrorMap>;
182
+ 'errors'<U extends ErrorMap>(errors: U): ContractRouterBuilder<MergedErrorMap<TErrorMap, U>, TMeta>;
183
+ 'prefix'(prefix: HTTPPath): ContractRouterBuilder<TErrorMap, TMeta>;
184
+ 'tag'(...tags: string[]): ContractRouterBuilder<TErrorMap, TMeta>;
185
+ 'router'<T extends ContractRouter<TMeta>>(router: T): EnhancedContractRouter<T, TErrorMap>;
186
+ }
187
+
188
+ interface ContractBuilderDef<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> extends ContractProcedureDef<TInputSchema, TOutputSchema, TErrorMap, TMeta>, EnhanceContractRouterOptions<TErrorMap> {
189
+ }
190
+ declare class ContractBuilder<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> extends ContractProcedure<TInputSchema, TOutputSchema, TErrorMap, TMeta> {
191
+ '~orpc': ContractBuilderDef<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
192
+ constructor(def: ContractBuilderDef<TInputSchema, TOutputSchema, TErrorMap, TMeta>);
193
+ /**
194
+ * Reset initial meta
195
+ */
196
+ $meta<U extends Meta>(initialMeta: U): ContractBuilder<TInputSchema, TOutputSchema, TErrorMap, U & Record<never, never>>;
197
+ /**
198
+ * Reset initial route
199
+ */
200
+ $route(initialRoute: Route): ContractBuilder<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
201
+ errors<U extends ErrorMap>(errors: U): ContractBuilder<TInputSchema, TOutputSchema, MergedErrorMap<TErrorMap, U>, TMeta>;
202
+ meta(meta: TMeta): ContractProcedureBuilder<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
203
+ route(route: Route): ContractProcedureBuilder<TInputSchema, TOutputSchema, TErrorMap, TMeta>;
204
+ input<U extends AnySchema>(schema: U): ContractProcedureBuilderWithInput<U, TOutputSchema, TErrorMap, TMeta>;
205
+ output<U extends AnySchema>(schema: U): ContractProcedureBuilderWithOutput<TInputSchema, U, TErrorMap, TMeta>;
206
+ prefix(prefix: HTTPPath): ContractRouterBuilder<TErrorMap, TMeta>;
207
+ tag(...tags: string[]): ContractRouterBuilder<TErrorMap, TMeta>;
208
+ router<T extends ContractRouter<TMeta>>(router: T): EnhancedContractRouter<T, TErrorMap>;
209
+ }
210
+ declare const oc: ContractBuilder<Schema<unknown, unknown>, Schema<unknown, unknown>, Record<never, never>, Record<never, never>>;
211
+
212
+ interface ContractConfig {
213
+ defaultMethod: HTTPMethod;
214
+ defaultSuccessStatus: number;
215
+ defaultSuccessDescription: string;
216
+ defaultInputStructure: InputStructure;
217
+ defaultOutputStructure: OutputStructure;
218
+ }
219
+ declare function fallbackContractConfig<T extends keyof ContractConfig>(key: T, value: ContractConfig[T] | undefined): ContractConfig[T];
220
+
221
+ interface EventIteratorSchemaDetails {
222
+ yields: AnySchema;
223
+ returns?: AnySchema;
224
+ }
225
+ declare function eventIterator<TYieldIn, TYieldOut, TReturnIn = unknown, TReturnOut = unknown>(yields: Schema<TYieldIn, TYieldOut>, returns?: Schema<TReturnIn, TReturnOut>): Schema<AsyncIteratorObject<TYieldIn, TReturnIn, void>, AsyncIteratorObject<TYieldOut, TReturnOut, void>>;
226
+ declare function getEventIteratorSchemaDetails(schema: AnySchema | undefined): undefined | EventIteratorSchemaDetails;
227
+
228
+ type ContractProcedureClient<TClientContext extends ClientContext, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> = Client<TClientContext, InferSchemaInput<TInputSchema>, InferSchemaOutput<TOutputSchema>, ErrorFromErrorMap<TErrorMap>>;
229
+
230
+ type ContractRouterClient<TRouter extends AnyContractRouter, TClientContext extends ClientContext = Record<never, never>> = TRouter extends ContractProcedure<infer UInputSchema, infer UOutputSchema, infer UErrorMap, any> ? ContractProcedureClient<TClientContext, UInputSchema, UOutputSchema, UErrorMap> : {
231
+ [K in keyof TRouter]: TRouter[K] extends AnyContractRouter ? ContractRouterClient<TRouter[K], TClientContext> : never;
232
+ };
233
+
234
+ export { type AnyContractProcedure, type AnyContractRouter, type AnySchema, ContractBuilder, type ContractBuilderDef, type ContractConfig, ContractProcedure, type ContractProcedureBuilder, type ContractProcedureBuilderWithInput, type ContractProcedureBuilderWithInputOutput, type ContractProcedureBuilderWithOutput, type ContractProcedureClient, type ContractProcedureDef, type ContractRouter, type ContractRouterBuilder, type ContractRouterClient, type EnhanceContractRouterOptions, type EnhanceRouteOptions, type EnhancedContractRouter, type ErrorFromErrorMap, type ErrorMap, type ErrorMapItem, type EventIteratorSchemaDetails, type InferContractRouterErrorMap, type InferContractRouterInputs, type InferContractRouterMeta, type InferContractRouterOutputs, type InferSchemaInput, type InferSchemaOutput, type InputStructure, type MergedErrorMap, type Meta, type ORPCErrorFromErrorMap, type OutputStructure, type Route, type Schema, type SchemaIssue, type TypeRest, ValidationError, type ValidationErrorOptions, enhanceContractRouter, enhanceRoute, eventIterator, fallbackContractConfig, getContractRouter, getEventIteratorSchemaDetails, isContractProcedure, mergeErrorMap, mergeMeta, mergePrefix, mergeRoute, mergeTags, oc, prefixRoute, type, unshiftTagRoute };
package/dist/index.mjs ADDED
@@ -0,0 +1,252 @@
1
+ import { isORPCErrorStatus, mapEventIterator, ORPCError } from '@orpc/client';
2
+ export { ORPCError } from '@orpc/client';
3
+ import { isAsyncIteratorObject } from '@orpc/shared';
4
+
5
+ class ValidationError extends Error {
6
+ issues;
7
+ constructor(options) {
8
+ super(options.message, options);
9
+ this.issues = options.issues;
10
+ }
11
+ }
12
+ function mergeErrorMap(errorMap1, errorMap2) {
13
+ return { ...errorMap1, ...errorMap2 };
14
+ }
15
+
16
+ function mergeMeta(meta1, meta2) {
17
+ return { ...meta1, ...meta2 };
18
+ }
19
+
20
+ class ContractProcedure {
21
+ "~orpc";
22
+ constructor(def) {
23
+ if (def.route?.successStatus && isORPCErrorStatus(def.route.successStatus)) {
24
+ throw new Error("[ContractProcedure] Invalid successStatus.");
25
+ }
26
+ if (Object.values(def.errorMap).some((val) => val && val.status && !isORPCErrorStatus(val.status))) {
27
+ throw new Error("[ContractProcedure] Invalid error status code.");
28
+ }
29
+ this["~orpc"] = def;
30
+ }
31
+ }
32
+ function isContractProcedure(item) {
33
+ if (item instanceof ContractProcedure) {
34
+ return true;
35
+ }
36
+ return (typeof item === "object" || typeof item === "function") && item !== null && "~orpc" in item && typeof item["~orpc"] === "object" && item["~orpc"] !== null && "errorMap" in item["~orpc"] && "route" in item["~orpc"] && "meta" in item["~orpc"];
37
+ }
38
+
39
+ function mergeRoute(a, b) {
40
+ return { ...a, ...b };
41
+ }
42
+ function prefixRoute(route, prefix) {
43
+ if (!route.path) {
44
+ return route;
45
+ }
46
+ return {
47
+ ...route,
48
+ path: `${prefix}${route.path}`
49
+ };
50
+ }
51
+ function unshiftTagRoute(route, tags) {
52
+ return {
53
+ ...route,
54
+ tags: [...tags, ...route.tags ?? []]
55
+ };
56
+ }
57
+ function mergePrefix(a, b) {
58
+ return a ? `${a}${b}` : b;
59
+ }
60
+ function mergeTags(a, b) {
61
+ return a ? [...a, ...b] : b;
62
+ }
63
+ function enhanceRoute(route, options) {
64
+ let router = route;
65
+ if (options.prefix) {
66
+ router = prefixRoute(router, options.prefix);
67
+ }
68
+ if (options.tags?.length) {
69
+ router = unshiftTagRoute(router, options.tags);
70
+ }
71
+ return router;
72
+ }
73
+
74
+ function getContractRouter(router, path) {
75
+ let current = router;
76
+ for (let i = 0; i < path.length; i++) {
77
+ const segment = path[i];
78
+ if (!current) {
79
+ return void 0;
80
+ }
81
+ if (isContractProcedure(current)) {
82
+ return void 0;
83
+ }
84
+ current = current[segment];
85
+ }
86
+ return current;
87
+ }
88
+ function enhanceContractRouter(router, options) {
89
+ if (isContractProcedure(router)) {
90
+ const enhanced2 = new ContractProcedure({
91
+ ...router["~orpc"],
92
+ errorMap: mergeErrorMap(options.errorMap, router["~orpc"].errorMap),
93
+ route: enhanceRoute(router["~orpc"].route, options)
94
+ });
95
+ return enhanced2;
96
+ }
97
+ const enhanced = {};
98
+ for (const key in router) {
99
+ enhanced[key] = enhanceContractRouter(router[key], options);
100
+ }
101
+ return enhanced;
102
+ }
103
+
104
+ class ContractBuilder extends ContractProcedure {
105
+ constructor(def) {
106
+ super(def);
107
+ this["~orpc"].prefix = def.prefix;
108
+ this["~orpc"].tags = def.tags;
109
+ }
110
+ /**
111
+ * Reset initial meta
112
+ */
113
+ $meta(initialMeta) {
114
+ return new ContractBuilder({
115
+ ...this["~orpc"],
116
+ meta: initialMeta
117
+ });
118
+ }
119
+ /**
120
+ * Reset initial route
121
+ */
122
+ $route(initialRoute) {
123
+ return new ContractBuilder({
124
+ ...this["~orpc"],
125
+ route: initialRoute
126
+ });
127
+ }
128
+ errors(errors) {
129
+ return new ContractBuilder({
130
+ ...this["~orpc"],
131
+ errorMap: mergeErrorMap(this["~orpc"].errorMap, errors)
132
+ });
133
+ }
134
+ meta(meta) {
135
+ return new ContractBuilder({
136
+ ...this["~orpc"],
137
+ meta: mergeMeta(this["~orpc"].meta, meta)
138
+ });
139
+ }
140
+ route(route) {
141
+ return new ContractBuilder({
142
+ ...this["~orpc"],
143
+ route: mergeRoute(this["~orpc"].route, route)
144
+ });
145
+ }
146
+ input(schema) {
147
+ return new ContractBuilder({
148
+ ...this["~orpc"],
149
+ inputSchema: schema
150
+ });
151
+ }
152
+ output(schema) {
153
+ return new ContractBuilder({
154
+ ...this["~orpc"],
155
+ outputSchema: schema
156
+ });
157
+ }
158
+ prefix(prefix) {
159
+ return new ContractBuilder({
160
+ ...this["~orpc"],
161
+ prefix: mergePrefix(this["~orpc"].prefix, prefix)
162
+ });
163
+ }
164
+ tag(...tags) {
165
+ return new ContractBuilder({
166
+ ...this["~orpc"],
167
+ tags: mergeTags(this["~orpc"].tags, tags)
168
+ });
169
+ }
170
+ router(router) {
171
+ return enhanceContractRouter(router, this["~orpc"]);
172
+ }
173
+ }
174
+ const oc = new ContractBuilder({
175
+ errorMap: {},
176
+ route: {},
177
+ meta: {}
178
+ });
179
+
180
+ const DEFAULT_CONFIG = {
181
+ defaultMethod: "POST",
182
+ defaultSuccessStatus: 200,
183
+ defaultSuccessDescription: "OK",
184
+ defaultInputStructure: "compact",
185
+ defaultOutputStructure: "compact"
186
+ };
187
+ function fallbackContractConfig(key, value) {
188
+ if (value === void 0) {
189
+ return DEFAULT_CONFIG[key];
190
+ }
191
+ return value;
192
+ }
193
+
194
+ const EVENT_ITERATOR_DETAILS_SYMBOL = Symbol("ORPC_EVENT_ITERATOR_DETAILS");
195
+ function eventIterator(yields, returns) {
196
+ return {
197
+ "~standard": {
198
+ [EVENT_ITERATOR_DETAILS_SYMBOL]: { yields, returns },
199
+ vendor: "orpc",
200
+ version: 1,
201
+ validate(iterator) {
202
+ if (!isAsyncIteratorObject(iterator)) {
203
+ return { issues: [{ message: "Expect event iterator", path: [] }] };
204
+ }
205
+ const mapped = mapEventIterator(iterator, {
206
+ async value(value, done) {
207
+ const schema = done ? returns : yields;
208
+ if (!schema) {
209
+ return value;
210
+ }
211
+ const result = await schema["~standard"].validate(value);
212
+ if (result.issues) {
213
+ throw new ORPCError("EVENT_ITERATOR_VALIDATION_FAILED", {
214
+ message: "Event iterator validation failed",
215
+ cause: new ValidationError({
216
+ issues: result.issues,
217
+ message: "Event iterator validation failed"
218
+ })
219
+ });
220
+ }
221
+ return result.value;
222
+ },
223
+ error: async (error) => error
224
+ });
225
+ return { value: mapped };
226
+ }
227
+ }
228
+ };
229
+ }
230
+ function getEventIteratorSchemaDetails(schema) {
231
+ if (schema === void 0) {
232
+ return void 0;
233
+ }
234
+ return schema["~standard"][EVENT_ITERATOR_DETAILS_SYMBOL];
235
+ }
236
+
237
+ function type(...[map]) {
238
+ return {
239
+ "~standard": {
240
+ vendor: "custom",
241
+ version: 1,
242
+ async validate(value) {
243
+ if (map) {
244
+ return { value: await map(value) };
245
+ }
246
+ return { value };
247
+ }
248
+ }
249
+ };
250
+ }
251
+
252
+ export { ContractBuilder, ContractProcedure, ValidationError, enhanceContractRouter, enhanceRoute, eventIterator, fallbackContractConfig, getContractRouter, getEventIteratorSchemaDetails, isContractProcedure, mergeErrorMap, mergeMeta, mergePrefix, mergeRoute, mergeTags, oc, prefixRoute, type, unshiftTagRoute };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/contract",
3
3
  "type": "module",
4
- "version": "0.0.0-next.ee0aeaf",
4
+ "version": "0.0.0-next.ee46dab",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -15,30 +15,27 @@
15
15
  ],
16
16
  "exports": {
17
17
  ".": {
18
- "types": "./dist/src/index.d.ts",
19
- "import": "./dist/index.js",
20
- "default": "./dist/index.js"
21
- },
22
- "./🔒/*": {
23
- "types": "./dist/src/*.d.ts"
18
+ "types": "./dist/index.d.mts",
19
+ "import": "./dist/index.mjs",
20
+ "default": "./dist/index.mjs"
24
21
  }
25
22
  },
26
23
  "files": [
27
- "!**/*.map",
28
- "!**/*.tsbuildinfo",
29
24
  "dist"
30
25
  ],
31
26
  "dependencies": {
32
- "@standard-schema/spec": "1.0.0-beta.4",
33
- "@orpc/shared": "0.0.0-next.ee0aeaf"
27
+ "@standard-schema/spec": "^1.0.0",
28
+ "@orpc/shared": "0.0.0-next.ee46dab",
29
+ "@orpc/client": "0.0.0-next.ee46dab",
30
+ "@orpc/standard-server": "0.0.0-next.ee46dab"
34
31
  },
35
32
  "devDependencies": {
36
33
  "arktype": "2.0.0-rc.26",
37
34
  "valibot": "1.0.0-beta.9",
38
- "zod": "3.24.1"
35
+ "zod": "^3.24.2"
39
36
  },
40
37
  "scripts": {
41
- "build": "tsup --clean --sourcemap --entry.index=src/index.ts --format=esm --onSuccess='tsc -b --noCheck'",
38
+ "build": "unbuild",
42
39
  "build:watch": "pnpm run build --watch",
43
40
  "type:check": "tsc -b"
44
41
  }
package/dist/index.js DELETED
@@ -1,151 +0,0 @@
1
- // src/procedure.ts
2
- var ContractProcedure = class {
3
- "~type" = "ContractProcedure";
4
- "~orpc";
5
- constructor(def) {
6
- this["~orpc"] = def;
7
- }
8
- };
9
- function isContractProcedure(item) {
10
- return item instanceof ContractProcedure;
11
- }
12
-
13
- // src/procedure-decorated.ts
14
- var DecoratedContractProcedure = class _DecoratedContractProcedure extends ContractProcedure {
15
- static decorate(procedure) {
16
- if (procedure instanceof _DecoratedContractProcedure) {
17
- return procedure;
18
- }
19
- return new _DecoratedContractProcedure(procedure["~orpc"]);
20
- }
21
- route(route) {
22
- return new _DecoratedContractProcedure({
23
- ...this["~orpc"],
24
- route
25
- });
26
- }
27
- prefix(prefix) {
28
- return new _DecoratedContractProcedure({
29
- ...this["~orpc"],
30
- ...this["~orpc"].route?.path ? {
31
- route: {
32
- ...this["~orpc"].route,
33
- path: `${prefix}${this["~orpc"].route.path}`
34
- }
35
- } : void 0
36
- });
37
- }
38
- pushTag(...tags) {
39
- return new _DecoratedContractProcedure({
40
- ...this["~orpc"],
41
- route: {
42
- ...this["~orpc"].route,
43
- tags: [...this["~orpc"].route?.tags ?? [], ...tags]
44
- }
45
- });
46
- }
47
- input(schema, example) {
48
- return new _DecoratedContractProcedure({
49
- ...this["~orpc"],
50
- InputSchema: schema,
51
- inputExample: example
52
- });
53
- }
54
- output(schema, example) {
55
- return new _DecoratedContractProcedure({
56
- ...this["~orpc"],
57
- OutputSchema: schema,
58
- outputExample: example
59
- });
60
- }
61
- };
62
-
63
- // src/router-builder.ts
64
- var ContractRouterBuilder = class _ContractRouterBuilder {
65
- "~type" = "ContractProcedure";
66
- "~orpc";
67
- constructor(def) {
68
- this["~orpc"] = def;
69
- }
70
- prefix(prefix) {
71
- return new _ContractRouterBuilder({
72
- ...this["~orpc"],
73
- prefix: `${this["~orpc"].prefix ?? ""}${prefix}`
74
- });
75
- }
76
- tag(...tags) {
77
- return new _ContractRouterBuilder({
78
- ...this["~orpc"],
79
- tags: [...this["~orpc"].tags ?? [], ...tags]
80
- });
81
- }
82
- router(router) {
83
- const adapted = {};
84
- for (const key in router) {
85
- const item = router[key];
86
- if (isContractProcedure(item)) {
87
- let decorated = DecoratedContractProcedure.decorate(item);
88
- if (this["~orpc"].tags) {
89
- decorated = decorated.pushTag(...this["~orpc"].tags);
90
- }
91
- if (this["~orpc"].prefix) {
92
- decorated = decorated.prefix(this["~orpc"].prefix);
93
- }
94
- adapted[key] = decorated;
95
- } else {
96
- adapted[key] = this.router(item);
97
- }
98
- }
99
- return adapted;
100
- }
101
- };
102
-
103
- // src/builder.ts
104
- var ContractBuilder = class {
105
- prefix(prefix) {
106
- return new ContractRouterBuilder({
107
- prefix
108
- });
109
- }
110
- tag(...tags) {
111
- return new ContractRouterBuilder({
112
- tags
113
- });
114
- }
115
- route(route) {
116
- return new DecoratedContractProcedure({
117
- route,
118
- InputSchema: void 0,
119
- OutputSchema: void 0
120
- });
121
- }
122
- input(schema, example) {
123
- return new DecoratedContractProcedure({
124
- InputSchema: schema,
125
- inputExample: example,
126
- OutputSchema: void 0
127
- });
128
- }
129
- output(schema, example) {
130
- return new DecoratedContractProcedure({
131
- OutputSchema: schema,
132
- outputExample: example,
133
- InputSchema: void 0
134
- });
135
- }
136
- router(router) {
137
- return router;
138
- }
139
- };
140
-
141
- // src/index.ts
142
- var oc = new ContractBuilder();
143
- export {
144
- ContractBuilder,
145
- ContractProcedure,
146
- ContractRouterBuilder,
147
- DecoratedContractProcedure,
148
- isContractProcedure,
149
- oc
150
- };
151
- //# sourceMappingURL=index.js.map
@@ -1,14 +0,0 @@
1
- import type { RouteOptions } from './procedure';
2
- import type { ContractRouter } from './router';
3
- import type { HTTPPath, Schema, SchemaInput, SchemaOutput } from './types';
4
- import { DecoratedContractProcedure } from './procedure-decorated';
5
- import { ContractRouterBuilder } from './router-builder';
6
- export declare class ContractBuilder {
7
- prefix(prefix: HTTPPath): ContractRouterBuilder;
8
- tag(...tags: string[]): ContractRouterBuilder;
9
- route(route: RouteOptions): DecoratedContractProcedure<undefined, undefined>;
10
- input<U extends Schema>(schema: U, example?: SchemaInput<U>): DecoratedContractProcedure<U, undefined>;
11
- output<U extends Schema>(schema: U, example?: SchemaOutput<U>): DecoratedContractProcedure<undefined, U>;
12
- router<T extends ContractRouter>(router: T): T;
13
- }
14
- //# sourceMappingURL=builder.d.ts.map
@@ -1,10 +0,0 @@
1
- /** unnoq */
2
- import { ContractBuilder } from './builder';
3
- export * from './builder';
4
- export * from './procedure';
5
- export * from './procedure-decorated';
6
- export * from './router';
7
- export * from './router-builder';
8
- export * from './types';
9
- export declare const oc: ContractBuilder;
10
- //# sourceMappingURL=index.d.ts.map
@@ -1,12 +0,0 @@
1
- import type { RouteOptions } from './procedure';
2
- import type { HTTPPath, Schema, SchemaInput, SchemaOutput } from './types';
3
- import { ContractProcedure } from './procedure';
4
- export declare class DecoratedContractProcedure<TInputSchema extends Schema, TOutputSchema extends Schema> extends ContractProcedure<TInputSchema, TOutputSchema> {
5
- static decorate<UInputSchema extends Schema = undefined, UOutputSchema extends Schema = undefined>(procedure: ContractProcedure<UInputSchema, UOutputSchema>): DecoratedContractProcedure<UInputSchema, UOutputSchema>;
6
- route(route: RouteOptions): DecoratedContractProcedure<TInputSchema, TOutputSchema>;
7
- prefix(prefix: HTTPPath): DecoratedContractProcedure<TInputSchema, TOutputSchema>;
8
- pushTag(...tags: string[]): DecoratedContractProcedure<TInputSchema, TOutputSchema>;
9
- input<U extends Schema = undefined>(schema: U, example?: SchemaInput<U>): DecoratedContractProcedure<U, TOutputSchema>;
10
- output<U extends Schema = undefined>(schema: U, example?: SchemaOutput<U>): DecoratedContractProcedure<TInputSchema, U>;
11
- }
12
- //# sourceMappingURL=procedure-decorated.d.ts.map
@@ -1,25 +0,0 @@
1
- import type { HTTPMethod, HTTPPath, Schema, SchemaOutput } from './types';
2
- export interface RouteOptions {
3
- method?: HTTPMethod;
4
- path?: HTTPPath;
5
- summary?: string;
6
- description?: string;
7
- deprecated?: boolean;
8
- tags?: string[];
9
- }
10
- export interface ContractProcedureDef<TInputSchema extends Schema, TOutputSchema extends Schema> {
11
- route?: RouteOptions;
12
- InputSchema: TInputSchema;
13
- inputExample?: SchemaOutput<TInputSchema>;
14
- OutputSchema: TOutputSchema;
15
- outputExample?: SchemaOutput<TOutputSchema>;
16
- }
17
- export declare class ContractProcedure<TInputSchema extends Schema, TOutputSchema extends Schema> {
18
- '~type': "ContractProcedure";
19
- '~orpc': ContractProcedureDef<TInputSchema, TOutputSchema>;
20
- constructor(def: ContractProcedureDef<TInputSchema, TOutputSchema>);
21
- }
22
- export type ANY_CONTRACT_PROCEDURE = ContractProcedure<any, any>;
23
- export type WELL_CONTRACT_PROCEDURE = ContractProcedure<Schema, Schema>;
24
- export declare function isContractProcedure(item: unknown): item is ANY_CONTRACT_PROCEDURE;
25
- //# sourceMappingURL=procedure.d.ts.map
@@ -1,20 +0,0 @@
1
- import type { ContractProcedure } from './procedure';
2
- import type { ContractRouter } from './router';
3
- import type { HTTPPath } from './types';
4
- import { DecoratedContractProcedure } from './procedure-decorated';
5
- export type AdaptedContractRouter<TContract extends ContractRouter> = {
6
- [K in keyof TContract]: TContract[K] extends ContractProcedure<infer UInputSchema, infer UOutputSchema> ? DecoratedContractProcedure<UInputSchema, UOutputSchema> : TContract[K] extends ContractRouter ? AdaptedContractRouter<TContract[K]> : never;
7
- };
8
- export interface ContractRouterBuilderDef {
9
- prefix?: HTTPPath;
10
- tags?: string[];
11
- }
12
- export declare class ContractRouterBuilder {
13
- '~type': "ContractProcedure";
14
- '~orpc': ContractRouterBuilderDef;
15
- constructor(def: ContractRouterBuilderDef);
16
- prefix(prefix: HTTPPath): ContractRouterBuilder;
17
- tag(...tags: string[]): ContractRouterBuilder;
18
- router<T extends ContractRouter>(router: T): AdaptedContractRouter<T>;
19
- }
20
- //# sourceMappingURL=router-builder.d.ts.map
@@ -1,12 +0,0 @@
1
- import type { ANY_CONTRACT_PROCEDURE, ContractProcedure } from './procedure';
2
- import type { SchemaInput, SchemaOutput } from './types';
3
- export interface ContractRouter {
4
- [k: string]: ANY_CONTRACT_PROCEDURE | ContractRouter;
5
- }
6
- export type InferContractRouterInputs<T extends ContractRouter> = {
7
- [K in keyof T]: T[K] extends ContractProcedure<infer UInputSchema, any> ? SchemaInput<UInputSchema> : T[K] extends ContractRouter ? InferContractRouterInputs<T[K]> : never;
8
- };
9
- export type InferContractRouterOutputs<T extends ContractRouter> = {
10
- [K in keyof T]: T[K] extends ContractProcedure<any, infer UOutputSchema> ? SchemaOutput<UOutputSchema> : T[K] extends ContractRouter ? InferContractRouterOutputs<T[K]> : never;
11
- };
12
- //# sourceMappingURL=router.d.ts.map
@@ -1,7 +0,0 @@
1
- import type { StandardSchemaV1 } from '@standard-schema/spec';
2
- export type HTTPPath = `/${string}`;
3
- export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
4
- export type Schema = StandardSchemaV1 | undefined;
5
- export type SchemaInput<TSchema extends Schema, TFallback = unknown> = TSchema extends undefined ? TFallback : TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferInput<TSchema> : TFallback;
6
- export type SchemaOutput<TSchema extends Schema, TFallback = unknown> = TSchema extends undefined ? TFallback : TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema> : TFallback;
7
- //# sourceMappingURL=types.d.ts.map