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

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/dist/index.js CHANGED
@@ -3,11 +3,20 @@ var ContractProcedure = class {
3
3
  "~type" = "ContractProcedure";
4
4
  "~orpc";
5
5
  constructor(def) {
6
+ if (def.route?.successStatus && (def.route.successStatus < 200 || def.route?.successStatus > 299)) {
7
+ throw new Error("[ContractProcedure] The successStatus must be between 200 and 299");
8
+ }
9
+ if (Object.values(def.errorMap ?? {}).some((val) => val && val.status && (val.status < 400 || val.status > 599))) {
10
+ throw new Error("[ContractProcedure] The error status code must be in the 400-599 range.");
11
+ }
6
12
  this["~orpc"] = def;
7
13
  }
8
14
  };
9
15
  function isContractProcedure(item) {
10
- return item instanceof ContractProcedure;
16
+ if (item instanceof ContractProcedure) {
17
+ return true;
18
+ }
19
+ return (typeof item === "object" || typeof item === "function") && item !== null && "~type" in item && item["~type"] === "ContractProcedure" && "~orpc" in item && typeof item["~orpc"] === "object" && item["~orpc"] !== null && "InputSchema" in item["~orpc"] && "OutputSchema" in item["~orpc"] && "errorMap" in item["~orpc"];
11
20
  }
12
21
 
13
22
  // src/procedure-decorated.ts
@@ -21,7 +30,10 @@ var DecoratedContractProcedure = class _DecoratedContractProcedure extends Contr
21
30
  route(route) {
22
31
  return new _DecoratedContractProcedure({
23
32
  ...this["~orpc"],
24
- route
33
+ route: {
34
+ ...this["~orpc"].route,
35
+ ...route
36
+ }
25
37
  });
26
38
  }
27
39
  prefix(prefix) {
@@ -35,12 +47,15 @@ var DecoratedContractProcedure = class _DecoratedContractProcedure extends Contr
35
47
  } : void 0
36
48
  });
37
49
  }
38
- pushTag(...tags) {
50
+ unshiftTag(...tags) {
39
51
  return new _DecoratedContractProcedure({
40
52
  ...this["~orpc"],
41
53
  route: {
42
54
  ...this["~orpc"].route,
43
- tags: [...this["~orpc"].route?.tags ?? [], ...tags]
55
+ tags: [
56
+ ...tags,
57
+ ...this["~orpc"].route?.tags?.filter((tag) => !tags.includes(tag)) ?? []
58
+ ]
44
59
  }
45
60
  });
46
61
  }
@@ -58,6 +73,15 @@ var DecoratedContractProcedure = class _DecoratedContractProcedure extends Contr
58
73
  outputExample: example
59
74
  });
60
75
  }
76
+ errors(errors) {
77
+ return new _DecoratedContractProcedure({
78
+ ...this["~orpc"],
79
+ errorMap: {
80
+ ...this["~orpc"].errorMap,
81
+ ...errors
82
+ }
83
+ });
84
+ }
61
85
  };
62
86
 
63
87
  // src/router-builder.ts
@@ -79,73 +103,304 @@ var ContractRouterBuilder = class _ContractRouterBuilder {
79
103
  tags: [...this["~orpc"].tags ?? [], ...tags]
80
104
  });
81
105
  }
106
+ errors(errors) {
107
+ return new _ContractRouterBuilder({
108
+ ...this["~orpc"],
109
+ errorMap: {
110
+ ...this["~orpc"].errorMap,
111
+ ...errors
112
+ }
113
+ });
114
+ }
82
115
  router(router) {
116
+ if (isContractProcedure(router)) {
117
+ let decorated = DecoratedContractProcedure.decorate(router);
118
+ if (this["~orpc"].tags) {
119
+ decorated = decorated.unshiftTag(...this["~orpc"].tags);
120
+ }
121
+ if (this["~orpc"].prefix) {
122
+ decorated = decorated.prefix(this["~orpc"].prefix);
123
+ }
124
+ decorated = decorated.errors(this["~orpc"].errorMap);
125
+ return decorated;
126
+ }
83
127
  const adapted = {};
84
128
  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
- }
129
+ adapted[key] = this.router(router[key]);
98
130
  }
99
131
  return adapted;
100
132
  }
101
133
  };
102
134
 
103
135
  // src/builder.ts
