@orpc/openapi 0.0.0-next.ff5907c → 0.0.0-next.ff68fdb

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.
Files changed (55) hide show
  1. package/README.md +93 -0
  2. package/dist/adapters/fetch/index.d.mts +13 -0
  3. package/dist/adapters/fetch/index.d.ts +13 -0
  4. package/dist/adapters/fetch/index.mjs +11 -0
  5. package/dist/adapters/hono/index.d.mts +6 -0
  6. package/dist/adapters/hono/index.d.ts +6 -0
  7. package/dist/adapters/hono/index.mjs +11 -0
  8. package/dist/adapters/next/index.d.mts +6 -0
  9. package/dist/adapters/next/index.d.ts +6 -0
  10. package/dist/adapters/next/index.mjs +11 -0
  11. package/dist/adapters/node/index.d.mts +13 -0
  12. package/dist/adapters/node/index.d.ts +13 -0
  13. package/dist/adapters/node/index.mjs +33 -0
  14. package/dist/adapters/standard/index.d.mts +34 -0
  15. package/dist/adapters/standard/index.d.ts +34 -0
  16. package/dist/adapters/standard/index.mjs +7 -0
  17. package/dist/index.d.mts +119 -0
  18. package/dist/index.d.ts +119 -0
  19. package/dist/index.mjs +303 -0
  20. package/dist/{chunk-LPBZEW4B.js → shared/openapi.CJTe38Ya.mjs} +27 -47
  21. package/dist/shared/openapi.CbzTVvGL.mjs +31 -0
  22. package/dist/shared/openapi.DZzpQAb-.mjs +231 -0
  23. package/package.json +30 -34
  24. package/dist/chunk-UU2TTVB2.js +0 -32
  25. package/dist/chunk-XGHV4TH3.js +0 -13
  26. package/dist/fetch.js +0 -9
  27. package/dist/hono.js +0 -9
  28. package/dist/index.js +0 -701
  29. package/dist/next.js +0 -9
  30. package/dist/node.js +0 -30
  31. package/dist/src/adapters/fetch/index.d.ts +0 -2
  32. package/dist/src/adapters/fetch/openapi-handler.d.ts +0 -11
  33. package/dist/src/adapters/hono/index.d.ts +0 -2
  34. package/dist/src/adapters/next/index.d.ts +0 -2
  35. package/dist/src/adapters/node/index.d.ts +0 -2
  36. package/dist/src/adapters/node/openapi-handler.d.ts +0 -11
  37. package/dist/src/adapters/standard/index.d.ts +0 -4
  38. package/dist/src/adapters/standard/openapi-codec.d.ts +0 -16
  39. package/dist/src/adapters/standard/openapi-handler.d.ts +0 -7
  40. package/dist/src/adapters/standard/openapi-matcher.d.ts +0 -20
  41. package/dist/src/index.d.ts +0 -16
  42. package/dist/src/openapi-content-builder.d.ts +0 -10
  43. package/dist/src/openapi-error.d.ts +0 -3
  44. package/dist/src/openapi-generator.d.ts +0 -67
  45. package/dist/src/openapi-input-structure-parser.d.ts +0 -22
  46. package/dist/src/openapi-operation-extender.d.ts +0 -7
  47. package/dist/src/openapi-output-structure-parser.d.ts +0 -18
  48. package/dist/src/openapi-parameters-builder.d.ts +0 -12
  49. package/dist/src/openapi-path-parser.d.ts +0 -8
  50. package/dist/src/openapi.d.ts +0 -3
  51. package/dist/src/schema-converter.d.ts +0 -16
  52. package/dist/src/schema-utils.d.ts +0 -11
  53. package/dist/src/schema.d.ts +0 -12
  54. package/dist/src/utils.d.ts +0 -4
  55. package/dist/standard.js +0 -10
