@orpc/contract 2.0.0-beta.5 → 2.0.0-beta.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +139 -102
- package/dist/builder-variants.d.ts +103 -0
- package/dist/builder.d.ts +78 -0
- package/dist/builder.js +108 -0
- package/dist/client-factory.d.ts +24 -0
- package/dist/client-factory.js +38 -0
- package/dist/error-factory.d.ts +77 -0
- package/dist/error-factory.js +110 -0
- package/dist/error-utils.d.ts +5 -0
- package/dist/error-utils.js +37 -0
- package/dist/error.d.ts +41 -0
- package/dist/error.js +22 -0
- package/dist/index.d.ts +20 -182
- package/dist/index.js +12 -0
- package/dist/meta-built-in.d.ts +30 -0
- package/dist/meta-built-in.js +45 -0
- package/dist/meta-utils.d.ts +55 -0
- package/dist/meta-utils.js +70 -0
- package/dist/meta.d.ts +53 -0
- package/dist/meta.js +11 -0
- package/dist/plugins/index.d.ts +3 -38
- package/dist/plugins/index.js +2 -0
- package/dist/plugins/request-validation.d.ts +28 -0
- package/dist/plugins/request-validation.js +50 -0
- package/dist/plugins/response-validation.d.ts +15 -0
- package/dist/plugins/response-validation.js +67 -0
- package/dist/procedure-client.d.ts +5 -0
- package/dist/procedure.d.ts +28 -0
- package/dist/procedure.js +17 -0
- package/dist/router-client.d.ts +11 -0
- package/dist/router-utils.d.ts +24 -0
- package/dist/router-utils.js +59 -0
- package/dist/router.d.ts +47 -0
- package/dist/schema-built-in.d.ts +18 -0
- package/dist/schema-built-in.js +69 -0
- package/dist/schema-utils.d.ts +20 -0
- package/dist/schema-utils.js +36 -0
- package/dist/schema.d.ts +25 -0
- package/package.json +34 -24
- package/dist/index.d.mts +0 -182
- package/dist/index.mjs +0 -193
- package/dist/plugins/index.d.mts +0 -38
- package/dist/plugins/index.mjs +0 -90
- package/dist/shared/contract.CW-2wl1i.mjs +0 -180
- package/dist/shared/contract.Do92aRJ4.d.mts +0 -126
- package/dist/shared/contract.Do92aRJ4.d.ts +0 -126
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { ProcedureContractBuilderWithInput, ProcedureContractBuilderWithOutput } from "./builder-variants.js";
|
|
2
|
+
import { ErrorMap } from "./error.js";
|
|
3
|
+
import { MergedErrorMap } from "./error-utils.js";
|
|
4
|
+
import { MetaPlugin } from "./meta.js";
|
|
5
|
+
import { ProcedureContract } from "./procedure.js";
|
|
6
|
+
import { RouterContract } from "./router.js";
|
|
7
|
+
import { AugmentedContractRouter } from "./router-utils.js";
|
|
8
|
+
import { AnySchema, Schema } from "./schema.js";
|
|
9
|
+
/**
|
|
10
|
+
* The input schema type used before `.input` is called.
|
|
11
|
+
* Input is `void` for better compatibility with third-party libraries,
|
|
12
|
+
* such as TanStack Query, which allow calling mutations without input.
|
|
13
|
+
*/
|
|
14
|
+
export type InitialInputSchema = Schema<void, unknown>;
|
|
15
|
+
/**
|
|
16
|
+
* The output schema type used before `.output` is called.
|
|
17
|
+
*/
|
|
18
|
+
export type InitialOutputSchema = Schema<unknown>;
|
|
19
|
+
/**
|
|
20
|
+
* The contract builder behind `oc`. Chain its methods to define procedure
|
|
21
|
+
* contracts — metadata, errors, and input/output schemas — without any
|
|
22
|
+
* business logic.
|
|
23
|
+
*
|
|
24
|
+
* @see {@link https://orpc.dev/docs/contract/procedure | Procedure Contract}
|
|
25
|
+
*/
|
|
26
|
+
export declare class ContractBuilder<TErrorMap extends ErrorMap> extends ProcedureContract<InitialInputSchema, InitialOutputSchema, TErrorMap> {
|
|
27
|
+
/**
|
|
28
|
+
* Private constructor to prevent direct instantiation.
|
|
29
|
+
* Use the static `create` method to initialize a new instance with a safe initial definition.
|
|
30
|
+
*/
|
|
31
|
+
private constructor();
|
|
32
|
+
/**
|
|
33
|
+
* Creates a fresh contract builder with an empty definition.
|
|
34
|
+
* Prefer the exported `oc` instance over calling this directly.
|
|
35
|
+
*
|
|
36
|
+
* @see {@link https://orpc.dev/docs/contract/procedure | Procedure Contract}
|
|
37
|
+
*/
|
|
38
|
+
static create(): ContractBuilder<{}>;
|
|
39
|
+
/**
|
|
40
|
+
* Applies metadata plugins to contracts built from this builder.
|
|
41
|
+
*
|
|
42
|
+
* @see {@link https://orpc.dev/docs/contract/procedure#metadata | Procedure Contract - Metadata}
|
|
43
|
+
*/
|
|
44
|
+
meta(...plugins: MetaPlugin<InitialInputSchema, InitialOutputSchema, TErrorMap>[]): ContractBuilder<TErrorMap>;
|
|
45
|
+
/**
|
|
46
|
+
* Defines typesafe errors that implementations of this contract can throw.
|
|
47
|
+
*
|
|
48
|
+
* @see {@link https://orpc.dev/docs/contract/procedure#typesafe-errors | Procedure Contract - Typesafe Errors}
|
|
49
|
+
*/
|
|
50
|
+
errors<T extends ErrorMap>(errors: T): ContractBuilder<MergedErrorMap<TErrorMap, T>>;
|
|
51
|
+
/**
|
|
52
|
+
* Defines the input schema used to validate and type the procedure input.
|
|
53
|
+
*
|
|
54
|
+
* @see {@link https://orpc.dev/docs/contract/procedure#inputoutput-validation | Procedure Contract - Input/Output Validation}
|
|
55
|
+
*/
|
|
56
|
+
input<T extends AnySchema>(schema: T): ProcedureContractBuilderWithInput<T, TErrorMap>;
|
|
57
|
+
/**
|
|
58
|
+
* Defines the output schema used to validate and type the procedure output.
|
|
59
|
+
*
|
|
60
|
+
* @see {@link https://orpc.dev/docs/contract/procedure#inputoutput-validation | Procedure Contract - Input/Output Validation}
|
|
61
|
+
*/
|
|
62
|
+
output<T extends AnySchema>(schema: T): ProcedureContractBuilderWithOutput<T, TErrorMap>;
|
|
63
|
+
/**
|
|
64
|
+
* Applies the builder's errors and metadata to every procedure contract in
|
|
65
|
+
* the given router contract.
|
|
66
|
+
*
|
|
67
|
+
* @see {@link https://orpc.dev/docs/contract/router#extending-router | Router Contract - Extending Router}
|
|
68
|
+
*/
|
|
69
|
+
router<T extends RouterContract>(router: T): AugmentedContractRouter<T, TErrorMap>;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The oRPC contract builder. Chain methods like `.input`, `.errors`, and
|
|
73
|
+
* `.output` to define procedure contracts, then compose them into router
|
|
74
|
+
* contracts.
|
|
75
|
+
*
|
|
76
|
+
* @see {@link https://orpc.dev/docs/contract/procedure | Procedure Contract}
|
|
77
|
+
*/
|
|
78
|
+
export declare const oc: ContractBuilder<{}>;
|
package/dist/builder.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { mergeErrorMap } from "./error-utils.js";
|
|
2
|
+
import { getHiddenMetaPlugins } from "./meta.js";
|
|
3
|
+
import { resolveMetaPlugins } from "./meta-utils.js";
|
|
4
|
+
import { ProcedureContract } from "./procedure.js";
|
|
5
|
+
import { augmentContractRouter } from "./router-utils.js";
|
|
6
|
+
import { toArray } from "@orpc/shared";
|
|
7
|
+
// src/builder.ts
|
|
8
|
+
/**
|
|
9
|
+
* The contract builder behind `oc`. Chain its methods to define procedure
|
|
10
|
+
* contracts — metadata, errors, and input/output schemas — without any
|
|
11
|
+
* business logic.
|
|
12
|
+
*
|
|
13
|
+
* @see {@link https://orpc.dev/docs/contract/procedure | Procedure Contract}
|
|
14
|
+
*/
|
|
15
|
+
var ContractBuilder = class ContractBuilder extends ProcedureContract {
|
|
16
|
+
/**
|
|
17
|
+
* Private constructor to prevent direct instantiation.
|
|
18
|
+
* Use the static `create` method to initialize a new instance with a safe initial definition.
|
|
19
|
+
*/
|
|
20
|
+
constructor(definition) {
|
|
21
|
+
super(definition);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Creates a fresh contract builder with an empty definition.
|
|
25
|
+
* Prefer the exported `oc` instance over calling this directly.
|
|
26
|
+
*
|
|
27
|
+
* @see {@link https://orpc.dev/docs/contract/procedure | Procedure Contract}
|
|
28
|
+
*/
|
|
29
|
+
static create() {
|
|
30
|
+
return new ContractBuilder({
|
|
31
|
+
errorMap: {},
|
|
32
|
+
meta: {}
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Applies metadata plugins to contracts built from this builder.
|
|
37
|
+
*
|
|
38
|
+
* @see {@link https://orpc.dev/docs/contract/procedure#metadata | Procedure Contract - Metadata}
|
|
39
|
+
*/
|
|
40
|
+
meta(...plugins) {
|
|
41
|
+
const [meta, metaPlugins] = resolveMetaPlugins(this["~orpc"].meta, this["~orpc"].metaPlugins, plugins);
|
|
42
|
+
return new ContractBuilder({
|
|
43
|
+
...this["~orpc"],
|
|
44
|
+
meta,
|
|
45
|
+
metaPlugins
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Defines typesafe errors that implementations of this contract can throw.
|
|
50
|
+
*
|
|
51
|
+
* @see {@link https://orpc.dev/docs/contract/procedure#typesafe-errors | Procedure Contract - Typesafe Errors}
|
|
52
|
+
*/
|
|
53
|
+
errors(errors) {
|
|
54
|
+
let result = new ContractBuilder({
|
|
55
|
+
...this["~orpc"],
|
|
56
|
+
errorMap: mergeErrorMap(this["~orpc"].errorMap, errors)
|
|
57
|
+
});
|
|
58
|
+
const plugins = getHiddenMetaPlugins(errors);
|
|
59
|
+
if (plugins) result = result.meta(...plugins);
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Defines the input schema used to validate and type the procedure input.
|
|
64
|
+
*
|
|
65
|
+
* @see {@link https://orpc.dev/docs/contract/procedure#inputoutput-validation | Procedure Contract - Input/Output Validation}
|
|
66
|
+
*/
|
|
67
|
+
input(schema) {
|
|
68
|
+
let result = new ContractBuilder({
|
|
69
|
+
...this["~orpc"],
|
|
70
|
+
inputSchemas: [...toArray(this["~orpc"].inputSchemas), schema]
|
|
71
|
+
});
|
|
72
|
+
const plugins = getHiddenMetaPlugins(schema);
|
|
73
|
+
if (plugins) result = result.meta(...plugins);
|
|
74
|
+
return result;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Defines the output schema used to validate and type the procedure output.
|
|
78
|
+
*
|
|
79
|
+
* @see {@link https://orpc.dev/docs/contract/procedure#inputoutput-validation | Procedure Contract - Input/Output Validation}
|
|
80
|
+
*/
|
|
81
|
+
output(schema) {
|
|
82
|
+
let result = new ContractBuilder({
|
|
83
|
+
...this["~orpc"],
|
|
84
|
+
outputSchemas: [...toArray(this["~orpc"].outputSchemas), schema]
|
|
85
|
+
});
|
|
86
|
+
const plugins = getHiddenMetaPlugins(schema);
|
|
87
|
+
if (plugins) result = result.meta(...plugins);
|
|
88
|
+
return result;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Applies the builder's errors and metadata to every procedure contract in
|
|
92
|
+
* the given router contract.
|
|
93
|
+
*
|
|
94
|
+
* @see {@link https://orpc.dev/docs/contract/router#extending-router | Router Contract - Extending Router}
|
|
95
|
+
*/
|
|
96
|
+
router(router) {
|
|
97
|
+
return augmentContractRouter(router, this["~orpc"]);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* The oRPC contract builder. Chain methods like `.input`, `.errors`, and
|
|
102
|
+
* `.output` to define procedure contracts, then compose them into router
|
|
103
|
+
* contracts.
|
|
104
|
+
*
|
|
105
|
+
* @see {@link https://orpc.dev/docs/contract/procedure | Procedure Contract}
|
|
106
|
+
*/
|
|
107
|
+
const oc = /* @__PURE__ */ ContractBuilder.create();
|
|
108
|
+
export { ContractBuilder, oc };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { RouterContract } from "./router.js";
|
|
2
|
+
import { RouterContractClient } from "./router-client.js";
|
|
3
|
+
import { ClientContext, ClientLink, ORPCClientOptions } from "@orpc/client";
|
|
4
|
+
export interface ContractClientFactory<TClientContext extends ClientContext> {
|
|
5
|
+
<T extends RouterContract>(contract: T): RouterContractClient<T, TClientContext>;
|
|
6
|
+
}
|
|
7
|
+
export interface ContractClientFactoryOptions<TClientContext extends ClientContext> extends Pick<ORPCClientOptions<RouterContractClient<RouterContract, TClientContext>>, "interceptors" | "scoped"> {
|
|
8
|
+
/**
|
|
9
|
+
* An optional reference to the root router-contract.
|
|
10
|
+
* When provided, the client factory will automatically register the passed contract
|
|
11
|
+
* into the router at the path defined by `meta.path`.
|
|
12
|
+
*/
|
|
13
|
+
contractRef?: RouterContract | undefined;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Creates a client factory that builds a client from any procedure or router contract,
|
|
17
|
+
* so large projects can import individual contracts instead of a single root client.
|
|
18
|
+
*
|
|
19
|
+
* @remarks
|
|
20
|
+
* **Warning**: Every procedure contract passed to the factory must define `meta.path` matching its location in the root contract.
|
|
21
|
+
*
|
|
22
|
+
* @see {@link https://orpc.dev/docs/contract/client-factory | Contract Client Factory}
|
|
23
|
+
*/
|
|
24
|
+
export declare function createContractClientFactory<TClientContext extends ClientContext>(link: ClientLink<TClientContext>, options?: ContractClientFactoryOptions<TClientContext>): ContractClientFactory<TClientContext>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { resolveBasePathMeta } from "./meta-built-in.js";
|
|
2
|
+
import { ProcedureContract } from "./procedure.js";
|
|
3
|
+
import { get, isNonPrimitive, set } from "@orpc/shared";
|
|
4
|
+
import { createORPCClient } from "@orpc/client";
|
|
5
|
+
// src/client-factory.ts
|
|
6
|
+
/**
|
|
7
|
+
* Creates a client factory that builds a client from any procedure or router contract,
|
|
8
|
+
* so large projects can import individual contracts instead of a single root client.
|
|
9
|
+
*
|
|
10
|
+
* @remarks
|
|
11
|
+
* **Warning**: Every procedure contract passed to the factory must define `meta.path` matching its location in the root contract.
|
|
12
|
+
*
|
|
13
|
+
* @see {@link https://orpc.dev/docs/contract/client-factory | Contract Client Factory}
|
|
14
|
+
*/
|
|
15
|
+
function createContractClientFactory(link, options = {}) {
|
|
16
|
+
const factory = (contract) => {
|
|
17
|
+
const path = resolveBasePathMeta(contract);
|
|
18
|
+
if (path === void 0) throw new TypeError("ContractClientFactory: procedure contract must define `meta.path` that matches its path in the root router contract.");
|
|
19
|
+
const contractRef = options.contractRef;
|
|
20
|
+
if (contractRef) {
|
|
21
|
+
const register = (contract, path) => {
|
|
22
|
+
if (contract instanceof ProcedureContract) {
|
|
23
|
+
set(contractRef, [...path, "~orpc"], contract["~orpc"]);
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
if (isNonPrimitive(contract)) for (const [key, value] of Object.entries(contract)) register(value, [...path, key]);
|
|
27
|
+
};
|
|
28
|
+
register(contract, path);
|
|
29
|
+
}
|
|
30
|
+
return createORPCClient(link, {
|
|
31
|
+
...options,
|
|
32
|
+
scoped: get(options.scoped, path),
|
|
33
|
+
path
|
|
34
|
+
});
|
|
35
|
+
};
|
|
36
|
+
return factory;
|
|
37
|
+
}
|
|
38
|
+
export { createContractClientFactory };
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { ErrorMap, ErrorMapItem } from "./error.js";
|
|
2
|
+
import { AnySchema, InferSchemaInput, Schema } from "./schema.js";
|
|
3
|
+
import { MaybeOptionalOptions } from "@orpc/shared";
|
|
4
|
+
import { ORPCError, ORPCErrorCode, ORPCErrorOptions } from "@orpc/client";
|
|
5
|
+
export interface ORPCErrorFactoryOptions<TData> {
|
|
6
|
+
/**
|
|
7
|
+
* Optional schema used to type and validate the error data.
|
|
8
|
+
* Must be a synchronous schema.
|
|
9
|
+
*/
|
|
10
|
+
data?: Schema<TData> | undefined;
|
|
11
|
+
/**
|
|
12
|
+
* Optional default message, can be overridden when constructing an error.
|
|
13
|
+
*/
|
|
14
|
+
message?: string | undefined;
|
|
15
|
+
}
|
|
16
|
+
export interface ORPCErrorFactory<TCode extends ORPCErrorCode, TData> extends ErrorMapItem {
|
|
17
|
+
code: TCode;
|
|
18
|
+
data: Schema<TData>;
|
|
19
|
+
new (...rest: MaybeOptionalOptions<ORPCErrorOptions<TData>>): ORPCError<TCode, TData>;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Creates a reusable error class ({@link ORPCErrorFactory}) for the given code,
|
|
23
|
+
* default message, and data schema.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```ts
|
|
27
|
+
* const RateLimitedError = error('RATE_LIMITED', {
|
|
28
|
+
* message: 'You are being rate limited',
|
|
29
|
+
* data: z.object({ retryAfter: z.number() }),
|
|
30
|
+
* })
|
|
31
|
+
*
|
|
32
|
+
* const procedure = os
|
|
33
|
+
* .errors({ [RateLimitedError.code]: RateLimitedError })
|
|
34
|
+
* .handler(() => {
|
|
35
|
+
* throw new RateLimitedError({ data: { retryAfter: 60 } })
|
|
36
|
+
* })
|
|
37
|
+
*
|
|
38
|
+
* try {
|
|
39
|
+
* const output = call(procedure)
|
|
40
|
+
* } catch (error) {
|
|
41
|
+
* if (error instanceof RateLimitedError) {
|
|
42
|
+
* console.log(error.data.retryAfter)
|
|
43
|
+
* }
|
|
44
|
+
* }
|
|
45
|
+
* ```
|
|
46
|
+
*
|
|
47
|
+
* @see {@link https://orpc.dev/docs/error-handling#error-factory | Error Handling - Error Factory}
|
|
48
|
+
*/
|
|
49
|
+
export declare function error<TCode extends ORPCErrorCode, TData = unknown>(code: TCode, { data: dataSchema, message }?: ORPCErrorFactoryOptions<TData>): ORPCErrorFactory<TCode, TData>;
|
|
50
|
+
export type ORPCErrorConstructorMapItemOptions<TData> = Omit<ORPCErrorOptions<TData>, "status">;
|
|
51
|
+
export interface ORPCErrorConstructorMapItem<TCode extends ORPCErrorCode, TInData> {
|
|
52
|
+
(...rest: MaybeOptionalOptions<ORPCErrorConstructorMapItemOptions<TInData>>): ORPCError<TCode, TInData>;
|
|
53
|
+
}
|
|
54
|
+
export type ORPCErrorConstructorMap<out T extends ErrorMap> = { [K in keyof T]-?: Exclude<T[K], undefined> extends (infer I extends ErrorMapItem) ? ORPCErrorConstructorMapItem<K & ORPCErrorCode, I["data"] extends AnySchema ? InferSchemaInput<I["data"]> : unknown> : never; };
|
|
55
|
+
/**
|
|
56
|
+
* Creates a map of ORPC error constructors.
|
|
57
|
+
*
|
|
58
|
+
* The returned object is a `Proxy` that allows access to arbitrary error codes:
|
|
59
|
+
* - If the code exists in the provided `errorMap`, the corresponding constructor
|
|
60
|
+
* will create a **defined** `ORPCError`.
|
|
61
|
+
* - If the code does not exist, a fallback `ORPCError` constructor is returned.
|
|
62
|
+
*
|
|
63
|
+
* The `in` operator can be used to check whether an error code is explicitly
|
|
64
|
+
* defined in the map.
|
|
65
|
+
*
|
|
66
|
+
* @example
|
|
67
|
+
* ```ts
|
|
68
|
+
* const errorMap = createORPCErrorConstructorMap({
|
|
69
|
+
* NOT_FOUND: {
|
|
70
|
+
* message: 'Not Found',
|
|
71
|
+
* },
|
|
72
|
+
* })
|
|
73
|
+
*
|
|
74
|
+
* throw errorMap.NOT_FOUND()
|
|
75
|
+
* ```
|
|
76
|
+
*/
|
|
77
|
+
export declare function createORPCErrorConstructorMap<T extends ErrorMap>(errorMap: T): ORPCErrorConstructorMap<T>;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { ValidationError } from "./error.js";
|
|
2
|
+
import { type } from "./schema-utils.js";
|
|
3
|
+
import { getOwn, resolveMaybeOptionalOptions } from "@orpc/shared";
|
|
4
|
+
import { ORPCError, RECURSIVE_CLIENT_UNWRAP_KEYS } from "@orpc/client";
|
|
5
|
+
// src/error-factory.ts
|
|
6
|
+
/**
|
|
7
|
+
* Creates a reusable error class ({@link ORPCErrorFactory}) for the given code,
|
|
8
|
+
* default message, and data schema.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* const RateLimitedError = error('RATE_LIMITED', {
|
|
13
|
+
* message: 'You are being rate limited',
|
|
14
|
+
* data: z.object({ retryAfter: z.number() }),
|
|
15
|
+
* })
|
|
16
|
+
*
|
|
17
|
+
* const procedure = os
|
|
18
|
+
* .errors({ [RateLimitedError.code]: RateLimitedError })
|
|
19
|
+
* .handler(() => {
|
|
20
|
+
* throw new RateLimitedError({ data: { retryAfter: 60 } })
|
|
21
|
+
* })
|
|
22
|
+
*
|
|
23
|
+
* try {
|
|
24
|
+
* const output = call(procedure)
|
|
25
|
+
* } catch (error) {
|
|
26
|
+
* if (error instanceof RateLimitedError) {
|
|
27
|
+
* console.log(error.data.retryAfter)
|
|
28
|
+
* }
|
|
29
|
+
* }
|
|
30
|
+
* ```
|
|
31
|
+
*
|
|
32
|
+
* @see {@link https://orpc.dev/docs/error-handling#error-factory | Error Handling - Error Factory}
|
|
33
|
+
*/
|
|
34
|
+
function error(code, { data: dataSchema, message } = {}) {
|
|
35
|
+
const validateData = (schema, value) => {
|
|
36
|
+
const result = schema["~standard"].validate(value);
|
|
37
|
+
if (result instanceof Promise) throw new TypeError(`Error factory "${code}" does not support async data schemas.`);
|
|
38
|
+
return result;
|
|
39
|
+
};
|
|
40
|
+
return class extends ORPCError {
|
|
41
|
+
static code = code;
|
|
42
|
+
static data = dataSchema ?? type();
|
|
43
|
+
static message = message;
|
|
44
|
+
constructor(...rest) {
|
|
45
|
+
const options = resolveMaybeOptionalOptions(rest);
|
|
46
|
+
let data = options.data;
|
|
47
|
+
if (dataSchema) {
|
|
48
|
+
const result = validateData(dataSchema, options.data);
|
|
49
|
+
if (result.issues) throw new ValidationError({
|
|
50
|
+
message: `Error factory "${code}" data validation failed`,
|
|
51
|
+
issues: result.issues,
|
|
52
|
+
invalidData: options.data
|
|
53
|
+
});
|
|
54
|
+
data = result.value;
|
|
55
|
+
}
|
|
56
|
+
super(code, {
|
|
57
|
+
...options,
|
|
58
|
+
message: options.message ?? message,
|
|
59
|
+
data
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
static [Symbol.hasInstance](instance) {
|
|
63
|
+
if (Function.prototype[Symbol.hasInstance].call(this, instance)) return true;
|
|
64
|
+
if (!(instance instanceof ORPCError)) return false;
|
|
65
|
+
if (instance.code !== code) return false;
|
|
66
|
+
if (dataSchema && validateData(dataSchema, instance.data).issues) return false;
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Creates a map of ORPC error constructors.
|
|
73
|
+
*
|
|
74
|
+
* The returned object is a `Proxy` that allows access to arbitrary error codes:
|
|
75
|
+
* - If the code exists in the provided `errorMap`, the corresponding constructor
|
|
76
|
+
* will create a **defined** `ORPCError`.
|
|
77
|
+
* - If the code does not exist, a fallback `ORPCError` constructor is returned.
|
|
78
|
+
*
|
|
79
|
+
* The `in` operator can be used to check whether an error code is explicitly
|
|
80
|
+
* defined in the map.
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* ```ts
|
|
84
|
+
* const errorMap = createORPCErrorConstructorMap({
|
|
85
|
+
* NOT_FOUND: {
|
|
86
|
+
* message: 'Not Found',
|
|
87
|
+
* },
|
|
88
|
+
* })
|
|
89
|
+
*
|
|
90
|
+
* throw errorMap.NOT_FOUND()
|
|
91
|
+
* ```
|
|
92
|
+
*/
|
|
93
|
+
function createORPCErrorConstructorMap(errorMap) {
|
|
94
|
+
return new Proxy(errorMap, { get(target, code) {
|
|
95
|
+
if (typeof code !== "string" || RECURSIVE_CLIENT_UNWRAP_KEYS.has(code)) return Reflect.get(target, code);
|
|
96
|
+
const item = (...rest) => {
|
|
97
|
+
const options = resolveMaybeOptionalOptions(rest);
|
|
98
|
+
const config = getOwn(errorMap, code);
|
|
99
|
+
const error = new ORPCError(code, {
|
|
100
|
+
message: options.message ?? config?.message,
|
|
101
|
+
data: options.data,
|
|
102
|
+
cause: options.cause
|
|
103
|
+
});
|
|
104
|
+
if (config) error.defined = true;
|
|
105
|
+
return error;
|
|
106
|
+
};
|
|
107
|
+
return item;
|
|
108
|
+
} });
|
|
109
|
+
}
|
|
110
|
+
export { createORPCErrorConstructorMap, error };
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { ErrorMap } from "./error.js";
|
|
2
|
+
import { AnyORPCError } from "@orpc/client";
|
|
3
|
+
export type MergedErrorMap<T1 extends ErrorMap, T2 extends ErrorMap> = keyof T1 extends never | keyof T2 ? T2 : Omit<T1, keyof T2> & T2;
|
|
4
|
+
export declare function mergeErrorMap<T1 extends ErrorMap = object, T2 extends ErrorMap = object>(errorMap1: T1 | undefined, errorMap2: T2 | undefined): MergedErrorMap<T1, T2>;
|
|
5
|
+
export declare function reconcileORPCError(map: ErrorMap, error: AnyORPCError): Promise<AnyORPCError>;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { getOwn } from "@orpc/shared";
|
|
2
|
+
import { cloneORPCError } from "@orpc/client";
|
|
3
|
+
// src/error-utils.ts
|
|
4
|
+
function mergeErrorMap(errorMap1, errorMap2) {
|
|
5
|
+
return {
|
|
6
|
+
...errorMap1,
|
|
7
|
+
...errorMap2
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
async function reconcileORPCError(map, error) {
|
|
11
|
+
const config = getOwn(map, error.code);
|
|
12
|
+
if (!config) {
|
|
13
|
+
if (!error.defined) return error;
|
|
14
|
+
const cloned = cloneORPCError(error);
|
|
15
|
+
cloned.defined = false;
|
|
16
|
+
return cloned;
|
|
17
|
+
}
|
|
18
|
+
if (!config.data) {
|
|
19
|
+
if (error.defined) return error;
|
|
20
|
+
const cloned = cloneORPCError(error);
|
|
21
|
+
cloned.defined = true;
|
|
22
|
+
return cloned;
|
|
23
|
+
}
|
|
24
|
+
const validated = await config.data["~standard"].validate(error.data);
|
|
25
|
+
if (validated.issues) {
|
|
26
|
+
if (!error.defined) return error;
|
|
27
|
+
const cloned = cloneORPCError(error);
|
|
28
|
+
cloned.defined = false;
|
|
29
|
+
return cloned;
|
|
30
|
+
}
|
|
31
|
+
if (error.data === validated.value && error.defined) return error;
|
|
32
|
+
const cloned = cloneORPCError(error);
|
|
33
|
+
cloned.data = validated.value;
|
|
34
|
+
cloned.defined = true;
|
|
35
|
+
return cloned;
|
|
36
|
+
}
|
|
37
|
+
export { mergeErrorMap, reconcileORPCError };
|
package/dist/error.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { AnySchema, InferSchemaOutput, SchemaIssue } from "./schema.js";
|
|
2
|
+
import { ORPCError, ORPCErrorCode } from "@orpc/client";
|
|
3
|
+
export interface ErrorMapItem {
|
|
4
|
+
/**
|
|
5
|
+
* Default message, can be overridden when constructing an error.
|
|
6
|
+
*/
|
|
7
|
+
message?: string | undefined;
|
|
8
|
+
/**
|
|
9
|
+
* Schema used to type and validate the error data.
|
|
10
|
+
*/
|
|
11
|
+
data?: AnySchema | undefined;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Map of error codes to their definitions, as passed to `.errors(...)`.
|
|
15
|
+
* Errors defined here remain properly typed on the client.
|
|
16
|
+
*
|
|
17
|
+
* @see {@link https://orpc.dev/docs/metadata | Metadata}
|
|
18
|
+
*/
|
|
19
|
+
export type ErrorMap = { [key in ORPCErrorCode]?: ErrorMapItem; };
|
|
20
|
+
export type ORPCErrorFromErrorMap<TErrorMap extends ErrorMap> = { [K in keyof TErrorMap]-?: Exclude<TErrorMap[K], undefined> extends (infer I extends ErrorMapItem) ? ORPCError<K & ORPCErrorCode, I["data"] extends AnySchema ? InferSchemaOutput<I["data"]> : unknown> : never; }[keyof TErrorMap];
|
|
21
|
+
export interface ValidationErrorOptions extends ErrorOptions {
|
|
22
|
+
message: string;
|
|
23
|
+
issues: readonly SchemaIssue[];
|
|
24
|
+
invalidData: unknown;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Error thrown when input, output, or error data fails schema validation,
|
|
28
|
+
* carrying the standard-schema `issues` and the invalid data.
|
|
29
|
+
* Usually found as the `cause` of an `ORPCError`.
|
|
30
|
+
*
|
|
31
|
+
* @see {@link https://orpc.dev/docs/recipes/validation-customization | Validation Customization}
|
|
32
|
+
*/
|
|
33
|
+
export declare class ValidationError extends Error {
|
|
34
|
+
override name: string;
|
|
35
|
+
/**
|
|
36
|
+
* This array is readonly because the upstream Standard Schema returns readonly issues.
|
|
37
|
+
*/
|
|
38
|
+
issues: readonly SchemaIssue[];
|
|
39
|
+
invalidData: unknown;
|
|
40
|
+
constructor(options: ValidationErrorOptions);
|
|
41
|
+
}
|
package/dist/error.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// src/error.ts
|
|
2
|
+
/**
|
|
3
|
+
* Error thrown when input, output, or error data fails schema validation,
|
|
4
|
+
* carrying the standard-schema `issues` and the invalid data.
|
|
5
|
+
* Usually found as the `cause` of an `ORPCError`.
|
|
6
|
+
*
|
|
7
|
+
* @see {@link https://orpc.dev/docs/recipes/validation-customization | Validation Customization}
|
|
8
|
+
*/
|
|
9
|
+
var ValidationError = class extends Error {
|
|
10
|
+
name = "ValidationError";
|
|
11
|
+
/**
|
|
12
|
+
* This array is readonly because the upstream Standard Schema returns readonly issues.
|
|
13
|
+
*/
|
|
14
|
+
issues;
|
|
15
|
+
invalidData;
|
|
16
|
+
constructor(options) {
|
|
17
|
+
super(options.message, options);
|
|
18
|
+
this.issues = options.issues;
|
|
19
|
+
this.invalidData = options.invalidData;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
export { ValidationError };
|