@orpc/openapi 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/adapters/aws-lambda/index.d.ts +3 -0
- package/dist/adapters/aws-lambda/index.js +1 -0
- package/dist/adapters/aws-lambda/openapi-handler.d.ts +17 -0
- package/dist/adapters/aws-lambda/openapi-handler.js +20 -0
- package/dist/adapters/fastify/index.d.ts +2 -0
- package/dist/adapters/fastify/index.js +1 -0
- package/dist/adapters/fastify/openapi-handler.d.ts +14 -0
- package/dist/adapters/fastify/openapi-handler.js +17 -0
- package/dist/adapters/fetch/index.d.ts +3 -27
- package/dist/adapters/fetch/index.js +2 -0
- package/dist/adapters/fetch/openapi-handler.d.ts +14 -0
- package/dist/adapters/fetch/openapi-handler.js +17 -0
- package/dist/adapters/fetch/openapi-link.d.ts +20 -0
- package/dist/adapters/fetch/openapi-link.js +22 -0
- package/dist/adapters/node/index.d.ts +2 -18
- package/dist/adapters/node/index.js +1 -0
- package/dist/adapters/node/openapi-handler.d.ts +14 -0
- package/dist/adapters/node/openapi-handler.js +17 -0
- package/dist/adapters/standard/index.d.ts +4 -50
- package/dist/adapters/standard/index.js +3 -0
- package/dist/adapters/standard/openapi-handler-codec.d.ts +61 -0
- package/dist/adapters/standard/openapi-handler-codec.js +158 -0
- package/dist/adapters/standard/openapi-link-codec.d.ts +58 -0
- package/dist/adapters/standard/openapi-link-codec.js +290 -0
- package/dist/adapters/standard/openapi-matcher.d.ts +29 -0
- package/dist/adapters/standard/openapi-matcher.js +78 -0
- package/dist/adapters/standard/utils.js +31 -0
- package/dist/bracket-notation.d.ts +26 -0
- package/dist/bracket-notation.js +135 -0
- package/dist/client-factory.d.ts +24 -0
- package/dist/client-factory.js +15 -0
- package/dist/constants.d.ts +1 -0
- package/dist/constants.js +5 -0
- package/dist/extensions/route.d.ts +36 -42
- package/dist/extensions/route.js +13 -0
- package/dist/helpers/{index.d.mts → form-data.d.ts} +11 -5
- package/dist/helpers/form-data.js +78 -0
- package/dist/helpers/index.d.ts +2 -51
- package/dist/helpers/index.js +1 -0
- package/dist/index.d.ts +15 -120
- package/dist/index.js +11 -0
- package/dist/meta.d.ts +327 -0
- package/dist/meta.js +66 -0
- package/dist/openapi-generator-components.d.ts +2 -0
- package/dist/openapi-generator-components.js +318 -0
- package/dist/openapi-generator-operation.d.ts +13 -0
- package/dist/openapi-generator-operation.js +459 -0
- package/dist/openapi-generator.d.ts +87 -0
- package/dist/openapi-generator.js +119 -0
- package/dist/openapi-json-serializer.d.ts +79 -0
- package/dist/openapi-json-serializer.js +221 -0
- package/dist/openapi-serializer.d.ts +42 -0
- package/dist/openapi-serializer.js +69 -0
- package/dist/plugins/index.d.ts +2 -90
- package/dist/plugins/index.js +1 -0
- package/dist/plugins/openapi-reference.d.ts +112 -0
- package/dist/plugins/openapi-reference.js +164 -0
- package/dist/router-utils.d.ts +18 -0
- package/dist/router-utils.js +32 -0
- package/dist/types.d.ts +28 -0
- package/dist/utils.d.ts +9 -0
- package/dist/utils.js +44 -0
- package/package.json +87 -49
- package/dist/adapters/fetch/index.d.mts +0 -27
- package/dist/adapters/fetch/index.mjs +0 -34
- package/dist/adapters/node/index.d.mts +0 -18
- package/dist/adapters/node/index.mjs +0 -21
- package/dist/adapters/standard/index.d.mts +0 -50
- package/dist/adapters/standard/index.mjs +0 -12
- package/dist/extensions/route.d.mts +0 -43
- package/dist/extensions/route.mjs +0 -14
- package/dist/helpers/index.mjs +0 -39
- package/dist/index.d.mts +0 -120
- package/dist/index.mjs +0 -930
- package/dist/plugins/index.d.mts +0 -90
- package/dist/plugins/index.mjs +0 -162
- package/dist/shared/openapi.7vgmPxca.d.ts +0 -82
- package/dist/shared/openapi.B2SK0ZAr.mjs +0 -359
- package/dist/shared/openapi.B9PQzqBn.mjs +0 -49
- package/dist/shared/openapi.BQzzr4-4.d.ts +0 -299
- package/dist/shared/openapi.BcEtAxQj.d.mts +0 -299
- package/dist/shared/openapi.Bt87OzTt.mjs +0 -131
- package/dist/shared/openapi.C7m7NAmH.d.mts +0 -142
- package/dist/shared/openapi.C7m7NAmH.d.ts +0 -142
- package/dist/shared/openapi.CTlpLuKN.mjs +0 -318
- package/dist/shared/openapi.CX6Ri5dP.d.mts +0 -82
- package/dist/shared/openapi.CYgMBSUF.d.mts +0 -18
- package/dist/shared/openapi.CYgMBSUF.d.ts +0 -18
- package/dist/shared/openapi.DmAa7YPO.mjs +0 -275
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
import "./constants.js";
|
|
2
|
+
import { isBodylessMethod } from "./utils.js";
|
|
3
|
+
import { getOwn, stringifyJSON, value } from "@orpc/shared";
|
|
4
|
+
import { getAsyncIteratorObjectSchemasDetails } from "@orpc/contract";
|
|
5
|
+
import { combineJsonObjectSchemaEntries, combineJsonSchemasWithComposition, containsJsonFileSchema, deduplicateJsonSchemas, doesJsonSchemaAcceptEmptyCollection, extractJsonObjectSchemaAdditionalProperties, extractJsonObjectSchemaEntries, flattenJsonUnionSchema, isJsonFileSchema, isJsonPrimitiveSchema, isUnconstrainedSchema, matchArrayableJsonSchema, resolveJsonSchemaLocalPointer, resolveJsonSchemaRootLocalRef } from "@orpc/json-schema";
|
|
6
|
+
import { DEFAULT_ERROR_STATUS, DEFAULT_SUCCESS_STATUS } from "@orpc/server";
|
|
7
|
+
// src/openapi-generator-operation.ts
|
|
8
|
+
var OpenAPIGeneratorError = class extends TypeError {};
|
|
9
|
+
function toOpenAPIPath(path, dynamicPathParams) {
|
|
10
|
+
if (!dynamicPathParams?.length) return path;
|
|
11
|
+
let normalized = "";
|
|
12
|
+
let currentIndex = 0;
|
|
13
|
+
for (const param of dynamicPathParams) {
|
|
14
|
+
normalized += path.slice(currentIndex, param.startIndex);
|
|
15
|
+
normalized += `{${param.parameterName}}`;
|
|
16
|
+
currentIndex = param.startIndex + param.segment.length;
|
|
17
|
+
}
|
|
18
|
+
normalized += path.slice(currentIndex);
|
|
19
|
+
return normalized;
|
|
20
|
+
}
|
|
21
|
+
function buildRequest(ctx, operation, def, meta, dynamicPathParams) {
|
|
22
|
+
const method = meta?.method ?? "POST";
|
|
23
|
+
const inputStructure = meta?.inputStructure ?? "compact";
|
|
24
|
+
const dynamicParams = dynamicPathParams?.map((v) => v.parameterName);
|
|
25
|
+
if (inputStructure === "compact") {
|
|
26
|
+
const iteratorDetails = getAsyncIteratorObjectSchemasDetails(def.inputSchemas);
|
|
27
|
+
if (iteratorDetails) {
|
|
28
|
+
renderPathParameters(ctx, operation, dynamicParams, void 0, void 0);
|
|
29
|
+
operation.requestBody = {
|
|
30
|
+
required: true,
|
|
31
|
+
content: toAsyncIteratorObjectContent(ctx, "input", ctx.convertSchemas(iteratorDetails.yieldSchemas, "input"), ctx.convertSchemas(iteratorDetails.returnSchemas, "input"))
|
|
32
|
+
};
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const [schema, optional] = ctx.convertSchemas(def.inputSchemas, "input");
|
|
37
|
+
if (isUnconstrainedSchema(schema) && !dynamicParams?.length) return;
|
|
38
|
+
const parts = inputStructure === "compact" ? extractCompactRequestParts(schema, optional, method, dynamicParams) : extractDetailedRequestParts(schema);
|
|
39
|
+
renderPathParameters(ctx, operation, dynamicParams, parts.paramsEntries, meta?.paramsStyles);
|
|
40
|
+
renderQueryParameters(ctx, operation, parts.queryEntries, meta?.queryStyles);
|
|
41
|
+
renderFreeFormQueryParameter(ctx, operation, parts);
|
|
42
|
+
renderHeaderParameters(ctx, operation, parts.headersEntries);
|
|
43
|
+
const content = parts.bodySchema === void 0 ? {} : toBodyContent(ctx, "input", parts.bodySchema);
|
|
44
|
+
if (Object.keys(content).length > 0) operation.requestBody = {
|
|
45
|
+
required: parts.bodyOptional ? void 0 : true,
|
|
46
|
+
content
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
function extractCompactRequestParts(schema, optional, method, dynamicParams) {
|
|
50
|
+
const entries = extractJsonObjectSchemaEntries(schema);
|
|
51
|
+
if (!entries && isBodylessMethod(method)) throw new OpenAPIGeneratorError(`method is ${method} but the input schema is not an object.\n ${method} sends every input field as a query parameter, so the input must be an object schema.\n Fix: make the input an object, or use a method with a request body (POST, PUT, PATCH, DELETE).`);
|
|
52
|
+
const paramsEntries = entries?.filter(([name]) => dynamicParams?.includes(name));
|
|
53
|
+
const restEntries = entries?.filter(([name]) => !dynamicParams?.includes(name));
|
|
54
|
+
const hasBody = !isBodylessMethod(method);
|
|
55
|
+
const additionalProperties = hasBody && dynamicParams?.length ? extractJsonObjectSchemaAdditionalProperties(schema) : void 0;
|
|
56
|
+
const bodySchema = !hasBody ? void 0 : !dynamicParams?.length ? schema : restEntries?.length || additionalProperties !== false ? combineJsonObjectSchemaEntries(restEntries ?? [], additionalProperties) : void 0;
|
|
57
|
+
return {
|
|
58
|
+
paramsEntries,
|
|
59
|
+
queryEntries: isBodylessMethod(method) ? restEntries : void 0,
|
|
60
|
+
querySchema: isBodylessMethod(method) ? schema : void 0,
|
|
61
|
+
headersEntries: void 0,
|
|
62
|
+
bodySchema,
|
|
63
|
+
bodyOptional: !dynamicParams?.length ? optional : restEntries?.every(([, , optional]) => optional)
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
function extractDetailedRequestParts(schema) {
|
|
67
|
+
const entries = extractJsonObjectSchemaEntries(schema);
|
|
68
|
+
if (!entries) throw new OpenAPIGeneratorError("inputStructure is \"detailed\" but the input schema is not an object.\n Expected an object shaped like: { params?: object, query?: object, headers?: object, body?: unknown }");
|
|
69
|
+
const section = (name) => entries.find(([entryName]) => entryName === name);
|
|
70
|
+
return {
|
|
71
|
+
paramsEntries: extractJsonObjectSchemaEntries(section("params")?.[1] ?? false),
|
|
72
|
+
queryEntries: extractJsonObjectSchemaEntries(section("query")?.[1] ?? false),
|
|
73
|
+
querySchema: section("query")?.[1],
|
|
74
|
+
headersEntries: extractJsonObjectSchemaEntries(section("headers")?.[1] ?? false),
|
|
75
|
+
bodySchema: section("body")?.[1],
|
|
76
|
+
bodyOptional: section("body")?.[2]
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
function renderPathParameters(ctx, operation, dynamicParams, paramsEntries, paramsStyles) {
|
|
80
|
+
if (!dynamicParams?.length) return;
|
|
81
|
+
if (!paramsEntries) throw new OpenAPIGeneratorError(`the route declares path params (${dynamicParams.map((p) => `{${p}}`).join(", ")}) but there is no object schema to source them from.\n compact mode: the input schema must be an object containing each param.\n detailed mode: the input's "params" section must be an object containing each param.`);
|
|
82
|
+
for (const name of dynamicParams) {
|
|
83
|
+
const entry = paramsEntries.find(([entryName]) => entryName === name);
|
|
84
|
+
if (!entry) throw new OpenAPIGeneratorError(`dynamic param "{${name}}" is missing from the input schema.\n Route params: ${dynamicParams.map((p) => `{${p}}`).join(", ")}\n Schema keys: ${paramsEntries.map(([n]) => n).join(", ") || "(none)"}`);
|
|
85
|
+
if (entry[2]) throw new OpenAPIGeneratorError(`dynamic param "${name}" is optional in the input schema.\n OpenAPI requires path params to be required. Make "${name}" required.`);
|
|
86
|
+
const style = paramsStyles?.[name];
|
|
87
|
+
const parameter = {
|
|
88
|
+
in: "path",
|
|
89
|
+
required: true,
|
|
90
|
+
name,
|
|
91
|
+
schema: ctx.registry.toOpenAPISchema(entry[1], "input")
|
|
92
|
+
};
|
|
93
|
+
if (style === "comma-delimited-array" || style === "comma-delimited-object") {
|
|
94
|
+
parameter.style = "simple";
|
|
95
|
+
parameter.explode = false;
|
|
96
|
+
}
|
|
97
|
+
operation.parameters ??= [];
|
|
98
|
+
operation.parameters.push(parameter);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function renderQueryParameters(ctx, operation, queryEntries, queryStyles) {
|
|
102
|
+
for (const [name, schema, optional] of queryEntries ?? []) {
|
|
103
|
+
const style = queryStyles?.[name];
|
|
104
|
+
const parameter = {
|
|
105
|
+
in: "query",
|
|
106
|
+
name,
|
|
107
|
+
schema: ctx.registry.toOpenAPISchema(schema, "input"),
|
|
108
|
+
allowEmptyValue: true,
|
|
109
|
+
allowReserved: true
|
|
110
|
+
};
|
|
111
|
+
const collectionKind = style === void 0 || style === "primitive" || style === "json" ? void 0 : style.endsWith("object") ? "object" : "array";
|
|
112
|
+
if (collectionKind ? !doesJsonSchemaAcceptEmptyCollection(schema, collectionKind) : !optional) parameter.required = true;
|
|
113
|
+
if (style === "comma-delimited-array" || style === "comma-delimited-object") parameter.explode = false;
|
|
114
|
+
else if (style === "pipe-delimited-array" || style === "pipe-delimited-object") parameter.style = "pipeDelimited";
|
|
115
|
+
else if (style === "space-delimited-array" || style === "space-delimited-object") parameter.style = "spaceDelimited";
|
|
116
|
+
else if (style === "json") {
|
|
117
|
+
parameter.content = { "application/json": { schema: parameter.schema } };
|
|
118
|
+
delete parameter.schema;
|
|
119
|
+
delete parameter.allowReserved;
|
|
120
|
+
} else if (style === void 0) {
|
|
121
|
+
if (!flattenJsonUnionSchema(schema).every(isPrimitive)) {
|
|
122
|
+
const arrayable = matchArrayableJsonSchema(schema);
|
|
123
|
+
if (!arrayable || !flattenJsonUnionSchema(arrayable[0]).every(isPrimitive)) {
|
|
124
|
+
parameter.style = "deepObject";
|
|
125
|
+
parameter.explode = true;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
operation.parameters ??= [];
|
|
130
|
+
operation.parameters.push(parameter);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* The keys of a query other than its fields, like those of a record, as an object of form style,
|
|
135
|
+
* unless their values are not primitives, which are sent in bracket notation (`b[0]=1`) no style
|
|
136
|
+
* describes, or the query constrains them in ways the parameter would lose (`propertyNames`).
|
|
137
|
+
*/
|
|
138
|
+
function renderFreeFormQueryParameter(ctx, operation, { querySchema, queryEntries }) {
|
|
139
|
+
if (querySchema === void 0) return;
|
|
140
|
+
const query = resolveJsonSchemaRootLocalRef(querySchema);
|
|
141
|
+
const additionalProperties = extractJsonObjectSchemaAdditionalProperties(querySchema);
|
|
142
|
+
if (additionalProperties === void 0 || !flattenJsonUnionSchema(additionalProperties).every(isPrimitive) || queryEntries?.some(([name]) => name === "query") || typeof query === "object" && (constrainsKeys(query.propertyNames) || query.patternProperties !== void 0 || query.minProperties !== void 0 || query.maxProperties !== void 0 || query.required?.some((name) => !Object.hasOwn(query.properties ?? {}, name)))) return;
|
|
143
|
+
const { properties: _, ...schema } = combineJsonObjectSchemaEntries([], additionalProperties);
|
|
144
|
+
operation.parameters ??= [];
|
|
145
|
+
operation.parameters.push({
|
|
146
|
+
in: "query",
|
|
147
|
+
name: "query",
|
|
148
|
+
schema: ctx.registry.toOpenAPISchema(schema, "input"),
|
|
149
|
+
style: "form",
|
|
150
|
+
explode: true
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Whether a schema of the keys of an object constrains them, which one saying only that they are
|
|
155
|
+
* strings (like those Zod writes for its records) does not.
|
|
156
|
+
*/
|
|
157
|
+
function constrainsKeys(propertyNames) {
|
|
158
|
+
return propertyNames !== void 0 && !(typeof propertyNames === "object" && propertyNames.type === "string" && Object.keys(propertyNames).length === 1);
|
|
159
|
+
}
|
|
160
|
+
function renderHeaderParameters(ctx, operation, headersEntries) {
|
|
161
|
+
for (const [name, schema, optional] of headersEntries ?? []) {
|
|
162
|
+
operation.parameters ??= [];
|
|
163
|
+
operation.parameters.push({
|
|
164
|
+
in: "header",
|
|
165
|
+
name,
|
|
166
|
+
required: optional ? void 0 : true,
|
|
167
|
+
schema: ctx.registry.toOpenAPISchema(schema, "input")
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function buildSuccessResponse(ctx, operation, def, meta) {
|
|
172
|
+
const status = meta?.successStatus ?? DEFAULT_SUCCESS_STATUS;
|
|
173
|
+
const description = meta?.successDescription ?? "OK";
|
|
174
|
+
const outputStructure = meta?.outputStructure ?? "compact";
|
|
175
|
+
if (outputStructure === "compact") {
|
|
176
|
+
const iteratorDetails = getAsyncIteratorObjectSchemasDetails(def.outputSchemas);
|
|
177
|
+
if (iteratorDetails) {
|
|
178
|
+
operation.responses ??= {};
|
|
179
|
+
operation.responses[toResponseStatusKey(status)] = {
|
|
180
|
+
description,
|
|
181
|
+
content: toAsyncIteratorObjectContent(ctx, "output", ctx.convertSchemas(iteratorDetails.yieldSchemas, "output"), ctx.convertSchemas(iteratorDetails.returnSchemas, "output"))
|
|
182
|
+
};
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const [schema] = ctx.convertSchemas(def.outputSchemas, "output");
|
|
187
|
+
if (isUnconstrainedSchema(schema) || outputStructure === "compact") {
|
|
188
|
+
operation.responses ??= {};
|
|
189
|
+
operation.responses[toResponseStatusKey(status)] = {
|
|
190
|
+
description,
|
|
191
|
+
content: toBodyContent(ctx, "output", schema)
|
|
192
|
+
};
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
for (const [responseStatus, parts] of extractDetailedResponseParts(schema, status)) {
|
|
196
|
+
const responseObject = { description: parts.descriptions.length ? parts.descriptions.join(", ") : description };
|
|
197
|
+
if (parts.bodies.length) responseObject.content = toBodyContent(ctx, "output", combineJsonSchemasWithComposition("anyOf", deduplicateJsonSchemas(parts.bodies)));
|
|
198
|
+
if (parts.headers.length) extractJsonObjectSchemaEntries(combineJsonSchemasWithComposition("anyOf", parts.headers))?.forEach(([name, schema, optional]) => {
|
|
199
|
+
responseObject.headers ??= {};
|
|
200
|
+
responseObject.headers[name] = {
|
|
201
|
+
required: optional ? void 0 : true,
|
|
202
|
+
schema: ctx.registry.toOpenAPISchema(schema, "output")
|
|
203
|
+
};
|
|
204
|
+
});
|
|
205
|
+
operation.responses ??= {};
|
|
206
|
+
operation.responses[toResponseStatusKey(responseStatus)] = responseObject;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Formats a numeric HTTP status as a Responses Object key.
|
|
211
|
+
*/
|
|
212
|
+
function toResponseStatusKey(status) {
|
|
213
|
+
return String(status);
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Flattens a detailed output schema (a union of `{ status?, headers?, body? }` objects)
|
|
217
|
+
* into per-status response pieces.
|
|
218
|
+
*/
|
|
219
|
+
function extractDetailedResponseParts(schema, defaultStatus) {
|
|
220
|
+
const partsByStatus = /* @__PURE__ */ new Map();
|
|
221
|
+
for (const item of flattenJsonUnionSchema(schema)) {
|
|
222
|
+
const entries = extractJsonObjectSchemaEntries(item);
|
|
223
|
+
if (!entries) throw new OpenAPIGeneratorError("outputStructure is \"detailed\" but the output schema (or one of its union members) is not an object.\n Expected each member shaped like: { status?: number (< 400), headers?: object, body?: unknown }");
|
|
224
|
+
const [, statusSchema, statusOptional = true] = entries.find(([name]) => name === "status") ?? [];
|
|
225
|
+
const statuses = statusSchema === void 0 ? /* @__PURE__ */ new Map() : extractDetailedStatuses(statusSchema);
|
|
226
|
+
if (!statuses) throw new OpenAPIGeneratorError(`invalid "status" field in the detailed output schema.
|
|
227
|
+
Expected: literal integers below 400 (const, enum, or a union of them)
|
|
228
|
+
Received: ${stringifyJSON(statusSchema)}`);
|
|
229
|
+
if (statusOptional && !statuses.has(defaultStatus)) statuses.set(defaultStatus, void 0);
|
|
230
|
+
const [, headersSchema, headersOptional = true] = entries.find(([name]) => name === "headers") ?? [];
|
|
231
|
+
const bodySchema = entries.find(([name]) => name === "body")?.[1];
|
|
232
|
+
for (const [status, description] of statuses) {
|
|
233
|
+
let parts = partsByStatus.get(status);
|
|
234
|
+
if (!parts) {
|
|
235
|
+
parts = {
|
|
236
|
+
descriptions: [],
|
|
237
|
+
bodies: [],
|
|
238
|
+
headers: []
|
|
239
|
+
};
|
|
240
|
+
partsByStatus.set(status, parts);
|
|
241
|
+
}
|
|
242
|
+
if (description !== void 0) parts.descriptions.push(description);
|
|
243
|
+
if (headersSchema !== void 0) parts.headers.push(headersSchema);
|
|
244
|
+
if (headersOptional) parts.headers.push({ type: "object" });
|
|
245
|
+
if (bodySchema !== void 0) parts.bodies.push(bodySchema);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return partsByStatus;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Collects every status a detailed output `status` schema allows, mapped to its description.
|
|
252
|
+
* Accepts `const`, `enum` (how Effect, arktype, and valibot `picklist` emit literals), or a union of them.
|
|
253
|
+
* Returns `undefined` when any member is not a literal integer below 400.
|
|
254
|
+
*/
|
|
255
|
+
function extractDetailedStatuses(schema) {
|
|
256
|
+
const statuses = /* @__PURE__ */ new Map();
|
|
257
|
+
for (const member of flattenJsonUnionSchema(schema)) {
|
|
258
|
+
if (typeof member !== "object") return;
|
|
259
|
+
const values = member.const !== void 0 ? [member.const] : member.enum;
|
|
260
|
+
if (!values?.length) return;
|
|
261
|
+
for (const value of values) {
|
|
262
|
+
if (!Number.isInteger(value) || value >= 400) return;
|
|
263
|
+
if (!statuses.has(value)) statuses.set(value, member.description);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
return statuses.size ? statuses : void 0;
|
|
267
|
+
}
|
|
268
|
+
function buildErrorResponse(ctx, operation, def) {
|
|
269
|
+
const definitionsByStatus = /* @__PURE__ */ new Map();
|
|
270
|
+
for (const code of Object.keys(def.errorMap)) {
|
|
271
|
+
const config = def.errorMap[code];
|
|
272
|
+
if (!config) continue;
|
|
273
|
+
const status = getOwn(ctx.errorStatusMap, code) ?? DEFAULT_ERROR_STATUS;
|
|
274
|
+
const [dataJsonSchema, dataOptional] = ctx.convertSchemas(config.data !== void 0 ? [config.data] : void 0, "output");
|
|
275
|
+
let definitions = definitionsByStatus.get(status);
|
|
276
|
+
if (!definitions) {
|
|
277
|
+
definitions = [];
|
|
278
|
+
definitionsByStatus.set(status, definitions);
|
|
279
|
+
}
|
|
280
|
+
definitions.push({
|
|
281
|
+
code,
|
|
282
|
+
dataJsonSchema,
|
|
283
|
+
dataOptional,
|
|
284
|
+
defaultMessage: config.message
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
if (!definitionsByStatus.size) return;
|
|
288
|
+
const undefinedErrorSchema = ctx.registry.register("UndefinedError", {
|
|
289
|
+
title: "UndefinedError",
|
|
290
|
+
type: "object",
|
|
291
|
+
properties: {
|
|
292
|
+
defined: { const: false },
|
|
293
|
+
code: { type: "string" },
|
|
294
|
+
message: { type: "string" },
|
|
295
|
+
data: {}
|
|
296
|
+
},
|
|
297
|
+
required: [
|
|
298
|
+
"defined",
|
|
299
|
+
"code",
|
|
300
|
+
"message"
|
|
301
|
+
]
|
|
302
|
+
});
|
|
303
|
+
for (const [status, definitions] of definitionsByStatus.entries()) {
|
|
304
|
+
const descriptions = definitions.map(({ defaultMessage }) => defaultMessage).filter((m) => m !== void 0);
|
|
305
|
+
const definedErrors = definitions.map((def) => ({
|
|
306
|
+
...def,
|
|
307
|
+
dataJsonSchema: ctx.registry.hoistDefs(def.dataJsonSchema, "output")
|
|
308
|
+
}));
|
|
309
|
+
const defaultSchema = () => combineJsonSchemasWithComposition("oneOf", [...definedErrors.map(({ code, dataJsonSchema, dataOptional }) => {
|
|
310
|
+
return ctx.registry.register(toErrorComponentName(code), {
|
|
311
|
+
title: code,
|
|
312
|
+
...combineJsonObjectSchemaEntries([
|
|
313
|
+
[
|
|
314
|
+
"defined",
|
|
315
|
+
{ const: true },
|
|
316
|
+
false
|
|
317
|
+
],
|
|
318
|
+
[
|
|
319
|
+
"code",
|
|
320
|
+
{ const: code },
|
|
321
|
+
false
|
|
322
|
+
],
|
|
323
|
+
[
|
|
324
|
+
"message",
|
|
325
|
+
{ type: "string" },
|
|
326
|
+
false
|
|
327
|
+
],
|
|
328
|
+
[
|
|
329
|
+
"data",
|
|
330
|
+
dataJsonSchema,
|
|
331
|
+
dataOptional
|
|
332
|
+
]
|
|
333
|
+
])
|
|
334
|
+
});
|
|
335
|
+
}), undefinedErrorSchema]);
|
|
336
|
+
const responseSchema = ctx.errorResponseBodySchema === void 0 ? defaultSchema() : value(ctx.errorResponseBodySchema, definedErrors, status, defaultSchema);
|
|
337
|
+
const responseObject = { description: descriptions.length ? descriptions.join(", ") : status.toString() };
|
|
338
|
+
if (responseSchema !== void 0 && responseSchema !== null) responseObject.content = { [ctx.errorResponseContentType]: { schema: ctx.registry.toOpenAPISchema(responseSchema, "output") } };
|
|
339
|
+
operation.responses ??= {};
|
|
340
|
+
operation.responses[toResponseStatusKey(status)] = responseObject;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Converts an error code into a component name, e.g. `BAD_REQUEST` -> `BadRequest`.
|
|
345
|
+
*/
|
|
346
|
+
function toErrorComponentName(code) {
|
|
347
|
+
return code.split(/[^a-z0-9]+/i).filter(Boolean).map((part) => {
|
|
348
|
+
const rest = part.slice(1);
|
|
349
|
+
return part.charAt(0).toUpperCase() + (rest === rest.toUpperCase() ? rest.toLowerCase() : rest);
|
|
350
|
+
}).join("") || "Error";
|
|
351
|
+
}
|
|
352
|
+
function toAsyncIteratorObjectContent(ctx, direction, [yieldSchema, yieldOptional], [returnSchema, returnOptional]) {
|
|
353
|
+
const schema = combineJsonSchemasWithComposition("oneOf", [
|
|
354
|
+
combineJsonObjectSchemaEntries([
|
|
355
|
+
[
|
|
356
|
+
"event",
|
|
357
|
+
{ const: "message" },
|
|
358
|
+
false
|
|
359
|
+
],
|
|
360
|
+
[
|
|
361
|
+
"data",
|
|
362
|
+
yieldSchema,
|
|
363
|
+
yieldOptional
|
|
364
|
+
],
|
|
365
|
+
[
|
|
366
|
+
"id",
|
|
367
|
+
{ type: "string" },
|
|
368
|
+
true
|
|
369
|
+
],
|
|
370
|
+
[
|
|
371
|
+
"retry",
|
|
372
|
+
{ type: "number" },
|
|
373
|
+
true
|
|
374
|
+
]
|
|
375
|
+
]),
|
|
376
|
+
combineJsonObjectSchemaEntries([
|
|
377
|
+
[
|
|
378
|
+
"event",
|
|
379
|
+
{ const: "close" },
|
|
380
|
+
false
|
|
381
|
+
],
|
|
382
|
+
[
|
|
383
|
+
"data",
|
|
384
|
+
returnSchema,
|
|
385
|
+
returnOptional
|
|
386
|
+
],
|
|
387
|
+
[
|
|
388
|
+
"id",
|
|
389
|
+
{ type: "string" },
|
|
390
|
+
true
|
|
391
|
+
],
|
|
392
|
+
[
|
|
393
|
+
"retry",
|
|
394
|
+
{ type: "number" },
|
|
395
|
+
true
|
|
396
|
+
]
|
|
397
|
+
]),
|
|
398
|
+
{
|
|
399
|
+
type: "object",
|
|
400
|
+
properties: {
|
|
401
|
+
event: { const: "error" },
|
|
402
|
+
data: {},
|
|
403
|
+
id: { type: "string" },
|
|
404
|
+
retry: { type: "number" }
|
|
405
|
+
},
|
|
406
|
+
required: ["event"]
|
|
407
|
+
}
|
|
408
|
+
]);
|
|
409
|
+
return { "text/event-stream": { schema: ctx.registry.toOpenAPISchema(schema, direction) } };
|
|
410
|
+
}
|
|
411
|
+
function toBodyContent(ctx, direction, schema) {
|
|
412
|
+
const fileSchemasByMediaType = /* @__PURE__ */ new Map();
|
|
413
|
+
const rest = flattenJsonUnionSchema(schema).filter((s) => {
|
|
414
|
+
const resolved = resolveJsonSchemaRootLocalRef(s);
|
|
415
|
+
if (!isJsonFileSchema(resolved)) return !isUnconstrainedSchema(s);
|
|
416
|
+
const contentMediaType = resolved.contentMediaType ?? "*/*";
|
|
417
|
+
const schemas = fileSchemasByMediaType.get(contentMediaType);
|
|
418
|
+
if (schemas) schemas.push(s);
|
|
419
|
+
else fileSchemasByMediaType.set(contentMediaType, [s]);
|
|
420
|
+
return false;
|
|
421
|
+
});
|
|
422
|
+
const content = {};
|
|
423
|
+
if (rest.length > 0) {
|
|
424
|
+
const restSchema = fileSchemasByMediaType.size ? combineJsonSchemasWithComposition("anyOf", rest) : schema;
|
|
425
|
+
const contentTypes = !containsJsonFileSchema(restSchema) ? ["application/json"] : mayHoldNoFiles(restSchema) ? ["multipart/form-data", "application/json"] : ["multipart/form-data"];
|
|
426
|
+
for (const contentType of contentTypes) {
|
|
427
|
+
const fileSchemas = fileSchemasByMediaType.get(contentType);
|
|
428
|
+
fileSchemasByMediaType.delete(contentType);
|
|
429
|
+
content[contentType] = { schema: ctx.registry.toOpenAPISchema(combineJsonSchemasWithComposition("anyOf", [restSchema, ...fileSchemas ?? []]), direction) };
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
for (const [contentType, schemas] of fileSchemasByMediaType.entries()) content[contentType] = { schema: ctx.registry.toOpenAPISchema(combineJsonSchemasWithComposition("anyOf", schemas), direction) };
|
|
433
|
+
return content;
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Whether a value of the schema may hold no file, like one whose files are optional: a value is
|
|
437
|
+
* sent as `multipart/form-data` only when it holds a file, which a required key or one of the
|
|
438
|
+
* first `minItems` items of an array (`[Blob]`) may always hold.
|
|
439
|
+
*/
|
|
440
|
+
function mayHoldNoFiles(root, schema = root, visiting = /* @__PURE__ */ new Set()) {
|
|
441
|
+
if (typeof schema === "boolean" || visiting.has(schema)) return true;
|
|
442
|
+
if (isJsonFileSchema(schema)) return false;
|
|
443
|
+
visiting.add(schema);
|
|
444
|
+
try {
|
|
445
|
+
const target = typeof schema.$ref === "string" ? resolveJsonSchemaLocalPointer(root, schema.$ref) : void 0;
|
|
446
|
+
const holdsNoFiles = (s) => mayHoldNoFiles(root, s, visiting);
|
|
447
|
+
const minItems = schema.minItems ?? 0;
|
|
448
|
+
return (target === void 0 || holdsNoFiles(target)) && (schema.anyOf === void 0 || schema.anyOf.some(holdsNoFiles)) && (schema.oneOf === void 0 || schema.oneOf.some(holdsNoFiles)) && (schema.allOf === void 0 || schema.allOf.every(holdsNoFiles)) && (schema.prefixItems ?? []).slice(0, minItems).every(holdsNoFiles) && (schema.items === void 0 || minItems <= (schema.prefixItems?.length ?? 0) || holdsNoFiles(schema.items)) && (schema.required ?? []).every((name) => {
|
|
449
|
+
const property = schema.properties?.[name];
|
|
450
|
+
return property === void 0 || holdsNoFiles(property);
|
|
451
|
+
});
|
|
452
|
+
} finally {
|
|
453
|
+
visiting.delete(schema);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
function isPrimitive(schema) {
|
|
457
|
+
return isJsonPrimitiveSchema(resolveJsonSchemaRootLocalRef(schema));
|
|
458
|
+
}
|
|
459
|
+
export { OpenAPIGeneratorError, buildErrorResponse, buildRequest, buildSuccessResponse, toOpenAPIPath };
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { OpenAPIErrorBodyDefinition, OpenAPIGeneratorError } from "./openapi-generator-operation.js";
|
|
2
|
+
import { OpenAPIJsonSerializer } from "./openapi-json-serializer.js";
|
|
3
|
+
import { OpenAPIDocument, OpenAPIV3_2, OpenAPIVersion } from "./types.js";
|
|
4
|
+
import { Public, Value } from "@orpc/shared";
|
|
5
|
+
import { AnyProcedureContract, RouterContract } from "@orpc/contract";
|
|
6
|
+
import { JsonSchema, JsonSchemaConverter } from "@orpc/json-schema";
|
|
7
|
+
import { AnyProcedure, AnyRouter } from "@orpc/server";
|
|
8
|
+
export interface OpenAPIGeneratorOptions {
|
|
9
|
+
converters?: JsonSchemaConverter[] | undefined;
|
|
10
|
+
/**
|
|
11
|
+
* The serializer used to serialize the generated OpenAPI documentation
|
|
12
|
+
*/
|
|
13
|
+
serializer?: Public<OpenAPIJsonSerializer> | undefined;
|
|
14
|
+
}
|
|
15
|
+
export interface OpenAPIGeneratorGenerateOptions<TVersion extends OpenAPIVersion> {
|
|
16
|
+
/**
|
|
17
|
+
* The OpenAPI version of the generated document.
|
|
18
|
+
* The document is generated as OpenAPI 3.2 and downgraded when an older version is requested.
|
|
19
|
+
* The minor version selects the conversion, the document carries the exact value, such as `3.1.0`.
|
|
20
|
+
*
|
|
21
|
+
* @default '3.2.0'
|
|
22
|
+
*/
|
|
23
|
+
version?: TVersion | undefined;
|
|
24
|
+
/**
|
|
25
|
+
* OpenAPI 3.2 document fields to start from, such as `info`, `servers`, or `components`.
|
|
26
|
+
* They are downgraded with the rest of the document when an older `version` is requested.
|
|
27
|
+
* The `openapi` field is derived from `version`.
|
|
28
|
+
*/
|
|
29
|
+
base?: Partial<Omit<OpenAPIV3_2.OpenAPIObject, "openapi">> | undefined;
|
|
30
|
+
/**
|
|
31
|
+
* Root-level `$defs` are always moved into `components.schemas`.
|
|
32
|
+
* Use this to customize the component name of a hoisted def.
|
|
33
|
+
*
|
|
34
|
+
* @remarks
|
|
35
|
+
* - Characters OpenAPI does not allow in component keys (anything but `a-z`, `A-Z`, `0-9`, `.`, `_`, `-`)
|
|
36
|
+
* are replaced by `_` in the returned name, e.g. `User Profile` becomes `User_Profile`.
|
|
37
|
+
* - The returned name is a preference, conflicting names are still postfixed (`Planet`, `PlanetInput`, `Planet2`, ...).
|
|
38
|
+
*
|
|
39
|
+
* @default defName => defName
|
|
40
|
+
*/
|
|
41
|
+
componentName?: ((defName: string, defSchema: JsonSchema) => string) | undefined;
|
|
42
|
+
/**
|
|
43
|
+
* Filter procedures. Return `false` to exclude a procedure from the OpenAPI specification.
|
|
44
|
+
*
|
|
45
|
+
* @default true
|
|
46
|
+
*/
|
|
47
|
+
filter?: Value<boolean, [contract: AnyProcedureContract | AnyProcedure, path: string[]]> | undefined;
|
|
48
|
+
/**
|
|
49
|
+
* Define a custom JSON schema for the error response body when using
|
|
50
|
+
* type-safe errors. Helps align ORPC error formatting with existing API
|
|
51
|
+
* response standards or conventions.
|
|
52
|
+
*
|
|
53
|
+
* @remarks
|
|
54
|
+
* - Return `defaultSchema()` to keep the default schema, or `null | undefined` to document an empty body, matching an `errorResponseBodyEncoder` that returns `undefined`.
|
|
55
|
+
* - The schema is an OpenAPI 3.2 Schema Object, it is downgraded with the rest of the document when an older `version` is requested.
|
|
56
|
+
*/
|
|
57
|
+
errorResponseBodySchema?: Value<JsonSchema | null | undefined, [definedErrors: OpenAPIErrorBodyDefinition[], status: number, defaultSchema: () => JsonSchema]> | undefined;
|
|
58
|
+
/**
|
|
59
|
+
* Media type of error responses in the generated document, e.g. `application/problem+json`.
|
|
60
|
+
* Should match the handler's `errorResponseContentType`.
|
|
61
|
+
*
|
|
62
|
+
* @default 'application/json'
|
|
63
|
+
*/
|
|
64
|
+
errorResponseContentType?: string | undefined;
|
|
65
|
+
/**
|
|
66
|
+
* Mapping ORPCError Code -> HTTP Status Code
|
|
67
|
+
* Codes missing from the map fall back to `DEFAULT_ERROR_STATUS` (400).
|
|
68
|
+
*
|
|
69
|
+
* @default COMMON_ERROR_STATUS_MAP
|
|
70
|
+
*/
|
|
71
|
+
errorStatusMap?: Record<string, number> | undefined;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Generates an OpenAPI document from a contract or router.
|
|
75
|
+
* Relies on JSON schema converters to translate input, output, and error schemas into JSON Schemas.
|
|
76
|
+
*
|
|
77
|
+
* @see {@link https://orpc.dev/docs/openapi/specification#openapi-generator | OpenAPI Specification - OpenAPI Generator}
|
|
78
|
+
*/
|
|
79
|
+
export declare class OpenAPIGenerator {
|
|
80
|
+
private readonly serializer;
|
|
81
|
+
private readonly converter;
|
|
82
|
+
constructor(options?: OpenAPIGeneratorOptions);
|
|
83
|
+
generate<TVersion extends OpenAPIVersion = "3.2.0">(router: RouterContract | AnyRouter, options?: OpenAPIGeneratorGenerateOptions<TVersion>): Promise<OpenAPIDocument<TVersion>>;
|
|
84
|
+
private convertSchema;
|
|
85
|
+
private convertSchemas;
|
|
86
|
+
}
|
|
87
|
+
export { type OpenAPIErrorBodyDefinition, OpenAPIGeneratorError };
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import "./constants.js";
|
|
2
|
+
import { getOpenAPIMeta } from "./meta.js";
|
|
3
|
+
import { OpenAPIComponentRegistry } from "./openapi-generator-components.js";
|
|
4
|
+
import { OpenAPIGeneratorError, buildErrorResponse, buildRequest, buildSuccessResponse, toOpenAPIPath } from "./openapi-generator-operation.js";
|
|
5
|
+
import { OpenAPIJsonSerializer } from "./openapi-json-serializer.js";
|
|
6
|
+
import { getDynamicPathParams } from "./utils.js";
|
|
7
|
+
import { clone, mergeHttpPath, pathToHttpPath, toArray, value } from "@orpc/shared";
|
|
8
|
+
import { downgradeSpecV31ToV30, downgradeSpecV32ToV31 } from "@openapi-spec/downgrader";
|
|
9
|
+
import { COMMON_ERROR_STATUS_MAP } from "@orpc/client";
|
|
10
|
+
import { DelegatingJsonSchemaConverter, StandardJsonSchemaConverter, combineJsonSchemasWithComposition, hoistRecursiveRefToDef } from "@orpc/json-schema";
|
|
11
|
+
import { walkProcedureContractsAsync } from "@orpc/server";
|
|
12
|
+
// src/openapi-generator.ts
|
|
13
|
+
/**
|
|
14
|
+
* Generates an OpenAPI document from a contract or router.
|
|
15
|
+
* Relies on JSON schema converters to translate input, output, and error schemas into JSON Schemas.
|
|
16
|
+
*
|
|
17
|
+
* @see {@link https://orpc.dev/docs/openapi/specification#openapi-generator | OpenAPI Specification - OpenAPI Generator}
|
|
18
|
+
*/
|
|
19
|
+
var OpenAPIGenerator = class {
|
|
20
|
+
serializer;
|
|
21
|
+
converter;
|
|
22
|
+
constructor(options = {}) {
|
|
23
|
+
this.serializer = options.serializer ?? new OpenAPIJsonSerializer();
|
|
24
|
+
this.converter = new DelegatingJsonSchemaConverter([...toArray(options.converters), new StandardJsonSchemaConverter()]);
|
|
25
|
+
}
|
|
26
|
+
async generate(router, options = {}) {
|
|
27
|
+
const version = options.version ?? "3.2.0";
|
|
28
|
+
const doc = {
|
|
29
|
+
...clone(options.base),
|
|
30
|
+
openapi: "3.2.0",
|
|
31
|
+
info: options.base?.info ?? {
|
|
32
|
+
title: "API Reference",
|
|
33
|
+
version: "0.0.0"
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
const ctx = {
|
|
37
|
+
registry: new OpenAPIComponentRegistry(doc, options.componentName),
|
|
38
|
+
convertSchemas: (schemas, direction) => this.convertSchemas(schemas, direction),
|
|
39
|
+
errorStatusMap: options.errorStatusMap ?? COMMON_ERROR_STATUS_MAP,
|
|
40
|
+
errorResponseBodySchema: options.errorResponseBodySchema,
|
|
41
|
+
errorResponseContentType: options.errorResponseContentType ?? "application/json"
|
|
42
|
+
};
|
|
43
|
+
const errors = [];
|
|
44
|
+
const routeOwners = /* @__PURE__ */ new Map();
|
|
45
|
+
const operationIdOwners = /* @__PURE__ */ new Map();
|
|
46
|
+
await walkProcedureContractsAsync(router, (contract, path) => {
|
|
47
|
+
if (value(options.filter, contract, path) === false) return;
|
|
48
|
+
const procedurePath = path.length ? path.join(".") : "(root)";
|
|
49
|
+
try {
|
|
50
|
+
const def = contract["~orpc"];
|
|
51
|
+
const meta = getOpenAPIMeta(contract);
|
|
52
|
+
const method = (meta?.method ?? "POST").toLowerCase();
|
|
53
|
+
if (method === "query" && !version.startsWith("3.2.")) throw new OpenAPIGeneratorError(`QUERY operations require OpenAPI 3.2, but version "${version}" was requested.`);
|
|
54
|
+
const postPath = meta?.path ?? pathToHttpPath(path);
|
|
55
|
+
const httpPath = meta?.prefix ? mergeHttpPath(meta.prefix, postPath) : postPath;
|
|
56
|
+
const dynamicPathParams = getDynamicPathParams(httpPath);
|
|
57
|
+
const openApiPath = toOpenAPIPath(httpPath, dynamicPathParams);
|
|
58
|
+
let operation;
|
|
59
|
+
if (meta?.spec !== void 0 && typeof meta.spec !== "function") operation = meta.spec;
|
|
60
|
+
else {
|
|
61
|
+
operation = {
|
|
62
|
+
operationId: meta?.operationId ?? path.join("."),
|
|
63
|
+
summary: meta?.summary,
|
|
64
|
+
description: meta?.description,
|
|
65
|
+
deprecated: meta?.deprecated,
|
|
66
|
+
tags: meta?.tags?.map((tag) => tag)
|
|
67
|
+
};
|
|
68
|
+
buildRequest(ctx, operation, def, meta, dynamicPathParams);
|
|
69
|
+
buildSuccessResponse(ctx, operation, def, meta);
|
|
70
|
+
buildErrorResponse(ctx, operation, def);
|
|
71
|
+
}
|
|
72
|
+
if (typeof meta?.spec === "function") operation = meta.spec(operation);
|
|
73
|
+
const routeKey = `${method} ${toOpenAPIPath(httpPath, dynamicPathParams?.map((p) => ({
|
|
74
|
+
...p,
|
|
75
|
+
parameterName: ""
|
|
76
|
+
})))}`;
|
|
77
|
+
const routeOwner = routeOwners.get(routeKey);
|
|
78
|
+
if (routeOwner !== void 0) throw new OpenAPIGeneratorError(`${method.toUpperCase()} ${openApiPath} is already documented by the procedure at ${routeOwner}.\n OpenAPI allows one operation per method and path (path param names are ignored).\n Fix: change the method or path of one of them.`);
|
|
79
|
+
const { operationId } = operation;
|
|
80
|
+
if (operationId !== void 0) {
|
|
81
|
+
const operationIdOwner = operationIdOwners.get(operationId);
|
|
82
|
+
if (operationIdOwner !== void 0) throw new OpenAPIGeneratorError(`operationId "${operationId}" is already used by the procedure at ${operationIdOwner}.\n OpenAPI requires operationIds to be unique. Fix: give one of them a different operationId.`);
|
|
83
|
+
operationIdOwners.set(operationId, procedurePath);
|
|
84
|
+
}
|
|
85
|
+
routeOwners.set(routeKey, procedurePath);
|
|
86
|
+
doc.paths ??= {};
|
|
87
|
+
doc.paths[openApiPath] ??= {};
|
|
88
|
+
doc.paths[openApiPath][method] = operation;
|
|
89
|
+
} catch (e) {
|
|
90
|
+
if (!(e instanceof OpenAPIGeneratorError)) throw e;
|
|
91
|
+
errors.push(`Procedure at ${procedurePath}: ${e.message}`);
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
if (errors.length) throw new OpenAPIGeneratorError(`[OpenAPIGenerator] Failed to generate the OpenAPI document (${errors.length} error${errors.length === 1 ? "" : "s"}):\n\n${errors.join("\n\n")}`);
|
|
95
|
+
const serialized = this.serializer.serializeJson(doc).json;
|
|
96
|
+
return toVersionedOpenAPIDocument(serialized, version);
|
|
97
|
+
}
|
|
98
|
+
convertSchema(schema, direction) {
|
|
99
|
+
const [jsonSchema, optional] = this.converter.convert(schema, direction);
|
|
100
|
+
return [hoistRecursiveRefToDef(strip$schemaField(jsonSchema)), optional];
|
|
101
|
+
}
|
|
102
|
+
convertSchemas(schemas, direction) {
|
|
103
|
+
if (!schemas || schemas.length <= 1) return this.convertSchema(schemas?.[0], direction);
|
|
104
|
+
const results = schemas.map((s) => this.convertSchema(s, direction));
|
|
105
|
+
return [combineJsonSchemasWithComposition("allOf", results.map(([jsonSchema]) => jsonSchema)), results.every(([, optional]) => optional)];
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
function toVersionedOpenAPIDocument(doc, version) {
|
|
109
|
+
return {
|
|
110
|
+
...version.startsWith("3.2.") ? doc : version.startsWith("3.1.") ? downgradeSpecV32ToV31(doc) : downgradeSpecV31ToV30(downgradeSpecV32ToV31(doc)),
|
|
111
|
+
openapi: version
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function strip$schemaField(schema) {
|
|
115
|
+
if (typeof schema !== "object") return schema;
|
|
116
|
+
const { $schema: _schema, ...rest } = schema;
|
|
117
|
+
return rest;
|
|
118
|
+
}
|
|
119
|
+
export { OpenAPIGenerator, OpenAPIGeneratorError };
|