@orpc/contract 0.0.0-next.df024bb → 0.0.0-next.df70448

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.mjs CHANGED
@@ -1,41 +1,14 @@
1
+ import { i as isContractProcedure, C as ContractProcedure, m as mergeErrorMap, V as ValidationError } from './shared/contract.D_dZrO__.mjs';
2
+ export { v as validateORPCError } from './shared/contract.D_dZrO__.mjs';
1
3
  import { mapEventIterator, ORPCError } from '@orpc/client';
2
4
  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
- }
5
+ import { isAsyncIteratorObject, get, isTypescriptObject, isPropertyKey } from '@orpc/shared';
6
+ export { AsyncIteratorClass } from '@orpc/shared';
15
7
 
16
8
  function mergeMeta(meta1, meta2) {
17
9
  return { ...meta1, ...meta2 };
18
10
  }
19
11
 
20
- class ContractProcedure {
21
- "~orpc";
22
- constructor(def) {
23
- if (def.route?.successStatus && (def.route.successStatus < 200 || def.route?.successStatus > 299)) {
24
- throw new Error("[ContractProcedure] The successStatus must be between 200 and 299");
25
- }
26
- if (Object.values(def.errorMap).some((val) => val && val.status && (val.status < 400 || val.status > 599))) {
27
- throw new Error("[ContractProcedure] The error status code must be in the 400-599 range.");
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 && "inputSchema" in item["~orpc"] && "outputSchema" in item["~orpc"] && "errorMap" in item["~orpc"] && "route" in item["~orpc"] && "meta" in item["~orpc"];
37
- }
38
-
39
12
  function mergeRoute(a, b) {
40
13
  return { ...a, ...b };
41
14
  }
@@ -60,31 +33,62 @@ function mergePrefix(a, b) {
60
33
  function mergeTags(a, b) {
61
34
  return a ? [...a, ...b] : b;
62
35
  }
63
- function adaptRoute(route, options) {
36
+ function enhanceRoute(route, options) {
64
37
  let router = route;
65
38
  if (options.prefix) {
66
39
  router = prefixRoute(router, options.prefix);
67
40
  }
68
- if (options.tags) {
41
+ if (options.tags?.length) {
69
42
  router = unshiftTagRoute(router, options.tags);
70
43
  }
71
44
  return router;
72
45
  }
73
46
 
74
- function adaptContractRouter(contract, options) {
75
- if (isContractProcedure(contract)) {
76
- const adapted2 = new ContractProcedure({
77
- ...contract["~orpc"],
78
- errorMap: mergeErrorMap(options.errorMap, contract["~orpc"].errorMap),
79
- route: adaptRoute(contract["~orpc"].route, options)
47
+ function getContractRouter(router, path) {
48
+ let current = router;
49
+ for (let i = 0; i < path.length; i++) {
50
+ const segment = path[i];
51
+ if (!current) {
52
+ return void 0;
53
+ }
54
+ if (isContractProcedure(current)) {
55
+ return void 0;
56
+ }
57
+ current = current[segment];
58
+ }
59
+ return current;
60
+ }
61
+ function enhanceContractRouter(router, options) {
62
+ if (isContractProcedure(router)) {
63
+ const enhanced2 = new ContractProcedure({
64
+ ...router["~orpc"],
65
+ errorMap: mergeErrorMap(options.errorMap, router["~orpc"].errorMap),
66
+ route: enhanceRoute(router["~orpc"].route, options)
80
67
  });
81
- return adapted2;
68
+ return enhanced2;
82
69
  }
83
- const adapted = {};
84
- for (const key in contract) {
85
- adapted[key] = adaptContractRouter(contract[key], options);
70
+ const enhanced = {};
71
+ for (const key in router) {
72
+ enhanced[key] = enhanceContractRouter(router[key], options);
86
73
  }
87
- return adapted;
74
+ return enhanced;
75
+ }
76
+ function minifyContractRouter(router) {
77
+ if (isContractProcedure(router)) {
78
+ const procedure = {
79
+ "~orpc": {
80
+ errorMap: {},
81
+ meta: router["~orpc"].meta,
82
+ route: router["~orpc"].route
83
+ }
84
+ };
85
+ return procedure;
86
+ }
87
+ const json = {};
88
+ for (const key in router) {
89
+ json[key] = minifyContractRouter(router[key]);
90
+ }
91
+ return json;
88
92
  }
89
93
 
90
94
  class ContractBuilder extends ContractProcedure {
@@ -94,7 +98,9 @@ class ContractBuilder extends ContractProcedure {
94
98
  this["~orpc"].tags = def.tags;
95
99
  }
96
100
  /**
97
- * Reset initial meta
101
+ * Sets or overrides the initial meta.
102
+ *
103
+ * @see {@link https://orpc.unnoq.com/docs/metadata Metadata Docs}
98
104
  */
99
105
  $meta(initialMeta) {
100
106
  return new ContractBuilder({
@@ -103,7 +109,11 @@ class ContractBuilder extends ContractProcedure {
103
109
  });
104
110
  }
105
111
  /**
106
- * Reset initial route
112
+ * Sets or overrides the initial route.
113
+ * This option is typically relevant when integrating with OpenAPI.
114
+ *
115
+ * @see {@link https://orpc.unnoq.com/docs/openapi/routing OpenAPI Routing Docs}
116
+ * @see {@link https://orpc.unnoq.com/docs/openapi/input-output-structure OpenAPI Input/Output Structure Docs}
107
117
  */
108
118
  $route(initialRoute) {
109
119
  return new ContractBuilder({
@@ -111,56 +121,103 @@ class ContractBuilder extends ContractProcedure {
111
121
  route: initialRoute
112
122
  });
113
123
  }
124
+ /**
125
+ * Adds type-safe custom errors to the contract.
126
+ * The provided errors are spared-merged with any existing errors in the contract.
127
+ *
128
+ * @see {@link https://orpc.unnoq.com/docs/error-handling#type%E2%80%90safe-error-handling Type-Safe Error Handling Docs}
129
+ */
114
130
  errors(errors) {
115
131
  return new ContractBuilder({
116
132
  ...this["~orpc"],
117
133
  errorMap: mergeErrorMap(this["~orpc"].errorMap, errors)
118
134
  });
119
135
  }
136
+ /**
137
+ * Sets or updates the metadata for the contract.
138
+ * The provided metadata is spared-merged with any existing metadata in the contract.
139
+ *
140
+ * @see {@link https://orpc.unnoq.com/docs/metadata Metadata Docs}
141
+ */
120
142
  meta(meta) {
121
143
  return new ContractBuilder({
122
144
  ...this["~orpc"],
123
145
  meta: mergeMeta(this["~orpc"].meta, meta)
124
146
  });
125
147
  }
148
+ /**
149
+ * Sets or updates the route definition for the contract.
150
+ * The provided route is spared-merged with any existing route in the contract.
151
+ * This option is typically relevant when integrating with OpenAPI.
152
+ *
153
+ * @see {@link https://orpc.unnoq.com/docs/openapi/routing OpenAPI Routing Docs}
154
+ * @see {@link https://orpc.unnoq.com/docs/openapi/input-output-structure OpenAPI Input/Output Structure Docs}
155
+ */
126
156
  route(route) {
127
157
  return new ContractBuilder({
128
158
  ...this["~orpc"],
129
159
  route: mergeRoute(this["~orpc"].route, route)
130
160
  });
131
161
  }
162
+ /**
163
+ * Defines the input validation schema for the contract.
164
+ *
165
+ * @see {@link https://orpc.unnoq.com/docs/procedure#input-output-validation Input Validation Docs}
166
+ */
132
167
  input(schema) {
133
168
  return new ContractBuilder({
134
169
  ...this["~orpc"],
135
170
  inputSchema: schema
136
171
  });
137
172
  }
173
+ /**
174
+ * Defines the output validation schema for the contract.
175
+ *
176
+ * @see {@link https://orpc.unnoq.com/docs/procedure#input-output-validation Output Validation Docs}
177
+ */
138
178
  output(schema) {
139
179
  return new ContractBuilder({
140
180
  ...this["~orpc"],
141
181
  outputSchema: schema
142
182
  });
143
183
  }
184
+ /**
185
+ * Prefixes all procedures in the contract router.
186
+ * The provided prefix is post-appended to any existing router prefix.
187
+ *
188
+ * @note This option does not affect procedures that do not define a path in their route definition.
189
+ *
190
+ * @see {@link https://orpc.unnoq.com/docs/openapi/routing#route-prefixes OpenAPI Route Prefixes Docs}
191
+ */
144
192
  prefix(prefix) {
145
193
  return new ContractBuilder({
146
194
  ...this["~orpc"],
147
195
  prefix: mergePrefix(this["~orpc"].prefix, prefix)
148
196
  });
149
197
  }
198
+ /**
199
+ * Adds tags to all procedures in the contract router.
200
+ * This helpful when you want to group procedures together in the OpenAPI specification.
201
+ *
202
+ * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification#operation-metadata OpenAPI Operation Metadata Docs}
203
+ */
150
204
  tag(...tags) {
151
205
  return new ContractBuilder({
152
206
  ...this["~orpc"],
153
207
  tags: mergeTags(this["~orpc"].tags, tags)
154
208
  });
155
209
  }
210
+ /**
211
+ * Applies all of the previously defined options to the specified contract router.
212
+ *
213
+ * @see {@link https://orpc.unnoq.com/docs/router#extending-router Extending Router Docs}
214
+ */
156
215
  router(router) {
157
- return adaptContractRouter(router, this["~orpc"]);
216
+ return enhanceContractRouter(router, this["~orpc"]);
158
217
  }
159
218
  }
160
219
  const oc = new ContractBuilder({
161
220
  errorMap: {},
162
- inputSchema: void 0,
163
- outputSchema: void 0,
164
221
  route: {},
165
222
  meta: {}
166
223
  });
@@ -179,11 +236,11 @@ function fallbackContractConfig(key, value) {
179
236
  return value;
180
237
  }
181
238
 
182
- const EVENT_ITERATOR_SCHEMA_SYMBOL = Symbol("ORPC_EVENT_ITERATOR_SCHEMA");
239
+ const EVENT_ITERATOR_DETAILS_SYMBOL = Symbol("ORPC_EVENT_ITERATOR_DETAILS");
183
240
  function eventIterator(yields, returns) {
184
241
  return {
185
242
  "~standard": {
186
- [EVENT_ITERATOR_SCHEMA_SYMBOL]: { yields, returns },
243
+ [EVENT_ITERATOR_DETAILS_SYMBOL]: { yields, returns },
187
244
  vendor: "orpc",
188
245
  version: 1,
189
246
  validate(iterator) {
@@ -202,7 +259,8 @@ function eventIterator(yields, returns) {
202
259
  message: "Event iterator validation failed",
203
260
  cause: new ValidationError({
204
261
  issues: result.issues,
205
- message: "Event iterator validation failed"
262
+ message: "Event iterator validation failed",
263
+ data: value
206
264
  })
207
265
  });
208
266
  }
@@ -219,7 +277,20 @@ function getEventIteratorSchemaDetails(schema) {
219
277
  if (schema === void 0) {
220
278
  return void 0;
221
279
  }
222
- return schema["~standard"][EVENT_ITERATOR_SCHEMA_SYMBOL];
280
+ return schema["~standard"][EVENT_ITERATOR_DETAILS_SYMBOL];
281
+ }
282
+
283
+ function inferRPCMethodFromContractRouter(contract) {
284
+ return (_, path) => {
285
+ const procedure = get(contract, path);
286
+ if (!isContractProcedure(procedure)) {
287
+ throw new Error(
288
+ `[inferRPCMethodFromContractRouter] No valid procedure found at path "${path.join(".")}". This may happen when the contract router is not properly configured.`
289
+ );
290
+ }
291
+ const method = fallbackContractConfig("defaultMethod", procedure["~orpc"].route.method);
292
+ return method === "HEAD" ? "GET" : method;
293
+ };
223
294
  }
224
295
 
225
296
  function type(...[map]) {
@@ -237,4 +308,19 @@ function type(...[map]) {
237
308
  };
238
309
  }
239
310
 
240
- export { ContractBuilder, ContractProcedure, ValidationError, adaptContractRouter, adaptRoute, eventIterator, fallbackContractConfig, getEventIteratorSchemaDetails, isContractProcedure, mergeErrorMap, mergeMeta, mergePrefix, mergeRoute, mergeTags, oc, prefixRoute, type, unshiftTagRoute };
311
+ function isSchemaIssue(issue) {
312
+ if (!isTypescriptObject(issue) || typeof issue.message !== "string") {
313
+ return false;
314
+ }
315
+ if (issue.path !== void 0) {
316
+ if (!Array.isArray(issue.path)) {
317
+ return false;
318
+ }
319
+ if (!issue.path.every((segment) => isPropertyKey(segment) || isTypescriptObject(segment) && isPropertyKey(segment.key))) {
320
+ return false;
321
+ }
322
+ }
323
+ return true;
324
+ }
325
+
326
+ export { ContractBuilder, ContractProcedure, ValidationError, enhanceContractRouter, enhanceRoute, eventIterator, fallbackContractConfig, getContractRouter, getEventIteratorSchemaDetails, inferRPCMethodFromContractRouter, isContractProcedure, isSchemaIssue, mergeErrorMap, mergeMeta, mergePrefix, mergeRoute, mergeTags, minifyContractRouter, oc, prefixRoute, type, unshiftTagRoute };
@@ -0,0 +1,43 @@
1
+ import { ClientContext } from '@orpc/client';
2
+ import { StandardLinkPlugin, StandardLinkOptions } from '@orpc/client/standard';
3
+ import { A as AnyContractRouter } from '../shared/contract.CvRxURhn.mjs';
4
+ import '@orpc/shared';
5
+ import '@standard-schema/spec';
6
+ import 'openapi-types';
7
+
8
+ declare class RequestValidationPluginError extends Error {
9
+ }
10
+ /**
11
+ * A link plugin that validates client requests against your contract schema,
12
+ * ensuring that data sent to your server matches the expected types defined in your contract.
13
+ *
14
+ * @throws {ORPCError} with code `BAD_REQUEST` (same as server side) if input doesn't match the expected schema
15
+ * @see {@link https://orpc.unnoq.com/docs/plugins/request-validation Request Validation Plugin Docs}
16
+ */
17
+ declare class RequestValidationPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
18
+ private readonly contract;
19
+ constructor(contract: AnyContractRouter);
20
+ init(options: StandardLinkOptions<T>): void;
21
+ }
22
+
23
+ /**
24
+ * A link plugin that validates server responses against your contract schema,
25
+ * ensuring that data returned from your server matches the expected types defined in your contract.
26
+ *
27
+ * - Throws `ValidationError` if output doesn't match the expected schema
28
+ * - Converts mismatched defined errors to normal `ORPCError` instances
29
+ *
30
+ * @see {@link https://orpc.unnoq.com/docs/plugins/response-validation Response Validation Plugin Docs}
31
+ */
32
+ declare class ResponseValidationPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
33
+ private readonly contract;
34
+ constructor(contract: AnyContractRouter);
35
+ /**
36
+ * run before (validate after) retry plugin, because validation failed can't be retried
37
+ * run before (validate after) durable iterator plugin, because we expect durable iterator to validation (if user use it)
38
+ */
39
+ order: number;
40
+ init(options: StandardLinkOptions<T>): void;
41
+ }
42
+
43
+ export { RequestValidationPlugin, RequestValidationPluginError, ResponseValidationPlugin };
@@ -0,0 +1,43 @@
1
+ import { ClientContext } from '@orpc/client';
2
+ import { StandardLinkPlugin, StandardLinkOptions } from '@orpc/client/standard';
3
+ import { A as AnyContractRouter } from '../shared/contract.CvRxURhn.js';
4
+ import '@orpc/shared';
5
+ import '@standard-schema/spec';
6
+ import 'openapi-types';
7
+
8
+ declare class RequestValidationPluginError extends Error {
9
+ }
10
+ /**
11
+ * A link plugin that validates client requests against your contract schema,
12
+ * ensuring that data sent to your server matches the expected types defined in your contract.
13
+ *
14
+ * @throws {ORPCError} with code `BAD_REQUEST` (same as server side) if input doesn't match the expected schema
15
+ * @see {@link https://orpc.unnoq.com/docs/plugins/request-validation Request Validation Plugin Docs}
16
+ */
17
+ declare class RequestValidationPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
18
+ private readonly contract;
19
+ constructor(contract: AnyContractRouter);
20
+ init(options: StandardLinkOptions<T>): void;
21
+ }
22
+
23
+ /**
24
+ * A link plugin that validates server responses against your contract schema,
25
+ * ensuring that data returned from your server matches the expected types defined in your contract.
26
+ *
27
+ * - Throws `ValidationError` if output doesn't match the expected schema
28
+ * - Converts mismatched defined errors to normal `ORPCError` instances
29
+ *
30
+ * @see {@link https://orpc.unnoq.com/docs/plugins/response-validation Response Validation Plugin Docs}
31
+ */
32
+ declare class ResponseValidationPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
33
+ private readonly contract;
34
+ constructor(contract: AnyContractRouter);
35
+ /**
36
+ * run before (validate after) retry plugin, because validation failed can't be retried
37
+ * run before (validate after) durable iterator plugin, because we expect durable iterator to validation (if user use it)
38
+ */
39
+ order: number;
40
+ init(options: StandardLinkOptions<T>): void;
41
+ }
42
+
43
+ export { RequestValidationPlugin, RequestValidationPluginError, ResponseValidationPlugin };
@@ -0,0 +1,81 @@
1
+ import { ORPCError } from '@orpc/client';
2
+ import { get } from '@orpc/shared';
3
+ import { i as isContractProcedure, V as ValidationError, v as validateORPCError } from '../shared/contract.D_dZrO__.mjs';
4
+
5
+ class RequestValidationPluginError extends Error {
6
+ }
7
+ class RequestValidationPlugin {
8
+ constructor(contract) {
9
+ this.contract = contract;
10
+ }
11
+ init(options) {
12
+ options.interceptors ??= [];
13
+ options.interceptors.push(async ({ next, path, input }) => {
14
+ const procedure = get(this.contract, path);
15
+ if (!isContractProcedure(procedure)) {
16
+ throw new RequestValidationPluginError(`No valid procedure found at path "${path.join(".")}", this may happen when the contract router is not properly configured.`);
17
+ }
18
+ const inputSchema = procedure["~orpc"].inputSchema;
19
+ if (inputSchema) {
20
+ const result = await inputSchema["~standard"].validate(input);
21
+ if (result.issues) {
22
+ throw new ORPCError("BAD_REQUEST", {
23
+ message: "Input validation failed",
24
+ data: {
25
+ issues: result.issues
26
+ },
27
+ cause: new ValidationError({
28
+ message: "Input validation failed",
29
+ issues: result.issues,
30
+ data: input
31
+ })
32
+ });
33
+ }
34
+ }
35
+ return await next();
36
+ });
37
+ }
38
+ }
39
+
40
+ class ResponseValidationPlugin {
41
+ constructor(contract) {
42
+ this.contract = contract;
43
+ }
44
+ /**
45
+ * run before (validate after) retry plugin, because validation failed can't be retried
46
+ * run before (validate after) durable iterator plugin, because we expect durable iterator to validation (if user use it)
47
+ */
48
+ order = 12e5;
49
+ init(options) {
50
+ options.interceptors ??= [];
51
+ options.interceptors.push(async ({ next, path }) => {
52
+ const procedure = get(this.contract, path);
53
+ if (!isContractProcedure(procedure)) {
54
+ throw new Error(`[ResponseValidationPlugin] no valid procedure found at path "${path.join(".")}", this may happen when the contract router is not properly configured.`);
55
+ }
56
+ try {
57
+ const output = await next();
58
+ const outputSchema = procedure["~orpc"].outputSchema;
59
+ if (!outputSchema) {
60
+ return output;
61
+ }
62
+ const result = await outputSchema["~standard"].validate(output);
63
+ if (result.issues) {
64
+ throw new ValidationError({
65
+ message: "Server response output does not match expected schema",
66
+ issues: result.issues,
67
+ data: output
68
+ });
69
+ }
70
+ return result.value;
71
+ } catch (e) {
72
+ if (e instanceof ORPCError) {
73
+ throw await validateORPCError(procedure["~orpc"].errorMap, e);
74
+ }
75
+ throw e;
76
+ }
77
+ });
78
+ }
79
+ }
80
+
81
+ export { RequestValidationPlugin, RequestValidationPluginError, ResponseValidationPlugin };