package/dist/index.mjs ADDED
@@ -0,0 +1,303 @@
1
+ import { isProcedure, resolveContractProcedures, toHttpPath } from '@orpc/server';
2
+ import { fallbackORPCErrorStatus, fallbackORPCErrorMessage } from '@orpc/client';
3
+ import { fallbackContractConfig, getEventIteratorSchemaDetails } from '@orpc/contract';
4
+ import { OpenAPISerializer } from '@orpc/openapi-client/standard';
5
+ import { clone } from '@orpc/shared';
6
+ import { t as toOpenAPIMethod, a as toOpenAPIPath, b as toOpenAPIEventIteratorContent, g as getDynamicParams, i as isAnySchema, c as isObjectSchema, d as separateObjectSchema, e as checkParamsSchema, f as toOpenAPIParameters, h as toOpenAPIContent, j as toOpenAPISchema } from './shared/openapi.DZzpQAb-.mjs';
7
+ export { L as LOGIC_KEYWORDS, l as filterSchemaBranches, k as isFileSchema, s as standardizeHTTPPath } from './shared/openapi.DZzpQAb-.mjs';
8
+ export { Format as JSONSchemaFormat } from 'json-schema-typed/draft-2020-12';
9
+
10
+ const OPERATION_EXTENDER_SYMBOL = Symbol("ORPC_OPERATION_EXTENDER");
11
+ function customOpenAPIOperation(o, extend) {
12
+ return new Proxy(o, {
13
+ get(target, prop, receiver) {
14
+ if (prop === OPERATION_EXTENDER_SYMBOL) {
15
+ return extend;
16
+ }
17
+ return Reflect.get(target, prop, receiver);
18
+ }
19
+ });
20
+ }
21
+ function getCustomOpenAPIOperation(o) {
22
+ return o[OPERATION_EXTENDER_SYMBOL];
23
+ }
24
+ function applyCustomOpenAPIOperation(operation, contract) {
25
+ const operationCustoms = [];
26
+ for (const errorItem of Object.values(contract["~orpc"].errorMap)) {
27
+ const maybeExtender = errorItem ? getCustomOpenAPIOperation(errorItem) : void 0;
28
+ if (maybeExtender) {
29
+ operationCustoms.push(maybeExtender);
30
+ }
31
+ }
32
+ if (isProcedure(contract)) {
33
+ for (const middleware of contract["~orpc"].middlewares) {
34
+ const maybeExtender = getCustomOpenAPIOperation(middleware);
35
+ if (maybeExtender) {
36
+ operationCustoms.push(maybeExtender);
37
+ }
38
+ }
39
+ }
40
+ let currentOperation = operation;
41
+ for (const custom of operationCustoms) {
42
+ if (typeof custom === "function") {
43
+ currentOperation = custom(currentOperation, contract);
44
+ } else {
45
+ currentOperation = {
46
+ ...currentOperation,
47
+ ...custom
48
+ };
49
+ }
50
+ }
51
+ return currentOperation;
52
+ }
53
+
54
+ class CompositeSchemaConverter {
55
+ converters;
56
+ constructor(converters) {
57
+ this.converters = converters;
58
+ }
59
+ convert(schema, options) {
60
+ for (const converter of this.converters) {
61
+ if (converter.condition(schema, options)) {
62
+ return converter.convert(schema, options);
63
+ }
64
+ }
65
+ return [false, {}];
66
+ }
67
+ }
68
+
69
+ class OpenAPIGeneratorError extends Error {
70
+ }
71
+ class OpenAPIGenerator {
72
+ serializer;
73
+ converter;
74
+ constructor(options = {}) {
75
+ this.serializer = new OpenAPISerializer();
76
+ this.converter = new CompositeSchemaConverter(options.schemaConverters ?? []);
77
+ }
78
+ async generate(router, base) {
79
+ const doc = clone(base);
80
+ doc.openapi = "3.1.1";
81
+ const errors = [];
82
+ await resolveContractProcedures({ path: [], router }, ({ contract, path }) => {
83
+ const operationId = path.join(".");
84
+ try {
85
+ const def = contract["~orpc"];
86
+ const method = toOpenAPIMethod(fallbackContractConfig("defaultMethod", def.route.method));
87
+ const httpPath = toOpenAPIPath(def.route.path ?? toHttpPath(path));
88
+ const operationObjectRef = {
89
+ operationId,
90
+ summary: def.route.summary,
91
+ description: def.route.description,
92
+ deprecated: def.route.deprecated,
93
+ tags: def.route.tags?.map((tag) => tag)
94
+ };
95
+ this.#request(operationObjectRef, def);
96
+ this.#successResponse(operationObjectRef, def);
97
+ this.#errorResponse(operationObjectRef, def);
98
+ doc.paths ??= {};
99
+ doc.paths[httpPath] ??= {};
100
+ doc.paths[httpPath][method] = applyCustomOpenAPIOperation(operationObjectRef, contract);
101
+ } catch (e) {
102
+ if (!(e instanceof OpenAPIGeneratorError)) {
103
+ throw e;
104
+ }
105
+ errors.push(
106
+ `[OpenAPIGenerator] Error occurred while generating OpenAPI for procedure at path: ${operationId}
107
+ ${e.message}`
108
+ );
109
+ }
110
+ });
111
+ if (errors.length) {
112
+ throw new OpenAPIGeneratorError(
113
+ `Some error occurred during OpenAPI generation:
114
+
115
+ ${errors.join("\n\n")}`
116
+ );
117
+ }
118
+ return this.serializer.serialize(doc);
119
+ }
120
+ #request(ref, def) {
121
+ const method = fallbackContractConfig("defaultMethod", def.route.method);
122
+ const details = getEventIteratorSchemaDetails(def.inputSchema);
123
+ if (details) {
124
+ ref.requestBody = {
125
+ required: true,
126
+ content: toOpenAPIEventIteratorContent(
127
+ this.converter.convert(details.yields, { strategy: "input" }),
128
+ this.converter.convert(details.returns, { strategy: "input" })
129
+ )
130
+ };
131
+ return;
132
+ }
133
+ const dynamicParams = getDynamicParams(def.route.path);
134
+ const inputStructure = fallbackContractConfig("defaultInputStructure", def.route.inputStructure);
135
+ let [required, schema] = this.converter.convert(def.inputSchema, { strategy: "input" });
136
+ if (isAnySchema(schema) && !dynamicParams?.length) {
137
+ return;
138
+ }
139
+ if (inputStructure === "compact") {
140
+ if (dynamicParams?.length) {
141
+ const error2 = new OpenAPIGeneratorError(
142
+ 'When input structure is "compact", and path has dynamic params, input schema must be an object with all dynamic params as required.'
143
+ );
144
+ if (!isObjectSchema(schema)) {
145
+ throw error2;
146
+ }
147
+ const [paramsSchema, rest] = separateObjectSchema(schema, dynamicParams);
148
+ schema = rest;
149
+ required = rest.required ? rest.required.length !== 0 : false;
150
+ if (!checkParamsSchema(paramsSchema, dynamicParams)) {
151
+ throw error2;
152
+ }
153
+ ref.parameters ??= [];
154
+ ref.parameters.push(...toOpenAPIParameters(paramsSchema, "path"));
155
+ }
156
+ if (method === "GET") {
157
+ if (!isObjectSchema(schema)) {
158
+ throw new OpenAPIGeneratorError(
159
+ 'When method is "GET", input schema must satisfy: object | any | unknown'
160
+ );
161
+ }
162
+ ref.parameters ??= [];
163
+ ref.parameters.push(...toOpenAPIParameters(schema, "query"));
164
+ } else {
165
+ ref.requestBody = {
166
+ required,
167
+ content: toOpenAPIContent(schema)
168
+ };
169
+ }
170
+ return;
171
+ }
172
+ const error = new OpenAPIGeneratorError(
173
+ 'When input structure is "detailed", input schema must satisfy: { params?: Record<string, unknown>, query?: Record<string, unknown>, headers?: Record<string, unknown>, body?: unknown }'
174
+ );
175
+ if (!isObjectSchema(schema)) {
176
+ throw error;
177
+ }
178
+ if (dynamicParams?.length && (schema.properties?.params === void 0 || !isObjectSchema(schema.properties.params) || !checkParamsSchema(schema.properties.params, dynamicParams))) {
179
+ throw new OpenAPIGeneratorError(
180
+ 'When input structure is "detailed" and path has dynamic params, the "params" schema must be an object with all dynamic params as required.'
181
+ );
182
+ }
183
+ for (const from of ["params", "query", "headers"]) {
184
+ const fromSchema = schema.properties?.[from];
185
+ if (fromSchema !== void 0) {
186
+ if (!isObjectSchema(fromSchema)) {
187
+ throw error;
188
+ }
189
+ const parameterIn = from === "params" ? "path" : from === "headers" ? "header" : "query";
190
+ ref.parameters ??= [];
191
+ ref.parameters.push(...toOpenAPIParameters(fromSchema, parameterIn));
192
+ }
193
+ }
194
+ if (schema.properties?.body !== void 0) {
195
+ ref.requestBody = {
196
+ required: schema.required?.includes("body"),
197
+ content: toOpenAPIContent(schema.properties.body)
198
+ };
199
+ }
200
+ }
201
+ #successResponse(ref, def) {
202
+ const outputSchema = def.outputSchema;
203
+ const status = fallbackContractConfig("defaultSuccessStatus", def.route.successStatus);
204
+ const description = fallbackContractConfig("defaultSuccessDescription", def.route?.successDescription);
205
+ const eventIteratorSchemaDetails = getEventIteratorSchemaDetails(outputSchema);
206
+ const outputStructure = fallbackContractConfig("defaultOutputStructure", def.route.outputStructure);
207
+ if (eventIteratorSchemaDetails) {
208
+ ref.responses ??= {};
209
+ ref.responses[status] = {
210
+ description,
211
+ content: toOpenAPIEventIteratorContent(
212
+ this.converter.convert(eventIteratorSchemaDetails.yields, { strategy: "output" }),
213
+ this.converter.convert(eventIteratorSchemaDetails.returns, { strategy: "output" })
214
+ )
215
+ };
216
+ return;
217
+ }
218
+ const [_, json] = this.converter.convert(outputSchema, { strategy: "output" });
219
+ ref.responses ??= {};
220
+ ref.responses[status] = {
221
+ description
222
+ };
223
+ if (outputStructure === "compact") {
224
+ ref.responses[status].content = toOpenAPIContent(json);
225
+ return;
226
+ }
227
+ const error = new OpenAPIGeneratorError(
228
+ 'When output structure is "detailed", output schema must satisfy: { headers?: Record<string, unknown>, body?: unknown }'
229
+ );
230
+ if (!isObjectSchema(json)) {
231
+ throw error;
232
+ }
233
+ if (json.properties?.headers !== void 0) {
234
+ if (!isObjectSchema(json.properties.headers)) {
235
+ throw error;
236
+ }
237
+ for (const key in json.properties.headers.properties) {
238
+ ref.responses[status].headers ??= {};
239
+ ref.responses[status].headers[key] = {
240
+ schema: toOpenAPISchema(json.properties.headers.properties[key]),
241
+ required: json.properties.headers.required?.includes(key)
242
+ };
243
+ }
244
+ }
245
+ if (json.properties?.body !== void 0) {
246
+ ref.responses[status].content = toOpenAPIContent(json.properties.body);
247
+ }
248
+ }
249
+ #errorResponse(ref, def) {
250
+ const errorMap = def.errorMap;
251
+ const errors = {};
252
+ for (const code in errorMap) {
253
+ const config = errorMap[code];
254
+ if (!config) {
255
+ continue;
256
+ }
257
+ const status = fallbackORPCErrorStatus(code, config.status);
258
+ const message = fallbackORPCErrorMessage(code, config.message);
259
+ const [dataRequired, dataSchema] = this.converter.convert(config.data, { strategy: "output" });
260
+ errors[status] ??= [];
261
+ errors[status].push({
262
+ type: "object",
263
+ properties: {
264
+ defined: { const: true },
265
+ code: { const: code },
266
+ status: { const: status },
267
+ message: { type: "string", default: message },
268
+ data: dataSchema
269
+ },
270
+ required: dataRequired ? ["defined", "code", "status", "message", "data"] : ["defined", "code", "status", "message"]
271
+ });
272
+ }
273
+ ref.responses ??= {};
274
+ for (const status in errors) {
275
+ const schemas = errors[status];
276
+ ref.responses[status] = {
277
+ description: status,
278
+ content: toOpenAPIContent({
279
+ oneOf: [
280
+ ...schemas,
281
+ {
282
+ type: "object",
283
+ properties: {
284
+ defined: { const: false },
285
+ code: { type: "string" },
286
+ status: { type: "number" },
287
+ message: { type: "string" },
288
+ data: {}
289
+ },
290
+ required: ["defined", "code", "status", "message"]
291
+ }
292
+ ]
293
+ })
294
+ };
295
+ }
296
+ }
297
+ }
298
+
299
+ const oo = {
300
+ spec: customOpenAPIOperation
301
+ };
302
+
303
+ export { CompositeSchemaConverter, OpenAPIGenerator, applyCustomOpenAPIOperation, checkParamsSchema, customOpenAPIOperation, getCustomOpenAPIOperation, getDynamicParams, isAnySchema, isObjectSchema, oo, separateObjectSchema, toOpenAPIContent, toOpenAPIEventIteratorContent, toOpenAPIMethod, toOpenAPIParameters, toOpenAPIPath, toOpenAPISchema };
@@ -1,15 +1,12 @@
1
- import {
2
- standardizeHTTPPath
3
- } from "./chunk-XGHV4TH3.js";
1
+ import { fallbackContractConfig } from '@orpc/contract';
2
+ import { isObject } from '@orpc/shared';
3
+ import { traverseContractProcedures, toHttpPath, isProcedure, getLazyMeta, unlazy, getRouter, createContractedProcedure } from '@orpc/server';
4
+ import { createRouter, addRoute, findRoute } from 'rou3';
5
+ import { s as standardizeHTTPPath } from './openapi.DZzpQAb-.mjs';
4
6
 