104
- var ContractBuilder = class {
136
+ var ContractBuilder = class _ContractBuilder {
137
+ "~type" = "ContractBuilder";
138
+ "~orpc";
139
+ constructor(def) {
140
+ this["~orpc"] = def;
141
+ }
142
+ errors(errors) {
143
+ return new _ContractBuilder({
144
+ ...this["~orpc"],
145
+ errorMap: {
146
+ ...this["~orpc"].errorMap,
147
+ ...errors
148
+ }
149
+ });
150
+ }
105
151
  prefix(prefix) {
106
152
  return new ContractRouterBuilder({
107
- prefix
153
+ prefix,
154
+ errorMap: this["~orpc"].errorMap
108
155
  });
109
156
  }
110
157
  tag(...tags) {
111
158
  return new ContractRouterBuilder({
112
- tags
159
+ tags,
160
+ errorMap: this["~orpc"].errorMap
113
161
  });
114
162
  }
115
163
  route(route) {
116
164
  return new DecoratedContractProcedure({
117
165
  route,
118
166
  InputSchema: void 0,
119
- OutputSchema: void 0
167
+ OutputSchema: void 0,
168
+ errorMap: this["~orpc"].errorMap
120
169
  });
121
170
  }
122
171
  input(schema, example) {
123
172
  return new DecoratedContractProcedure({
124
173
  InputSchema: schema,
125
174
  inputExample: example,
126
- OutputSchema: void 0
175
+ OutputSchema: void 0,
176
+ errorMap: this["~orpc"].errorMap
127
177
  });
128
178
  }
129
179
  output(schema, example) {
130
180
  return new DecoratedContractProcedure({
131
181
  OutputSchema: schema,
132
182
  outputExample: example,
133
- InputSchema: void 0
183
+ InputSchema: void 0,
184
+ errorMap: this["~orpc"].errorMap
134
185
  });
135
186
  }
136
187
  router(router) {
137
- return router;
188
+ return new ContractRouterBuilder({
189
+ errorMap: this["~orpc"].errorMap
190
+ }).router(router);
191
+ }
192
+ };
193
+
194
+ // src/error-orpc.ts
195
+ import { isPlainObject } from "@orpc/shared";
196
+ var COMMON_ORPC_ERROR_DEFS = {
197
+ BAD_REQUEST: {
198
+ status: 400,
199
+ message: "Bad Request"
200
+ },
201
+ UNAUTHORIZED: {
202
+ status: 401,
203
+ message: "Unauthorized"
204
+ },
205
+ FORBIDDEN: {
206
+ status: 403,
207
+ message: "Forbidden"
208
+ },
209
+ NOT_FOUND: {
210
+ status: 404,
211
+ message: "Not Found"
212
+ },
213
+ METHOD_NOT_SUPPORTED: {
214
+ status: 405,
215
+ message: "Method Not Supported"
216
+ },
217
+ NOT_ACCEPTABLE: {
218
+ status: 406,
219
+ message: "Not Acceptable"
220
+ },
221
+ TIMEOUT: {
222
+ status: 408,
223
+ message: "Request Timeout"
224
+ },
225
+ CONFLICT: {
226
+ status: 409,
227
+ message: "Conflict"
228
+ },
229
+ PRECONDITION_FAILED: {
230
+ status: 412,
231
+ message: "Precondition Failed"
232
+ },
233
+ PAYLOAD_TOO_LARGE: {
234
+ status: 413,
235
+ message: "Payload Too Large"
236
+ },
237
+ UNSUPPORTED_MEDIA_TYPE: {
238
+ status: 415,
239
+ message: "Unsupported Media Type"
240
+ },
241
+ UNPROCESSABLE_CONTENT: {
242
+ status: 422,
243
+ message: "Unprocessable Content"
244
+ },
245
+ TOO_MANY_REQUESTS: {
246
+ status: 429,
247
+ message: "Too Many Requests"
248
+ },
249
+ CLIENT_CLOSED_REQUEST: {
250
+ status: 499,
251
+ message: "Client Closed Request"
252
+ },
253
+ INTERNAL_SERVER_ERROR: {
254
+ status: 500,
255
+ message: "Internal Server Error"
256
+ },
257
+ NOT_IMPLEMENTED: {
258
+ status: 501,
259
+ message: "Not Implemented"
260
+ },
261
+ BAD_GATEWAY: {
262
+ status: 502,
263
+ message: "Bad Gateway"
264
+ },
265
+ SERVICE_UNAVAILABLE: {
266
+ status: 503,
267
+ message: "Service Unavailable"
268
+ },
269
+ GATEWAY_TIMEOUT: {
270
+ status: 504,
271
+ message: "Gateway Timeout"
272
+ }
273
+ };
274
+ function fallbackORPCErrorStatus(code, status) {
275
+ return status ?? COMMON_ORPC_ERROR_DEFS[code]?.status ?? 500;
276
+ }
277
+ function fallbackORPCErrorMessage(code, message) {
278
+ return message || COMMON_ORPC_ERROR_DEFS[code]?.message || code;
279
+ }
280
+ var ORPCError = class extends Error {
281
+ defined;
282
+ code;
283
+ status;
284
+ data;
285
+ constructor(options) {
286
+ if (options.status && (options.status < 400 || options.status >= 600)) {
287
+ throw new Error("[ORPCError] The error status code must be in the 400-599 range.");
288
+ }
289
+ const message = fallbackORPCErrorMessage(options.code, options.message);
290
+ super(message, options);
291
+ this.code = options.code;
292
+ this.status = fallbackORPCErrorStatus(options.code, options.status);
293
+ this.defined = options.defined ?? false;
294
+ this.data = options.data;
295
+ }
296
+ toJSON() {
297
+ return {
298
+ defined: this.defined,
299
+ code: this.code,
300
+ status: this.status,
301
+ message: this.message,
302
+ data: this.data
303
+ };
304
+ }
305
+ static isValidJSON(json) {
306
+ return isPlainObject(json) && "defined" in json && typeof json.defined === "boolean" && "code" in json && typeof json.code === "string" && "status" in json && typeof json.status === "number" && "message" in json && typeof json.message === "string";
307
+ }
308
+ };
309
+ function isDefinedError(error) {
310
+ return error instanceof ORPCError && error.defined;
311
+ }
312
+ async function validateORPCError(map, error) {
313
+ const { code, status, message, data, cause, defined } = error;
314
+ const config = map?.[error.code];
315
+ if (!config || fallbackORPCErrorStatus(error.code, config.status) !== error.status) {
316
+ return defined ? new ORPCError({ defined: false, code, status, message, data, cause }) : error;
317
+ }
318
+ if (!config.data) {
319
+ return defined ? error : new ORPCError({ defined: true, code, status, message, data, cause });
320
+ }
321
+ const validated = await config.data["~standard"].validate(error.data);
322
+ if (validated.issues) {
323
+ return defined ? new ORPCError({ defined: false, code, status, message, data, cause }) : error;
324
+ }
325
+ return new ORPCError({
326
+ defined: true,
327
+ code,
328
+ status,
329
+ message,
330
+ data: validated.value,
331
+ cause
332
+ });
333
+ }
334
+
335
+ // src/client-utils.ts
336
+ async function safe(promise) {
337
+ try {
338
+ const output = await promise;
339
+ return [output, void 0, false];
340
+ } catch (e) {
341
+ const error = e;
342
+ if (isDefinedError(error)) {
343
+ return [void 0, error, true];
344
+ }
345
+ return [void 0, error, false];
346
+ }
347
+ }
348
+
349
+ // src/config.ts
350
+ var DEFAULT_CONFIG = {
351
+ defaultMethod: "POST",
352
+ defaultSuccessStatus: 200,
353
+ defaultSuccessDescription: "OK",
354
+ defaultInputStructure: "compact",
355
+ defaultOutputStructure: "compact"
356
+ };
357
+ var GLOBAL_CONFIG_REF = { value: DEFAULT_CONFIG };
358
+ function configGlobal(config) {
359
+ if (config.defaultSuccessStatus !== void 0 && (config.defaultSuccessStatus < 200 || config.defaultSuccessStatus > 299)) {
360
+ throw new Error("[configGlobal] The defaultSuccessStatus must be between 200 and 299");
361
+ }
362
+ GLOBAL_CONFIG_REF.value = config;
363
+ }
364
+ function fallbackToGlobalConfig(key, value) {
365
+ if (value === void 0) {
366
+ const fallback = GLOBAL_CONFIG_REF.value[key];
367
+ if (fallback === void 0) {
368
+ return DEFAULT_CONFIG[key];
369
+ }
370
+ return fallback;
371
+ }
372
+ return value;
373
+ }
374
+
375
+ // src/error.ts
376
+ var ValidationError = class extends Error {
377
+ issues;
378
+ constructor(options) {
379
+ super(options.message, options);
380
+ this.issues = options.issues;
138
381
  }
139
382
  };
140
383
 
141
384
  // src/index.ts
142
- var oc = new ContractBuilder();
385
+ var oc = new ContractBuilder({
386
+ errorMap: {}
387
+ });
143
388
  export {
389
+ COMMON_ORPC_ERROR_DEFS,
144
390
  ContractBuilder,
145
391
  ContractProcedure,
146
392
  ContractRouterBuilder,
147
393
  DecoratedContractProcedure,
394
+ ORPCError,
395
+ ValidationError,
396
+ configGlobal,
397
+ fallbackORPCErrorMessage,
398
+ fallbackORPCErrorStatus,
399
+ fallbackToGlobalConfig,
148
400
  isContractProcedure,
149
- oc
401
+ isDefinedError,
402
+ oc,
403
+ safe,
404
+ validateORPCError
150
405
  };
151
406
  //# sourceMappingURL=index.js.map
@@ -1,14 +1,23 @@
1
+ import type { ErrorMap, ErrorMapGuard, ErrorMapSuggestions, StrictErrorMap } from './error-map';
1
2
  import type { RouteOptions } from './procedure';
2
3
  import type { ContractRouter } from './router';
4
+ import type { AdaptedContractRouter } from './router-builder';
3
5
  import type { HTTPPath, Schema, SchemaInput, SchemaOutput } from './types';
4
6
  import { DecoratedContractProcedure } from './procedure-decorated';
5
7
  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;
8
+ export type ContractBuilderDef<TErrorMap extends ErrorMap> = {
9
+ errorMap: TErrorMap;
10
+ };
11
+ export declare class ContractBuilder<TErrorMap extends ErrorMap> {
12
+ '~type': "ContractBuilder";
13
+ '~orpc': ContractBuilderDef<TErrorMap>;
14
+ constructor(def: ContractBuilderDef<TErrorMap>);
15
+ errors<const U extends ErrorMap & ErrorMapGuard<TErrorMap> & ErrorMapSuggestions>(errors: U): ContractBuilder<U & TErrorMap>;
16
+ prefix(prefix: HTTPPath): ContractRouterBuilder<TErrorMap>;
17
+ tag(...tags: string[]): ContractRouterBuilder<TErrorMap>;
18
+ route(route: RouteOptions): DecoratedContractProcedure<undefined, undefined, TErrorMap>;
19
+ input<U extends Schema>(schema: U, example?: SchemaInput<U>): DecoratedContractProcedure<U, undefined, TErrorMap>;
20
+ output<U extends Schema>(schema: U, example?: SchemaOutput<U>): DecoratedContractProcedure<undefined, U, TErrorMap>;
21
+ router<T extends ContractRouter<ErrorMap & Partial<StrictErrorMap<TErrorMap>>>>(router: T): AdaptedContractRouter<T, TErrorMap>;
13
22
  }
14
23
  //# sourceMappingURL=builder.d.ts.map
@@ -0,0 +1,5 @@
1
+ import type { ClientPromiseResult } from './client';
2
+ import { type ORPCError } from './error-orpc';
3
+ export type SafeResult<TOutput, TError extends Error> = [output: TOutput, error: undefined, isDefinedError: false] | [output: undefined, error: TError, isDefinedError: false] | [output: undefined, error: Extract<TError, ORPCError<any, any>>, isDefinedError: true];
4
+ export declare function safe<TOutput, TError extends Error>(promise: ClientPromiseResult<TOutput, TError>): Promise<SafeResult<TOutput, TError>>;
5
+ //# sourceMappingURL=client-utils.d.ts.map
@@ -0,0 +1,19 @@
1
+ import type { AbortSignal } from './types';
2
+ export type ClientOptions<TClientContext> = {
3
+ signal?: AbortSignal;
4
+ } & (undefined extends TClientContext ? {
5
+ context?: TClientContext;
6
+ } : {
7
+ context: TClientContext;
8
+ });
9
+ export type ClientRest<TClientContext, TInput> = [input: TInput, options: ClientOptions<TClientContext>] | (undefined extends TInput & TClientContext ? [] : never) | (undefined extends TClientContext ? [input: TInput] : never);
10
+ export type ClientPromiseResult<TOutput, TError extends Error> = Promise<TOutput> & {
11
+ __typeError?: TError;
12
+ };
13
+ export interface Client<TClientContext, TInput, TOutput, TError extends Error> {
14
+ (...rest: ClientRest<TClientContext, TInput>): ClientPromiseResult<TOutput, TError>;
15
+ }
16
+ export type NestedClient<TClientContext> = Client<TClientContext, any, any, any> | {
17
+ [k: string]: NestedClient<TClientContext>;
18
+ };
19
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1,36 @@
1
+ import type { HTTPMethod, InputStructure } from './types';
2
+ export interface ORPCConfig {
3
+ /**
4
+ * @default 'POST'
5
+ */
6
+ defaultMethod?: HTTPMethod;
7
+ /**
8
+ *
9
+ * @default 200
10
+ */
11
+ defaultSuccessStatus?: number;
12
+ /**
13
+ *
14
+ * @default 'OK'
15
+ */
16
+ defaultSuccessDescription?: string;
17
+ /**
18
+ *
19
+ * @default 'compact'
20
+ */
21
+ defaultInputStructure?: InputStructure;
22
+ /**
23
+ *
24
+ * @default 'compact'
25
+ */
26
+ defaultOutputStructure?: InputStructure;
27
+ }
28
+ /**
29
+ * Set the global configuration, this configuration can effect entire project
30
+ */
31
+ export declare function configGlobal(config: ORPCConfig): void;
32
+ /**
33
+ * Fallback the value to the global config if it is undefined
34
+ */
35
+ export declare function fallbackToGlobalConfig<T extends keyof ORPCConfig>(key: T, value: ORPCConfig[T]): Exclude<ORPCConfig[T], undefined>;
36
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1,58 @@
1
+ import type { CommonORPCErrorCode } from './error-orpc';
2
+ import type { Schema } from './types';
3
+ export type ErrorMapItem<TDataSchema extends Schema> = {
4
+ /**
5
+ *
6
+ * @default 500
7
+ */
8
+ status?: number;
9
+ message?: string;
10
+ description?: string;
11
+ data?: TDataSchema;
12
+ };
13
+ export interface ErrorMap {
14
+ [k: string]: ErrorMapItem<Schema>;
15
+ }
16
+ /**
17
+ * const U extends ErrorMap & ErrorMapGuard<TErrorMap> & ErrorMapSuggestions
18
+ *
19
+ * Purpose:
20
+ * - Helps `U` suggest `CommonORPCErrorCode` to the user when typing.
21
+ *
22
+ * Why not replace `ErrorMap` with `ErrorMapSuggestions`?
23
+ * - `ErrorMapSuggestions` has a drawback: it allows `undefined` values for items.
24
+ * - `ErrorMapGuard<TErrorMap>` uses `Partial`, which can introduce `undefined` values.
25
+ *
26
+ * This could lead to unintended behavior where `undefined` values override `TErrorMap`,
27
+ * potentially resulting in a `never` type after merging.
28
+ *
29
+ * Recommendation:
30
+ * - Use `ErrorMapSuggestions` to assist users in typing correctly but do not replace `ErrorMap`.
31
+ * - Ensure `ErrorMapGuard<TErrorMap>` is adjusted to prevent `undefined` values.
32
+ */
33
+ export type ErrorMapSuggestions = {
34
+ [key in CommonORPCErrorCode | (string & {})]?: ErrorMapItem<Schema>;
35
+ };
36
+ /**
37
+ * `U` extends `ErrorMap` & `ErrorMapGuard<TErrorMap>`
38
+ *
39
+ * `ErrorMapGuard` is a utility type that ensures `U` cannot redefine the structure of `TErrorMap`.
40
+ * It achieves this by setting each key in `TErrorMap` to `never`, effectively preventing any redefinition.
41
+ *
42
+ * Why not just use `Partial<TErrorMap>`?
43
+ * - Allowing users to redefine existing error map items would require using `StrictErrorMap`.
44
+ * - However, I prefer not to use `StrictErrorMap` frequently, due to perceived performance concerns,
45
+ * though this has not been benchmarked and is based on personal preference.
46
+ *
47
+ */
48
+ export type ErrorMapGuard<TErrorMap extends ErrorMap> = {
49
+ [K in keyof TErrorMap]?: never;
50
+ };
51
+ /**
52
+ * Since `undefined` has a specific meaning (it use default value),
53
+ * we ensure all additional properties in each item of the ErrorMap are explicitly set to `undefined`.
54
+ */
55
+ export type StrictErrorMap<T extends ErrorMap> = {
56
+ [K in keyof T]: T[K] & Partial<Record<Exclude<keyof ErrorMapItem<any>, keyof T[K]>, undefined>>;
57
+ };
58
+ //# sourceMappingURL=error-map.d.ts.map
@@ -0,0 +1,109 @@
1
+ import type { ErrorMap, ErrorMapItem } from './error-map';
2
+ import type { SchemaOutput } from './types';
3
+ export type ORPCErrorFromErrorMap<TErrorMap extends ErrorMap> = {
4
+ [K in keyof TErrorMap]: K extends string ? TErrorMap[K] extends ErrorMapItem<infer TDataSchema> ? ORPCError<K, SchemaOutput<TDataSchema>> : never : never;
5
+ }[keyof TErrorMap];
6
+ export declare const COMMON_ORPC_ERROR_DEFS: {
7
+ readonly BAD_REQUEST: {
8
+ readonly status: 400;
9
+ readonly message: "Bad Request";
10
+ };
11
+ readonly UNAUTHORIZED: {
12
+ readonly status: 401;
13
+ readonly message: "Unauthorized";
14
+ };
15
+ readonly FORBIDDEN: {
16
+ readonly status: 403;
17
+ readonly message: "Forbidden";
18
+ };
19
+ readonly NOT_FOUND: {
20
+ readonly status: 404;
21
+ readonly message: "Not Found";
22
+ };
23
+ readonly METHOD_NOT_SUPPORTED: {
24
+ readonly status: 405;
25
+ readonly message: "Method Not Supported";
26
+ };
27
+ readonly NOT_ACCEPTABLE: {
28
+ readonly status: 406;
29
+ readonly message: "Not Acceptable";
30
+ };
31
+ readonly TIMEOUT: {
32
+ readonly status: 408;
33
+ readonly message: "Request Timeout";
34
+ };
35
+ readonly CONFLICT: {
36
+ readonly status: 409;
37
+ readonly message: "Conflict";
38
+ };
39
+ readonly PRECONDITION_FAILED: {
40
+ readonly status: 412;
41
+ readonly message: "Precondition Failed";
42
+ };
43
+ readonly PAYLOAD_TOO_LARGE: {
44
+ readonly status: 413;
45
+ readonly message: "Payload Too Large";
46
+ };
47
+ readonly UNSUPPORTED_MEDIA_TYPE: {
48
+ readonly status: 415;
49
+ readonly message: "Unsupported Media Type";
50
+ };
51
+ readonly UNPROCESSABLE_CONTENT: {
52
+ readonly status: 422;
53
+ readonly message: "Unprocessable Content";
54
+ };
55
+ readonly TOO_MANY_REQUESTS: {
56
+ readonly status: 429;
57
+ readonly message: "Too Many Requests";
58
+ };
59
+ readonly CLIENT_CLOSED_REQUEST: {
60
+ readonly status: 499;
61
+ readonly message: "Client Closed Request";
62
+ };
63
+ readonly INTERNAL_SERVER_ERROR: {
64
+ readonly status: 500;
65
+ readonly message: "Internal Server Error";
66
+ };
67
+ readonly NOT_IMPLEMENTED: {
68
+ readonly status: 501;
69
+ readonly message: "Not Implemented";
70
+ };
71
+ readonly BAD_GATEWAY: {
72
+ readonly status: 502;
73
+ readonly message: "Bad Gateway";
74
+ };
75
+ readonly SERVICE_UNAVAILABLE: {
76
+ readonly status: 503;
77
+ readonly message: "Service Unavailable";
78
+ };
79
+ readonly GATEWAY_TIMEOUT: {
80
+ readonly status: 504;
81
+ readonly message: "Gateway Timeout";
82
+ };
83
+ };
84
+ export type CommonORPCErrorCode = keyof typeof COMMON_ORPC_ERROR_DEFS;
85
+ export type ORPCErrorOptions<TCode extends string, TData> = ErrorOptions & {
86
+ defined?: boolean;
87
+ code: TCode;
88
+ status?: number;
89
+ message?: string;
90
+ } & (undefined extends TData ? {
91
+ data?: TData;
92
+ } : {
93
+ data: TData;
94
+ });
95
+ export declare function fallbackORPCErrorStatus(code: CommonORPCErrorCode | (string & {}), status: number | undefined): number;
96
+ export declare function fallbackORPCErrorMessage(code: CommonORPCErrorCode | (string & {}), message: string | undefined): string;
97
+ export declare class ORPCError<TCode extends CommonORPCErrorCode | (string & {}), TData> extends Error {
98
+ readonly defined: boolean;
99
+ readonly code: TCode;
100
+ readonly status: number;
101
+ readonly data: TData;
102
+ constructor(options: ORPCErrorOptions<TCode, TData>);
103
+ toJSON(): ORPCErrorJSON<TCode, TData>;
104
+ static isValidJSON(json: unknown): json is ORPCErrorJSON<string, unknown>;
105
+ }
106
+ export type ORPCErrorJSON<TCode extends string, TData> = Pick<ORPCError<TCode, TData>, 'defined' | 'code' | 'status' | 'message' | 'data'>;
107
+ export declare function isDefinedError<T>(error: T): error is Extract<T, ORPCError<any, any>>;
108
+ export declare function validateORPCError(map: ErrorMap, error: ORPCError<any, any>): Promise<ORPCError<string, unknown>>;
109
+ //# sourceMappingURL=error-orpc.d.ts.map
@@ -0,0 +1,13 @@
1
+ import type { StandardSchemaV1 } from '@standard-schema/spec';
2
+ import type { ErrorMap } from './error-map';
3
+ import type { ORPCErrorFromErrorMap } from './error-orpc';
4
+ export type ErrorFromErrorMap<TErrorMap extends ErrorMap> = Error | ORPCErrorFromErrorMap<TErrorMap>;
5
+ export interface ValidationErrorOptions extends ErrorOptions {
6
+ message: string;
7
+ issues: readonly StandardSchemaV1.Issue[];
8
+ }
9
+ export declare class ValidationError extends Error {
10
+ readonly issues: readonly StandardSchemaV1.Issue[];
11
+ constructor(options: ValidationErrorOptions);
12
+ }
13
+ //# sourceMappingURL=error.d.ts.map
@@ -1,10 +1,18 @@
1
1
  /** unnoq */
2
2
  import { ContractBuilder } from './builder';
3
3
  export * from './builder';
4
+ export * from './client';
5
+ export * from './client-utils';
6
+ export * from './config';
7
+ export * from './error';
8
+ export * from './error-map';
9
+ export * from './error-orpc';
4
10
  export * from './procedure';
11
+ export * from './procedure-client';
5
12
  export * from './procedure-decorated';
6
13
  export * from './router';
7
14
  export * from './router-builder';
15
+ export * from './router-client';
8
16
  export * from './types';
9
- export declare const oc: ContractBuilder;
17
+ export declare const oc: ContractBuilder<Record<never, never>>;
10
18
  //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,6 @@
1
+ import type { Client } from './client';
2
+ import type { ErrorFromErrorMap } from './error';
3
+ import type { ErrorMap } from './error-map';
4
+ import type { Schema, SchemaInput, SchemaOutput } from './types';
5
+ export type ContractProcedureClient<TClientContext, TInputSchema extends Schema, TOutputSchema extends Schema, TErrorMap extends ErrorMap> = Client<TClientContext, SchemaInput<TInputSchema>, SchemaOutput<TOutputSchema>, ErrorFromErrorMap<TErrorMap>>;
6
+ //# sourceMappingURL=procedure-client.d.ts.map
@@ -1,12 +1,14 @@
1
+ import type { ErrorMap, ErrorMapGuard, ErrorMapSuggestions } from './error-map';
1
2
  import type { RouteOptions } from './procedure';
2
3
  import type { HTTPPath, Schema, SchemaInput, SchemaOutput } from './types';
3
4
  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>;
5
+ export declare class DecoratedContractProcedure<TInputSchema extends Schema, TOutputSchema extends Schema, TErrorMap extends ErrorMap> extends ContractProcedure<TInputSchema, TOutputSchema, TErrorMap> {
6
+ static decorate<UInputSchema extends Schema, UOutputSchema extends Schema, TErrorMap extends ErrorMap>(procedure: ContractProcedure<UInputSchema, UOutputSchema, TErrorMap>): DecoratedContractProcedure<UInputSchema, UOutputSchema, TErrorMap>;
7
+ route(route: RouteOptions): DecoratedContractProcedure<TInputSchema, TOutputSchema, TErrorMap>;
8
+ prefix(prefix: HTTPPath): DecoratedContractProcedure<TInputSchema, TOutputSchema, TErrorMap>;
9
+ unshiftTag(...tags: string[]): DecoratedContractProcedure<TInputSchema, TOutputSchema, TErrorMap>;
10
+ input<U extends Schema>(schema: U, example?: SchemaInput<U>): DecoratedContractProcedure<U, TOutputSchema, TErrorMap>;
11
+ output<U extends Schema>(schema: U, example?: SchemaOutput<U>): DecoratedContractProcedure<TInputSchema, U, TErrorMap>;
12
+ errors<const U extends ErrorMap & ErrorMapGuard<TErrorMap> & ErrorMapSuggestions>(errors: U): DecoratedContractProcedure<TInputSchema, TOutputSchema, TErrorMap & U>;
11
13
  }
12
14
  //# sourceMappingURL=procedure-decorated.d.ts.map
@@ -1,25 +1,83 @@
1
- import type { HTTPMethod, HTTPPath, Schema, SchemaOutput } from './types';
1
+ import type { ErrorMap } from './error-map';
2
+ import type { HTTPMethod, HTTPPath, InputStructure, OutputStructure, Schema, SchemaOutput } from './types';
2
3
  export interface RouteOptions {
3
4
  method?: HTTPMethod;
4
5
  path?: HTTPPath;
5
6
  summary?: string;
6
7
  description?: string;
7
8
  deprecated?: boolean;
8
- tags?: string[];
9
+ tags?: readonly string[];
10
+ /**
11
+ * The status code of the response when the procedure is successful.
12
+ *
13
+ * @default 200
14
+ */
15
+ successStatus?: number;
16
+ /**
17
+ * The description of the response when the procedure is successful.
18
+ *
19
+ * @default 'OK'
20
+ */
21
+ successDescription?: string;
22
+ /**
23
+ * Determines how the input should be structured based on `params`, `query`, `headers`, and `body`.
24
+ *
25
+ * @option 'compact'
26
+ * Combines `params` and either `query` or `body` (depending on the HTTP method) into a single object.
27
+ *
28
+ * @option 'detailed'
29
+ * Keeps each part of the request (`params`, `query`, `headers`, and `body`) as separate fields in the input object.
30
+ *
31
+ * Example:
32
+ * ```ts
33
+ * const input = {
34
+ * params: { id: 1 },
35
+ * query: { search: 'hello' },
36
+ * headers: { 'Content-Type': 'application/json' },
37
+ * body: { name: 'John' },
38
+ * }
39
+ * ```
40
+ *
41
+ * @default 'compact'
42
+ */
43
+ inputStructure?: InputStructure;
44
+ /**
45
+ * Determines how the response should be structured based on the output.
46
+ *
47
+ * @option 'compact'
48
+ * Includes only the body data, encoded directly in the response.
49
+ *
50
+ * @option 'detailed'
51
+ * Separates the output into `headers` and `body` fields.
52
+ * - `headers`: Custom headers to merge with the response headers.
53
+ * - `body`: The response data.
54
+ *
55
+ * Example:
56
+ * ```ts
57
+ * const output = {
58
+ * headers: { 'x-custom-header': 'value' },
59
+ * body: { message: 'Hello, world!' },
60
+ * };
61
+ * ```
62
+ *
63
+ * @default 'compact'
64
+ */
65
+ outputStructure?: OutputStructure;
9
66
  }
10
- export interface ContractProcedureDef<TInputSchema extends Schema, TOutputSchema extends Schema> {
67
+ export interface ContractProcedureDef<TInputSchema extends Schema, TOutputSchema extends Schema, TErrorMap extends ErrorMap> {
11
68
  route?: RouteOptions;
12
69
  InputSchema: TInputSchema;
13
70
  inputExample?: SchemaOutput<TInputSchema>;
14
71
  OutputSchema: TOutputSchema;
15
72
  outputExample?: SchemaOutput<TOutputSchema>;
73
+ errorMap: TErrorMap;
16
74
  }
17
- export declare class ContractProcedure<TInputSchema extends Schema, TOutputSchema extends Schema> {
75
+ export declare class ContractProcedure<TInputSchema extends Schema, TOutputSchema extends Schema, TErrorMap extends ErrorMap> {
18
76
  '~type': "ContractProcedure";
19
- '~orpc': ContractProcedureDef<TInputSchema, TOutputSchema>;
20
- constructor(def: ContractProcedureDef<TInputSchema, TOutputSchema>);
77
+ '~orpc': ContractProcedureDef<TInputSchema, TOutputSchema, TErrorMap>;
78
+ constructor(def: ContractProcedureDef<TInputSchema, TOutputSchema, TErrorMap>);
21
79
  }
22
- export type ANY_CONTRACT_PROCEDURE = ContractProcedure<any, any>;
23
- export type WELL_CONTRACT_PROCEDURE = ContractProcedure<Schema, Schema>;
80
+ export type ANY_CONTRACT_PROCEDURE = ContractProcedure<any, any, any>;
81
+ export type WELL_CONTRACT_PROCEDURE = ContractProcedure<Schema, Schema, ErrorMap>;
24
82
  export declare function isContractProcedure(item: unknown): item is ANY_CONTRACT_PROCEDURE;
25
83
  //# sourceMappingURL=procedure.d.ts.map
@@ -1,20 +1,23 @@
1
+ import type { ErrorMap, ErrorMapGuard, ErrorMapSuggestions, StrictErrorMap } from './error-map';
1
2
  import type { ContractProcedure } from './procedure';
2
3
  import type { ContractRouter } from './router';
3
4
  import type { HTTPPath } from './types';
4
5
  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;
6
+ export type AdaptedContractRouter<TContract extends ContractRouter<any>, TErrorMapExtra extends ErrorMap> = {
7
+ [K in keyof TContract]: TContract[K] extends ContractProcedure<infer UInputSchema, infer UOutputSchema, infer UErrors> ? DecoratedContractProcedure<UInputSchema, UOutputSchema, UErrors & TErrorMapExtra> : TContract[K] extends ContractRouter<any> ? AdaptedContractRouter<TContract[K], TErrorMapExtra> : never;
7
8
  };
8
- export interface ContractRouterBuilderDef {
9
+ export interface ContractRouterBuilderDef<TErrorMap extends ErrorMap> {
9
10
  prefix?: HTTPPath;
10
11
  tags?: string[];
12
+ errorMap: TErrorMap;
11
13
  }
12
- export declare class ContractRouterBuilder {
14
+ export declare class ContractRouterBuilder<TErrorMap extends ErrorMap> {
13
15
  '~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>;
16
+ '~orpc': ContractRouterBuilderDef<TErrorMap>;
17
+ constructor(def: ContractRouterBuilderDef<TErrorMap>);
18
+ prefix(prefix: HTTPPath): ContractRouterBuilder<TErrorMap>;
19
+ tag(...tags: string[]): ContractRouterBuilder<TErrorMap>;
20
+ errors<const U extends ErrorMap & ErrorMapGuard<TErrorMap> & ErrorMapSuggestions>(errors: U): ContractRouterBuilder<U & TErrorMap>;
21
+ router<T extends ContractRouter<ErrorMap & Partial<StrictErrorMap<TErrorMap>>>>(router: T): AdaptedContractRouter<T, TErrorMap>;
19
22
  }
20
23
  //# sourceMappingURL=router-builder.d.ts.map
@@ -0,0 +1,7 @@
1
+ import type { ContractProcedure } from './procedure';
2
+ import type { ContractProcedureClient } from './procedure-client';
3
+ import type { ContractRouter } from './router';
4
+ export type ContractRouterClient<TRouter extends ContractRouter<any>, TClientContext> = TRouter extends ContractProcedure<infer UInputSchema, infer UOutputSchema, infer UErrorMap> ? ContractProcedureClient<TClientContext, UInputSchema, UOutputSchema, UErrorMap> : {
5
+ [K in keyof TRouter]: TRouter[K] extends ContractRouter<any> ? ContractRouterClient<TRouter[K], TClientContext> : never;
6
+ };
7
+ //# sourceMappingURL=router-client.d.ts.map
@@ -1,12 +1,13 @@
1
- import type { ANY_CONTRACT_PROCEDURE, ContractProcedure } from './procedure';
1
+ import type { ErrorMap } from './error-map';
2
+ import type { ContractProcedure } from './procedure';
2
3
  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;
4
+ export type ContractRouter<T extends ErrorMap> = ContractProcedure<any, any, T> | {
5
+ [k: string]: ContractRouter<T>;
8
6
  };
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;
7
+ export type InferContractRouterInputs<T extends ContractRouter<any>> = T extends ContractProcedure<infer UInputSchema, any, any> ? SchemaInput<UInputSchema> : {
8
+ [K in keyof T]: T[K] extends ContractRouter<any> ? InferContractRouterInputs<T[K]> : never;
9
+ };
10
+ export type InferContractRouterOutputs<T extends ContractRouter<any>> = T extends ContractProcedure<any, infer UOutputSchema, any> ? SchemaOutput<UOutputSchema> : {
11
+ [K in keyof T]: T[K] extends ContractRouter<any> ? InferContractRouterOutputs<T[K]> : never;
11
12
  };
12
13
  //# sourceMappingURL=router.d.ts.map
@@ -1,7 +1,11 @@
1
+ import type { FindGlobalInstanceType } from '@orpc/shared';
1
2
  import type { StandardSchemaV1 } from '@standard-schema/spec';
2
3
  export type HTTPPath = `/${string}`;
3
4
  export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
5
+ export type InputStructure = 'compact' | 'detailed';
6
+ export type OutputStructure = 'compact' | 'detailed';
4
7
  export type Schema = StandardSchemaV1 | undefined;
5
8
  export type SchemaInput<TSchema extends Schema, TFallback = unknown> = TSchema extends undefined ? TFallback : TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferInput<TSchema> : TFallback;
6
9
  export type SchemaOutput<TSchema extends Schema, TFallback = unknown> = TSchema extends undefined ? TFallback : TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema> : TFallback;
10
+ export type AbortSignal = FindGlobalInstanceType<'AbortSignal'>;
7
11
  //# sourceMappingURL=types.d.ts.map
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.f22c7ec",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -30,7 +30,7 @@
30
30
  ],
31
31
  "dependencies": {
32
32
  "@standard-schema/spec": "1.0.0-beta.4",
33
- "@orpc/shared": "0.0.0-next.ee0aeaf"
33
+ "@orpc/shared": "0.0.0-next.f22c7ec"
34
34
  },
35
35
  "devDependencies": {
36
36
  "arktype": "2.0.0-rc.26",