5
- // src/adapters/standard/openapi-codec.ts
6
- import { OpenAPISerializer } from "@orpc/client/openapi";
7
- import { fallbackContractConfig } from "@orpc/contract";
8
- import { isObject } from "@orpc/shared";
9
- var OpenAPICodec = class {
10
- serializer;
11
- constructor(options) {
12
- this.serializer = options?.serializer ?? new OpenAPISerializer();
7
+ class OpenAPICodec {
8
+ constructor(serializer) {
9
+ this.serializer = serializer;
13
10
  }
14
11
  async decode(request, params, procedure) {
15
12
  const inputStructure = fallbackContractConfig("defaultInputStructure", procedure["~orpc"].route.inputStructure);
@@ -71,29 +68,22 @@ var OpenAPICodec = class {
71
68
  body: this.serializer.serialize(error.toJSON())
72
69
  };
73
70
  }
74
- };
71
+ }
72
+
73
+ function toRou3Pattern(path) {
74
+ return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/**:$1").replace(/\/\{([^}]+)\}/g, "/:$1");
75
+ }
76
+ function decodeParams(params) {
77
+ return Object.fromEntries(Object.entries(params).map(([key, value]) => [key, decodeURIComponent(value)]));
78
+ }
75
79
 
76
- // src/adapters/standard/openapi-matcher.ts
77
- import { fallbackContractConfig as fallbackContractConfig2 } from "@orpc/contract";
78
- import { convertPathToHttpPath, createContractedProcedure, eachContractProcedure, getLazyRouterPrefix, getRouterChild, isProcedure, unlazy } from "@orpc/server";
79
- import { addRoute, createRouter, findRoute } from "rou3";
80
- var OpenAPIMatcher = class {
80
+ class OpenAPIMatcher {
81
81
  tree = createRouter();
82
- ignoreUndefinedMethod;
83
- constructor(options) {
84
- this.ignoreUndefinedMethod = options?.ignoreUndefinedMethod ?? false;
85
- }
86
82
  pendingRouters = [];
87
83
  init(router, path = []) {
88
- const laziedOptions = eachContractProcedure({
89
- router,
90
- path
91
- }, ({ path: path2, contract }) => {
92
- if (!contract["~orpc"].route.method && this.ignoreUndefinedMethod) {
93
- return;
94
- }
95
- const method = fallbackContractConfig2("defaultMethod", contract["~orpc"].route.method);
96
- const httpPath = contract["~orpc"].route.path ? toRou3Pattern(contract["~orpc"].route.path) : convertPathToHttpPath(path2);
84
+ const laziedOptions = traverseContractProcedures({ router, path }, ({ path: path2, contract }) => {
85
+ const method = fallbackContractConfig("defaultMethod", contract["~orpc"].route.method);
86
+ const httpPath = toRou3Pattern(contract["~orpc"].route.path ?? toHttpPath(path2));
97
87
  if (isProcedure(contract)) {
98
88
  addRoute(this.tree, method, httpPath, {
99
89
  path: path2,
@@ -113,8 +103,8 @@ var OpenAPIMatcher = class {
113
103
  });
114
104
  this.pendingRouters.push(...laziedOptions.map((option) => ({
115
105
  ...option,
116
- httpPathPrefix: convertPathToHttpPath(option.path),
117
- laziedPrefix: getLazyRouterPrefix(option.lazied)
106
+ httpPathPrefix: toHttpPath(option.path),
107
+ laziedPrefix: getLazyMeta(option.router).prefix
118
108
  })));
119
109
  }
120
110
  async match(method, pathname) {
@@ -122,7 +112,7 @@ var OpenAPIMatcher = class {
122
112
  const newPendingRouters = [];
123
113
  for (const pendingRouter of this.pendingRouters) {
124
114
  if (!pendingRouter.laziedPrefix || pathname.startsWith(pendingRouter.laziedPrefix) || pathname.startsWith(pendingRouter.httpPathPrefix)) {
125
- const { default: router } = await unlazy(pendingRouter.lazied);
115
+ const { default: router } = await unlazy(pendingRouter.router);
126
116
  this.init(router, pendingRouter.path);
127
117
  } else {
128
118
  newPendingRouters.push(pendingRouter);
@@ -135,14 +125,14 @@ var OpenAPIMatcher = class {
135
125
  return void 0;
136
126
  }
137
127
  if (!match.data.procedure) {
138
- const { default: maybeProcedure } = await unlazy(getRouterChild(match.data.router, ...match.data.path));
128
+ const { default: maybeProcedure } = await unlazy(getRouter(match.data.router, match.data.path));
139
129
  if (!isProcedure(maybeProcedure)) {
140
130
  throw new Error(`
141
- [Contract-First] Missing or invalid implementation for procedure at path: ${convertPathToHttpPath(match.data.path)}.
131
+ [Contract-First] Missing or invalid implementation for procedure at path: ${toHttpPath(match.data.path)}.
142
132
  Ensure that the procedure is correctly defined and matches the expected contract.
143
133
  `);
144
134
  }
145
- match.data.procedure = createContractedProcedure(match.data.contract, maybeProcedure);
135
+ match.data.procedure = createContractedProcedure(maybeProcedure, match.data.contract);
146
136
  }
147
137
  return {
148
138
  path: match.data.path,
@@ -150,16 +140,6 @@ var OpenAPIMatcher = class {
150
140
  params: match.params ? decodeParams(match.params) : void 0
151
141
  };
152
142
  }
153
- };
154
- function toRou3Pattern(path) {
155
- return standardizeHTTPPath(path).replace(/\{\+([^}]+)\}/g, "**:$1").replace(/\{([^}]+)\}/g, ":$1");
156
- }
157
- function decodeParams(params) {
158
- return Object.fromEntries(Object.entries(params).map(([key, value]) => [key, decodeURIComponent(value)]));
159
143
  }
160
144
 
161
- export {
162
- OpenAPICodec,
163
- OpenAPIMatcher
164
- };
165
- //# sourceMappingURL=chunk-LPBZEW4B.js.map
145
+ export { OpenAPICodec as O, OpenAPIMatcher as a, decodeParams as d, toRou3Pattern as t };
@@ -0,0 +1,31 @@
1
+ import { OpenAPISerializer } from '@orpc/openapi-client/standard';
2
+ import { StandardHandler } from '@orpc/server/standard';
3
+ import { toStandardLazyRequest, toFetchResponse } from '@orpc/standard-server-fetch';
4
+ import { a as OpenAPIMatcher, O as OpenAPICodec } from './openapi.CJTe38Ya.mjs';
5
+ import '@orpc/shared';
6
+ import 'json-schema-typed/draft-2020-12';
7
+
8
+ class OpenAPIHandler {
9
+ standardHandler;
10
+ constructor(router, options = {}) {
11
+ const serializer = new OpenAPISerializer();
12
+ const matcher = new OpenAPIMatcher();
13
+ const codec = new OpenAPICodec(serializer);
14
+ this.standardHandler = new StandardHandler(router, matcher, codec, options);
15
+ }
16
+ async handle(request, ...[
17
+ options = {}
18
+ ]) {
19
+ const standardRequest = toStandardLazyRequest(request);
20
+ const result = await this.standardHandler.handle(standardRequest, options);
21
+ if (!result.matched) {
22
+ return result;
23
+ }
24
+ return {
25
+ matched: true,
26
+ response: toFetchResponse(result.response, options)
27
+ };
28
+ }
29
+ }
30
+
31
+ export { OpenAPIHandler as O };
@@ -0,0 +1,231 @@
1
+ import { isObject, findDeepMatches } from '@orpc/shared';
2
+ import 'json-schema-typed/draft-2020-12';
3
+
4
+ const LOGIC_KEYWORDS = [
5
+ "$dynamicRef",
6
+ "$ref",
7
+ "additionalItems",
8
+ "additionalProperties",
9
+ "allOf",
10
+ "anyOf",
11
+ "const",
12
+ "contains",
13
+ "contentEncoding",
14
+ "contentMediaType",
15
+ "contentSchema",
16
+ "dependencies",
17
+ "dependentRequired",
18
+ "dependentSchemas",
19
+ "else",
20
+ "enum",
21
+ "exclusiveMaximum",
22
+ "exclusiveMinimum",
23
+ "format",
24
+ "if",
25
+ "items",
26
+ "maxContains",
27
+ "maximum",
28
+ "maxItems",
29
+ "maxLength",
30
+ "maxProperties",
31
+ "minContains",
32
+ "minimum",
33
+ "minItems",
34
+ "minLength",
35
+ "minProperties",
36
+ "multipleOf",
37
+ "not",
38
+ "oneOf",
39
+ "pattern",
40
+ "patternProperties",
41
+ "prefixItems",
42
+ "properties",
43
+ "propertyNames",
44
+ "required",
45
+ "then",
46
+ "type",
47
+ "unevaluatedItems",
48
+ "unevaluatedProperties",
49
+ "uniqueItems"
50
+ ];
51
+
52
+ function isFileSchema(schema) {
53
+ return isObject(schema) && schema.type === "string" && typeof schema.contentMediaType === "string";
54
+ }
55
+ function isObjectSchema(schema) {
56
+ return isObject(schema) && schema.type === "object";
57
+ }
58
+ function isAnySchema(schema) {
59
+ if (schema === true) {
60
+ return true;
61
+ }
62
+ if (Object.keys(schema).every((k) => !LOGIC_KEYWORDS.includes(k))) {
63
+ return true;
64
+ }
65
+ return false;
66
+ }
67
+ function separateObjectSchema(schema, separatedProperties) {
68
+ if (Object.keys(schema).some((k) => k !== "type" && k !== "properties" && k !== "required" && LOGIC_KEYWORDS.includes(k))) {
69
+ return [{ type: "object" }, schema];
70
+ }
71
+ const matched = { ...schema };
72
+ const rest = { ...schema };
73
+ matched.properties = schema.properties && Object.entries(schema.properties).filter(([key]) => separatedProperties.includes(key)).reduce((acc, [key, value]) => {
74
+ acc[key] = value;
75
+ return acc;
76
+ }, {});
77
+ matched.required = schema.required?.filter((key) => separatedProperties.includes(key));
78
+ matched.examples = schema.examples?.map((example) => {
79
+ if (!isObject(example)) {
80
+ return example;
81
+ }
82
+ return Object.entries(example).reduce((acc, [key, value]) => {
83
+ if (separatedProperties.includes(key)) {
84
+ acc[key] = value;
85
+ }
86
+ return acc;
87
+ }, {});
88
+ });
89
+ rest.properties = schema.properties && Object.entries(schema.properties).filter(([key]) => !separatedProperties.includes(key)).reduce((acc, [key, value]) => {
90
+ acc[key] = value;
91
+ return acc;
92
+ }, {});
93
+ rest.required = schema.required?.filter((key) => !separatedProperties.includes(key));
94
+ rest.examples = schema.examples?.map((example) => {
95
+ if (!isObject(example)) {
96
+ return example;
97
+ }
98
+ return Object.entries(example).reduce((acc, [key, value]) => {
99
+ if (!separatedProperties.includes(key)) {
100
+ acc[key] = value;
101
+ }
102
+ return acc;
103
+ }, {});
104
+ });
105
+ return [matched, rest];
106
+ }
107
+ function filterSchemaBranches(schema, check, matches = []) {
108
+ if (check(schema)) {
109
+ matches.push(schema);
110
+ return [matches, void 0];
111
+ }
112
+ if (isObject(schema)) {
113
+ for (const keyword of ["anyOf", "oneOf"]) {
114
+ if (schema[keyword] && Object.keys(schema).every(
115
+ (k) => k === keyword || !LOGIC_KEYWORDS.includes(k)
116
+ )) {
117
+ const rest = schema[keyword].map((s) => filterSchemaBranches(s, check, matches)[1]).filter((v) => !!v);
118
+ if (rest.length === 1 && typeof rest[0] === "object") {
119
+ return [matches, { ...schema, [keyword]: void 0, ...rest[0] }];
120
+ }
121
+ return [matches, { ...schema, [keyword]: rest }];
122
+ }
123
+ }
124
+ }
125
+ return [matches, schema];
126
+ }
127
+
128
+ function standardizeHTTPPath(path) {
129
+ return `/${path.replace(/\/{2,}/g, "/").replace(/^\/|\/$/g, "")}`;
130
+ }
131
+ function toOpenAPIPath(path) {
132
+ return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/{$1}");
133
+ }
134
+ function toOpenAPIMethod(method) {
135
+ return method.toLocaleLowerCase();
136
+ }
137
+ function getDynamicParams(path) {
138
+ return path ? standardizeHTTPPath(path).match(/\/\{([^}]+)\}/g)?.map((v) => v.match(/\{\+?([^}]+)\}/)[1]) : void 0;
139
+ }
140
+ function toOpenAPIContent(schema) {
141
+ const content = {};
142
+ const [matches, restSchema] = filterSchemaBranches(schema, isFileSchema);
143
+ for (const file of matches) {
144
+ content[file.contentMediaType] = {
145
+ schema: toOpenAPISchema(file)
146
+ };
147
+ }
148
+ if (restSchema !== void 0) {
149
+ content["application/json"] = {
150
+ schema: toOpenAPISchema(restSchema)
151
+ };
152
+ const isStillHasFileSchema = findDeepMatches((v) => isObject(v) && isFileSchema(v), restSchema).values.length > 0;
153
+ if (isStillHasFileSchema) {
154
+ content["multipart/form-data"] = {
155
+ schema: toOpenAPISchema(restSchema)
156
+ };
157
+ }
158
+ }
159
+ return content;
160
+ }
161
+ function toOpenAPIEventIteratorContent([yieldsRequired, yieldsSchema], [returnsRequired, returnsSchema]) {
162
+ return {
163
+ "text/event-stream": {
164
+ schema: toOpenAPISchema({
165
+ oneOf: [
166
+ {
167
+ type: "object",
168
+ properties: {
169
+ event: { const: "message" },
170
+ data: yieldsSchema,
171
+ id: { type: "string" },
172
+ retry: { type: "number" }
173
+ },
174
+ required: yieldsRequired ? ["event", "data"] : ["event"]
175
+ },
176
+ {
177
+ type: "object",
178
+ properties: {
179
+ event: { const: "done" },
180
+ data: returnsSchema,
181
+ id: { type: "string" },
182
+ retry: { type: "number" }
183
+ },
184
+ required: returnsRequired ? ["event", "data"] : ["event"]
185
+ },
186
+ {
187
+ type: "object",
188
+ properties: {
189
+ event: { const: "error" },
190
+ data: {},
191
+ id: { type: "string" },
192
+ retry: { type: "number" }
193
+ },
194
+ required: ["event"]
195
+ }
196
+ ]
197
+ })
198
+ }
199
+ };
200
+ }
201
+ function toOpenAPIParameters(schema, parameterIn) {
202
+ const parameters = [];
203
+ for (const key in schema.properties) {
204
+ const keySchema = schema.properties[key];
205
+ parameters.push({
206
+ name: key,
207
+ in: parameterIn,
208
+ required: schema.required?.includes(key),
209
+ style: parameterIn === "query" ? "deepObject" : void 0,
210
+ explode: parameterIn === "query" ? true : void 0,
211
+ schema: toOpenAPISchema(keySchema)
212
+ });
213
+ }
214
+ return parameters;
215
+ }
216
+ function checkParamsSchema(schema, params) {
217
+ const properties = Object.keys(schema.properties ?? {});
218
+ const required = schema.required ?? [];
219
+ if (properties.length !== params.length || properties.some((v) => !params.includes(v))) {
220
+ return false;
221
+ }
222
+ if (required.length !== params.length || required.some((v) => !params.includes(v))) {
223
+ return false;
224
+ }
225
+ return true;
226
+ }
227
+ function toOpenAPISchema(schema) {
228
+ return schema === true ? {} : schema === false ? { not: {} } : schema;
229
+ }
230
+
231
+ export { LOGIC_KEYWORDS as L, toOpenAPIPath as a, toOpenAPIEventIteratorContent as b, isObjectSchema as c, separateObjectSchema as d, checkParamsSchema as e, toOpenAPIParameters as f, getDynamicParams as g, toOpenAPIContent as h, isAnySchema as i, toOpenAPISchema as j, isFileSchema as k, filterSchemaBranches as l, standardizeHTTPPath as s, toOpenAPIMethod as t };