@orpc/openapi 2.0.0-beta.2 → 2.0.0-beta.21
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 +32 -21
- package/dist/adapters/fetch/index.d.mts +2 -2
- package/dist/adapters/fetch/index.d.ts +2 -2
- package/dist/adapters/fetch/index.mjs +3 -3
- package/dist/adapters/node/index.d.mts +2 -2
- package/dist/adapters/node/index.d.ts +2 -2
- package/dist/adapters/node/index.mjs +2 -2
- package/dist/adapters/standard/index.d.mts +2 -2
- package/dist/adapters/standard/index.d.ts +2 -2
- package/dist/adapters/standard/index.mjs +3 -3
- package/dist/extensions/route.d.mts +2 -2
- package/dist/extensions/route.d.ts +2 -2
- package/dist/index.d.mts +63 -37
- package/dist/index.d.ts +63 -37
- package/dist/index.mjs +711 -753
- package/dist/plugins/index.d.mts +1 -1
- package/dist/plugins/index.d.ts +1 -1
- package/dist/shared/{openapi.BYcWgK1j.d.ts → openapi.B6hEbRyF.d.ts} +18 -14
- package/dist/shared/{openapi.C7m7NAmH.d.mts → openapi.BOOA-bde.d.mts} +1 -1
- package/dist/shared/{openapi.C7m7NAmH.d.ts → openapi.BOOA-bde.d.ts} +1 -1
- package/dist/shared/{openapi.XeW6_5tm.d.mts → openapi.BafbB3uM.d.mts} +18 -14
- package/dist/shared/{openapi.CYgMBSUF.d.mts → openapi.ByT4oUeY.d.mts} +2 -2
- package/dist/shared/{openapi.CYgMBSUF.d.ts → openapi.ByT4oUeY.d.ts} +2 -2
- package/dist/shared/{openapi.B2SK0ZAr.mjs → openapi.C-p_Q2lb.mjs} +4 -4
- package/dist/shared/{openapi.DR-y5p-D.mjs → openapi.CVgUshDP.mjs} +28 -25
- package/dist/shared/{openapi.BQzzr4-4.d.ts → openapi.DNNo0V-l.d.ts} +23 -9
- package/dist/shared/{openapi.BcEtAxQj.d.mts → openapi.hg_rhZ4x.d.mts} +23 -9
- package/dist/shared/{openapi.DmAa7YPO.mjs → openapi.zZH_UksW.mjs} +7 -4
- package/package.json +29 -13
package/dist/index.mjs
CHANGED
|
@@ -1,789 +1,201 @@
|
|
|
1
1
|
export { B as BracketNotationSerializer } from './shared/openapi.Bt87OzTt.mjs';
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
export { d as OpenAPIJsonSerializer } from './shared/openapi.
|
|
5
|
-
import { g as getOpenAPIMeta } from './shared/openapi.B9PQzqBn.mjs';
|
|
6
|
-
export { o as openapi } from './shared/openapi.B9PQzqBn.mjs';
|
|
2
|
+
import { createContractClientFactory, getAsyncIteratorObjectSchemaDetails, ProcedureContract, resolveMetaPlugins } from '@orpc/contract';
|
|
3
|
+
import { D as DEFAULT_OPENAPI_METHOD, a as DEFAULT_OPENAPI_INPUT_STRUCTURE, c as DEFAULT_OPENAPI_SUCCESS_DESCRIPTION, b as DEFAULT_OPENAPI_OUTPUT_STRUCTURE, i as isBodylessMethod, O as OpenAPISerializer, g as getDynamicPathParams } from './shared/openapi.zZH_UksW.mjs';
|
|
4
|
+
export { d as OpenAPIJsonSerializer } from './shared/openapi.zZH_UksW.mjs';
|
|
5
|
+
import { g as getOpenAPIMeta, o as openapi } from './shared/openapi.B9PQzqBn.mjs';
|
|
7
6
|
import { COMMON_ERROR_STATUS_MAP } from '@orpc/client';
|
|
8
7
|
export { COMMON_ERROR_STATUS_MAP } from '@orpc/client';
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
8
|
+
import { encodeJsonPointerSegment, ensureJsonSchemaObject, mapJsonSchemaRefs, decodeJsonPointerSegment, isUnconstrainedSchema, combineJsonSchemasWithComposition, extractJsonObjectSchemaEntries, combineJsonObjectSchemaEntries, flattenJsonUnionSchema, isJsonPrimitiveSchema, matchArrayableJsonSchema, isJsonFileSchema, DelegatingJsonSchemaConverter, StandardJsonSchemaConverter } from '@orpc/json-schema';
|
|
9
|
+
import { DEFAULT_SUCCESS_STATUS, DEFAULT_ERROR_STATUS, walkProcedureContractsAsync } from '@orpc/server';
|
|
10
|
+
import { isDeepEqual, value, findDeepMatches, isPlainObject, stringifyJSON, toArray, clone, pathToHttpPath, mergeHttpPath, isTypescriptObject } from '@orpc/shared';
|
|
12
11
|
import '@standardserver/core';
|
|
13
12
|
|
|
14
|
-
function
|
|
15
|
-
return
|
|
13
|
+
function createContractJsonifiedClientFactory(link, options = {}) {
|
|
14
|
+
return createContractClientFactory(link, options);
|
|
16
15
|
}
|
|
17
16
|
|
|
18
|
-
class
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
openapi: options.base?.openapi ?? "3.1.2",
|
|
34
|
-
info: options.base?.info ?? { title: "API Reference", version: "0.0.0" }
|
|
35
|
-
};
|
|
36
|
-
const errors = [];
|
|
37
|
-
await walkProcedureContractsAsync(router, async (contract, path) => {
|
|
38
|
-
if (value(options.filter, contract, path) === false) {
|
|
39
|
-
return;
|
|
40
|
-
}
|
|
41
|
-
try {
|
|
42
|
-
const def = contract["~orpc"];
|
|
43
|
-
const meta = getOpenAPIMeta(contract);
|
|
44
|
-
const method = (meta?.method ?? DEFAULT_OPENAPI_METHOD).toLowerCase();
|
|
45
|
-
const postPath = meta?.path ?? pathToHttpPath(path);
|
|
46
|
-
const httpPath = meta?.prefix ? mergeHttpPath(meta.prefix, postPath) : postPath;
|
|
47
|
-
const dynamicPathParams = getDynamicPathParams(httpPath);
|
|
48
|
-
const openApiPath = toOpenAPIPath(httpPath, dynamicPathParams);
|
|
49
|
-
let operationRef;
|
|
50
|
-
if (meta?.spec !== void 0 && typeof meta.spec !== "function") {
|
|
51
|
-
operationRef = meta.spec;
|
|
52
|
-
} else {
|
|
53
|
-
operationRef = {
|
|
54
|
-
operationId: meta?.operationId ?? path.join("."),
|
|
55
|
-
summary: meta?.summary,
|
|
56
|
-
description: meta?.description,
|
|
57
|
-
deprecated: meta?.deprecated,
|
|
58
|
-
tags: meta?.tags?.map((tag) => tag)
|
|
59
|
-
};
|
|
60
|
-
await this.request(doc, operationRef, def, meta, dynamicPathParams, options, path);
|
|
61
|
-
await this.successResponse(doc, operationRef, def, meta, options, path);
|
|
62
|
-
await this.errorResponse(doc, operationRef, def, meta, options);
|
|
63
|
-
}
|
|
64
|
-
if (typeof meta?.spec === "function") {
|
|
65
|
-
operationRef = meta.spec(operationRef);
|
|
66
|
-
}
|
|
67
|
-
doc.paths ??= {};
|
|
68
|
-
doc.paths[openApiPath] ??= {};
|
|
69
|
-
doc.paths[openApiPath][method] = operationRef;
|
|
70
|
-
} catch (e) {
|
|
71
|
-
if (!(e instanceof OpenAPIGeneratorError)) {
|
|
72
|
-
throw e;
|
|
73
|
-
}
|
|
74
|
-
errors.push(
|
|
75
|
-
`[OpenAPIGenerator] Error occurred while generating OpenAPI for procedure at path: ${path.join(".")}
|
|
76
|
-
${e.message}`
|
|
77
|
-
);
|
|
17
|
+
class OpenAPIComponentRegistry {
|
|
18
|
+
constructor(doc, customComponentName) {
|
|
19
|
+
this.doc = doc;
|
|
20
|
+
this.customComponentName = customComponentName;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Registers `schema` as a component under `preferredName` (or an equivalent/postfixed name)
|
|
24
|
+
* and returns a `$ref` to it.
|
|
25
|
+
*/
|
|
26
|
+
register(preferredName, schema) {
|
|
27
|
+
const { $defs, ...body } = schema;
|
|
28
|
+
let defName = preferredName;
|
|
29
|
+
if ($defs) {
|
|
30
|
+
for (let i = 2; defName in $defs; i++) {
|
|
31
|
+
defName = `${preferredName}${i}`;
|
|
78
32
|
}
|
|
79
|
-
});
|
|
80
|
-
if (errors.length) {
|
|
81
|
-
throw new OpenAPIGeneratorError(
|
|
82
|
-
`Some error occurred during OpenAPI generation:
|
|
83
|
-
|
|
84
|
-
${errors.join("\n\n")}`
|
|
85
|
-
);
|
|
86
33
|
}
|
|
87
|
-
return this.
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
return [strip$schemaField(jsonSchema), optional];
|
|
34
|
+
return this.hoistDefs({
|
|
35
|
+
$defs: { ...$defs, [defName]: body },
|
|
36
|
+
$ref: `#/$defs/${encodeJsonPointerSegment(defName)}`
|
|
37
|
+
});
|
|
92
38
|
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
async request(doc, ref, def, meta, dynamicPathParams, options, path) {
|
|
109
|
-
const method = meta?.method ?? DEFAULT_OPENAPI_METHOD;
|
|
110
|
-
const inputStructure = meta?.inputStructure ?? DEFAULT_OPENAPI_INPUT_STRUCTURE;
|
|
111
|
-
const inputSchemas = def.inputSchemas;
|
|
112
|
-
if (inputStructure === "compact") {
|
|
113
|
-
const eventIteratorDetails = getEventIteratorDetails(inputSchemas);
|
|
114
|
-
if (eventIteratorDetails) {
|
|
115
|
-
const [yieldSchemas, returnSchemas] = eventIteratorDetails;
|
|
116
|
-
const yieldResult = await this.convertSchemas(yieldSchemas, "input");
|
|
117
|
-
const returnResult = await this.convertSchemas(returnSchemas, "input");
|
|
118
|
-
ref.requestBody = {
|
|
119
|
-
required: true,
|
|
120
|
-
content: toEventIteratorContent(yieldResult, returnResult, doc, options)
|
|
121
|
-
};
|
|
122
|
-
return;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
const dynamicParams = dynamicPathParams?.map((v) => v.parameterName);
|
|
126
|
-
const [schema, optional] = await this.convertSchemas(inputSchemas, "input");
|
|
127
|
-
if (isUnconstrainedSchema(schema) && !dynamicParams?.length) {
|
|
128
|
-
return;
|
|
129
|
-
}
|
|
130
|
-
const objectSchemaEntries = extractJsonObjectSchemaEntries(schema);
|
|
131
|
-
if (!objectSchemaEntries) {
|
|
132
|
-
if (inputStructure === "detailed") {
|
|
133
|
-
throw new OpenAPIGeneratorError(
|
|
134
|
-
`Procedure at path "${path.join(".")}" has inputStructure "detailed" but its input schema is not an object.
|
|
135
|
-
Expected shape: { params?: Record<string, unknown>, query?: Record<string, unknown>, headers?: Record<string, unknown>, body?: unknown }`
|
|
136
|
-
);
|
|
137
|
-
}
|
|
138
|
-
if (method === "GET") {
|
|
139
|
-
throw new OpenAPIGeneratorError(
|
|
140
|
-
`Procedure at path "${path.join(".")}" uses method "GET" but its input schema is not an object.
|
|
141
|
-
GET procedures map all input fields to query parameters, so the schema must be an object.
|
|
142
|
-
Expected: Record<string, unknown>`
|
|
143
|
-
);
|
|
39
|
+
/**
|
|
40
|
+
* Moves a schema's root-level `$defs` into `doc.components.schemas` and rewrites
|
|
41
|
+
* its refs accordingly.
|
|
42
|
+
*/
|
|
43
|
+
hoistDefs(schema, direction) {
|
|
44
|
+
if (typeof schema !== "object" || !schema.$defs) {
|
|
45
|
+
return schema;
|
|
46
|
+
}
|
|
47
|
+
const { $defs, ...rest } = schema;
|
|
48
|
+
const defs = {};
|
|
49
|
+
const preferredNames = {};
|
|
50
|
+
for (const defName of Object.keys($defs)) {
|
|
51
|
+
const defSchema = $defs[defName];
|
|
52
|
+
if (defSchema === void 0) {
|
|
53
|
+
continue;
|
|
144
54
|
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
const
|
|
150
|
-
if (
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
55
|
+
const normalized = ensureJsonSchemaObject(defSchema);
|
|
56
|
+
defs[defName] = normalized;
|
|
57
|
+
preferredNames[defName] = this.customComponentName?.(defName, normalized) ?? defName;
|
|
58
|
+
}
|
|
59
|
+
const defNames = Object.keys(defs);
|
|
60
|
+
if (defNames.length === 0) {
|
|
61
|
+
return schema;
|
|
62
|
+
}
|
|
63
|
+
this.doc.components ??= {};
|
|
64
|
+
this.doc.components.schemas ??= {};
|
|
65
|
+
const componentsSchemas = this.doc.components.schemas;
|
|
66
|
+
const identityRenameMap = Object.fromEntries(
|
|
67
|
+
defNames.map((defName) => [defName, preferredNames[defName]])
|
|
68
|
+
);
|
|
69
|
+
const renameMap = {};
|
|
70
|
+
const pendingSchemas = [];
|
|
71
|
+
for (const defName of defNames) {
|
|
72
|
+
const cleanSchema = defs[defName];
|
|
73
|
+
const candidateSchemas = Object.fromEntries(
|
|
74
|
+
defNames.map((currentDefName) => [
|
|
75
|
+
preferredNames[currentDefName],
|
|
76
|
+
rewriteComponentSchemaRefs(defs[currentDefName], {
|
|
77
|
+
...identityRenameMap,
|
|
78
|
+
...renameMap
|
|
79
|
+
})
|
|
80
|
+
])
|
|
81
|
+
);
|
|
82
|
+
const preferredName = preferredNames[defName];
|
|
83
|
+
const prelimSchema = candidateSchemas[preferredName];
|
|
84
|
+
const [componentName, reuseExisting] = resolveComponentName(
|
|
85
|
+
componentsSchemas,
|
|
86
|
+
new Set(Object.values(renameMap)),
|
|
87
|
+
preferredName,
|
|
88
|
+
prelimSchema,
|
|
89
|
+
candidateSchemas,
|
|
90
|
+
direction
|
|
91
|
+
);
|
|
92
|
+
renameMap[defName] = componentName;
|
|
93
|
+
if (!reuseExisting) {
|
|
94
|
+
pendingSchemas.push({ cleanSchema, componentName });
|
|
156
95
|
}
|
|
157
|
-
dynamicParams.forEach((name) => {
|
|
158
|
-
const entry = paramsObjectSchemaEntries.find(([n]) => n === name);
|
|
159
|
-
if (!entry) {
|
|
160
|
-
throw new OpenAPIGeneratorError(
|
|
161
|
-
`Procedure at path "${path.join(".")}" is missing dynamic param "${name}" in its input schema.
|
|
162
|
-
Route params: ${dynamicParams.map((p) => `{${p}}`).join(", ")}
|
|
163
|
-
Schema keys: ${paramsObjectSchemaEntries.map(([n]) => n).join(", ") || "(none)"}`
|
|
164
|
-
);
|
|
165
|
-
}
|
|
166
|
-
if (entry[2]) {
|
|
167
|
-
throw new OpenAPIGeneratorError(
|
|
168
|
-
`Procedure at path "${path.join(".")}" has dynamic param "${name}" marked as optional in its input schema, but path params must always be required in OpenAPI.`
|
|
169
|
-
);
|
|
170
|
-
}
|
|
171
|
-
ref.parameters ??= [];
|
|
172
|
-
ref.parameters.push({
|
|
173
|
-
in: "path",
|
|
174
|
-
required: true,
|
|
175
|
-
name,
|
|
176
|
-
schema: toOpenAPISchema(entry[1], doc, options)
|
|
177
|
-
});
|
|
178
|
-
});
|
|
179
|
-
}
|
|
180
|
-
if (queryObjectSchemaEntries) {
|
|
181
|
-
queryObjectSchemaEntries.forEach(([name, schema2, optional2]) => {
|
|
182
|
-
const style = meta?.queryStyles?.[name];
|
|
183
|
-
const parameter = {
|
|
184
|
-
in: "query",
|
|
185
|
-
name,
|
|
186
|
-
schema: toOpenAPISchema(schema2, doc, options),
|
|
187
|
-
allowEmptyValue: true,
|
|
188
|
-
allowReserved: true
|
|
189
|
-
};
|
|
190
|
-
if (!optional2) {
|
|
191
|
-
parameter.required = true;
|
|
192
|
-
}
|
|
193
|
-
if (style === "comma-delimited-array" || style === "comma-delimited-object") {
|
|
194
|
-
parameter.explode = false;
|
|
195
|
-
} else if (style === "pipe-delimited-array" || style === "pipe-delimited-object") {
|
|
196
|
-
parameter.style = "pipeDelimited";
|
|
197
|
-
} else if (style === "space-delimited-array" || style === "space-delimited-object") {
|
|
198
|
-
parameter.style = "spaceDelimited";
|
|
199
|
-
} else if (style === "json") {
|
|
200
|
-
parameter.content = {
|
|
201
|
-
"application/json": { schema: parameter.schema }
|
|
202
|
-
};
|
|
203
|
-
delete parameter.schema;
|
|
204
|
-
} else if (style === void 0) {
|
|
205
|
-
if (!isJsonPrimitiveSchema(schema2)) {
|
|
206
|
-
const arrayable = matchArrayableJsonSchema(schema2);
|
|
207
|
-
if (!arrayable || !isJsonPrimitiveSchema(arrayable[0])) {
|
|
208
|
-
parameter.style = "deepObject";
|
|
209
|
-
parameter.explode = true;
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
} else ;
|
|
213
|
-
ref.parameters ??= [];
|
|
214
|
-
ref.parameters.push(parameter);
|
|
215
|
-
});
|
|
216
|
-
}
|
|
217
|
-
if (headersObjectSchemaEntries) {
|
|
218
|
-
headersObjectSchemaEntries.forEach(([name, schema2, optional2]) => {
|
|
219
|
-
ref.parameters ??= [];
|
|
220
|
-
ref.parameters.push({
|
|
221
|
-
in: "header",
|
|
222
|
-
name,
|
|
223
|
-
required: optional2 ? void 0 : true,
|
|
224
|
-
schema: toOpenAPISchema(schema2, doc, options)
|
|
225
|
-
});
|
|
226
|
-
});
|
|
227
96
|
}
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
};
|
|
97
|
+
for (const { cleanSchema, componentName } of pendingSchemas) {
|
|
98
|
+
componentsSchemas[componentName] = rewriteComponentSchemaRefs(
|
|
99
|
+
cleanSchema,
|
|
100
|
+
renameMap
|
|
101
|
+
);
|
|
234
102
|
}
|
|
103
|
+
return rewriteComponentSchemaRefs(rest, renameMap);
|
|
235
104
|
}
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
const status = meta?.successStatus ?? DEFAULT_SUCCESS_STATUS;
|
|
239
|
-
const description = meta?.successDescription ?? DEFAULT_OPENAPI_SUCCESS_DESCRIPTION;
|
|
240
|
-
const outputStructure = meta?.outputStructure ?? DEFAULT_OPENAPI_OUTPUT_STRUCTURE;
|
|
241
|
-
if (outputStructure === "compact") {
|
|
242
|
-
const eventDetails = getEventIteratorDetails(outputSchemas);
|
|
243
|
-
if (eventDetails) {
|
|
244
|
-
const [yieldSchemas, returnSchemas] = eventDetails;
|
|
245
|
-
const yieldResult = await this.convertSchemas(yieldSchemas, "output");
|
|
246
|
-
const returnResult = await this.convertSchemas(returnSchemas, "output");
|
|
247
|
-
ref.responses ??= {};
|
|
248
|
-
ref.responses[status] = {
|
|
249
|
-
description,
|
|
250
|
-
content: toEventIteratorContent(yieldResult, returnResult, doc, options)
|
|
251
|
-
};
|
|
252
|
-
return;
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
const [schema] = await this.convertSchemas(outputSchemas, "output");
|
|
256
|
-
if (isUnconstrainedSchema(schema) || outputStructure === "compact") {
|
|
257
|
-
ref.responses ??= {};
|
|
258
|
-
ref.responses[status] = {
|
|
259
|
-
description,
|
|
260
|
-
content: toBodyContent(schema, doc, options)
|
|
261
|
-
};
|
|
262
|
-
return;
|
|
263
|
-
}
|
|
264
|
-
const schemasByStatus = /* @__PURE__ */ new Map();
|
|
265
|
-
for (const item of flattenJsonUnionSchema(schema)) {
|
|
266
|
-
const objectSchemaEntries = extractJsonObjectSchemaEntries(item);
|
|
267
|
-
if (!objectSchemaEntries) {
|
|
268
|
-
throw new OpenAPIGeneratorError(
|
|
269
|
-
`Procedure at path "${path.join(".")}" has outputStructure "detailed" but its output schema is not an object.
|
|
270
|
-
Expected shape: { status: number (200-299), headers?: Record<string, unknown>, body?: unknown }`
|
|
271
|
-
);
|
|
272
|
-
}
|
|
273
|
-
const statusSchema = objectSchemaEntries?.find(([name]) => name === "status")?.[1];
|
|
274
|
-
if (statusSchema !== void 0 && (typeof statusSchema !== "object" || !Number.isInteger(statusSchema.const) || statusSchema.const < 200 || statusSchema.const >= 300)) {
|
|
275
|
-
throw new OpenAPIGeneratorError(
|
|
276
|
-
`Procedure at path "${path.join(".")}" has an invalid "status" field in its outputStructure "detailed" schema.
|
|
277
|
-
Expected: a const integer in the 200-299 range
|
|
278
|
-
Received: ${stringifyJSON(statusSchema)}`
|
|
279
|
-
);
|
|
280
|
-
}
|
|
281
|
-
const status2 = (statusSchema?.const || void 0) ?? meta?.successStatus ?? DEFAULT_SUCCESS_STATUS;
|
|
282
|
-
const description2 = statusSchema?.description;
|
|
283
|
-
const schemas = schemasByStatus.get(status2);
|
|
284
|
-
const headersSchema = objectSchemaEntries?.find(([name]) => name === "headers")?.[1];
|
|
285
|
-
const bodySchema = objectSchemaEntries?.find(([name]) => name === "body")?.[1];
|
|
286
|
-
if (schemas) {
|
|
287
|
-
schemas.push({ description: description2, headers: headersSchema, body: bodySchema });
|
|
288
|
-
} else {
|
|
289
|
-
schemasByStatus.set(status2, [{ description: description2, headers: headersSchema, body: bodySchema }]);
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
for (const [status2, schemas] of schemasByStatus.entries()) {
|
|
293
|
-
const descriptions = schemas.map(({ description: description2 }) => description2).filter((d) => d !== void 0);
|
|
294
|
-
const responseObject = {
|
|
295
|
-
description: descriptions.length ? descriptions.join(", ") : description
|
|
296
|
-
};
|
|
297
|
-
const bodySchemas = schemas.map(({ body }) => body).filter((b) => b !== void 0);
|
|
298
|
-
if (bodySchemas.length) {
|
|
299
|
-
responseObject.content = toBodyContent(combineJsonSchemasWithComposition("anyOf", bodySchemas), doc, options);
|
|
300
|
-
}
|
|
301
|
-
const headerSchemas = schemas.map(({ headers }) => headers).filter((b) => b !== void 0);
|
|
302
|
-
if (headerSchemas.length) {
|
|
303
|
-
const entries = extractJsonObjectSchemaEntries(combineJsonSchemasWithComposition("anyOf", headerSchemas));
|
|
304
|
-
entries?.forEach(([name, schema2, optional]) => {
|
|
305
|
-
responseObject.headers ??= {};
|
|
306
|
-
responseObject.headers[name] = {
|
|
307
|
-
required: optional ? void 0 : true,
|
|
308
|
-
schema: toOpenAPISchema(schema2, doc, options)
|
|
309
|
-
};
|
|
310
|
-
});
|
|
311
|
-
}
|
|
312
|
-
ref.responses ??= {};
|
|
313
|
-
ref.responses[status2] = responseObject;
|
|
314
|
-
}
|
|
105
|
+
toOpenAPISchema(schema, direction) {
|
|
106
|
+
return ensureJsonSchemaObject(this.hoistDefs(schema, direction));
|
|
315
107
|
}
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
const definitions = errorDefinitionsByStatus.get(status);
|
|
329
|
-
if (definitions) {
|
|
330
|
-
definitions.push({ code, dataJsonSchema, dataOptional, defaultMessage });
|
|
331
|
-
} else {
|
|
332
|
-
errorDefinitionsByStatus.set(status, [{ code, dataJsonSchema, dataOptional, defaultMessage }]);
|
|
108
|
+
}
|
|
109
|
+
function resolveComponentName(componentsSchemas, claimedNames, preferredName, schema, candidateSchemas, direction) {
|
|
110
|
+
let mintName;
|
|
111
|
+
for (let i = 1; ; i++) {
|
|
112
|
+
const [componentName, mintable, tail] = componentNameCandidate(preferredName, direction, i);
|
|
113
|
+
const existingSchema = componentsSchemas[componentName];
|
|
114
|
+
if (existingSchema === void 0) {
|
|
115
|
+
if (mintable && !claimedNames.has(componentName)) {
|
|
116
|
+
mintName ??= componentName;
|
|
117
|
+
if (tail) {
|
|
118
|
+
return [mintName, false];
|
|
119
|
+
}
|
|
333
120
|
}
|
|
121
|
+
continue;
|
|
334
122
|
}
|
|
335
|
-
if (
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
data: {}
|
|
347
|
-
},
|
|
348
|
-
required: ["defined", "inferable", "code", "status", "message"]
|
|
349
|
-
}
|
|
350
|
-
},
|
|
351
|
-
$ref: "#/$defs/UndefinedError"
|
|
352
|
-
}, doc, options);
|
|
353
|
-
for (const [status, definitions] of errorDefinitionsByStatus.entries()) {
|
|
354
|
-
const descriptions = definitions.map(({ defaultMessage }) => defaultMessage).filter((m) => m !== void 0);
|
|
355
|
-
const customBodySchema = value(
|
|
356
|
-
options.customErrorResponseBodySchema,
|
|
357
|
-
definitions.map((def2) => ({ ...def2, dataJsonSchema: hoistDefs(def2.dataJsonSchema, doc, options) })),
|
|
358
|
-
status
|
|
359
|
-
);
|
|
360
|
-
const responseSchema = customBodySchema ?? combineJsonSchemasWithComposition("oneOf", [
|
|
361
|
-
...definitions.map(({ code, dataJsonSchema, dataOptional, defaultMessage }) => {
|
|
362
|
-
return combineJsonObjectSchemaEntries([
|
|
363
|
-
["defined", { const: true }, false],
|
|
364
|
-
["inferable", { type: "boolean" }, false],
|
|
365
|
-
["code", { const: code }, false],
|
|
366
|
-
["status", { const: status }, false],
|
|
367
|
-
["message", { type: "string", default: defaultMessage }, false],
|
|
368
|
-
["data", dataJsonSchema, dataOptional]
|
|
369
|
-
]);
|
|
370
|
-
}),
|
|
371
|
-
undefinedErrorSchema
|
|
372
|
-
]);
|
|
373
|
-
ref.responses ??= {};
|
|
374
|
-
ref.responses[status] = {
|
|
375
|
-
description: descriptions.length ? descriptions.join(", ") : status.toString(),
|
|
376
|
-
content: {
|
|
377
|
-
"application/json": {
|
|
378
|
-
schema: toOpenAPISchema(responseSchema, doc, options)
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
};
|
|
382
|
-
}
|
|
123
|
+
if (areSchemasEquivalentForReuse(
|
|
124
|
+
schema,
|
|
125
|
+
existingSchema,
|
|
126
|
+
schema,
|
|
127
|
+
existingSchema,
|
|
128
|
+
candidateSchemas,
|
|
129
|
+
componentsSchemas,
|
|
130
|
+
/* @__PURE__ */ new Map([[preferredName, componentName]]),
|
|
131
|
+
/* @__PURE__ */ new Map([[componentName, preferredName]])
|
|
132
|
+
)) {
|
|
133
|
+
return [componentName, true];
|
|
383
134
|
}
|
|
384
135
|
}
|
|
385
136
|
}
|
|
386
|
-
function
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
doc,
|
|
390
|
-
options
|
|
391
|
-
));
|
|
392
|
-
}
|
|
393
|
-
function toOpenAPIPath(path, dynamicPathParams) {
|
|
394
|
-
if (!dynamicPathParams?.length) {
|
|
395
|
-
return path;
|
|
396
|
-
}
|
|
397
|
-
let normalized = "";
|
|
398
|
-
let currentIndex = 0;
|
|
399
|
-
for (const param of dynamicPathParams) {
|
|
400
|
-
normalized += path.slice(currentIndex, param.startIndex);
|
|
401
|
-
normalized += `{${param.parameterName}}`;
|
|
402
|
-
currentIndex = param.startIndex + param.segment.length;
|
|
403
|
-
}
|
|
404
|
-
normalized += path.slice(currentIndex);
|
|
405
|
-
return normalized;
|
|
406
|
-
}
|
|
407
|
-
function strip$schemaField(schema) {
|
|
408
|
-
if (typeof schema !== "object") {
|
|
409
|
-
return schema;
|
|
410
|
-
}
|
|
411
|
-
const { $schema, ...rest } = schema;
|
|
412
|
-
return rest;
|
|
413
|
-
}
|
|
414
|
-
function getEventIteratorDetails(schemas) {
|
|
415
|
-
if (!schemas || schemas.length === 0) {
|
|
416
|
-
return void 0;
|
|
137
|
+
function componentNameCandidate(preferredName, direction, attempt) {
|
|
138
|
+
if (attempt === 1) {
|
|
139
|
+
return [preferredName, true, false];
|
|
417
140
|
}
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
const details = getEventIteratorSchemaDetails(s);
|
|
422
|
-
if (!details) {
|
|
423
|
-
return void 0;
|
|
141
|
+
if (direction !== void 0) {
|
|
142
|
+
if (attempt === 2) {
|
|
143
|
+
return [`${preferredName}${direction === "input" ? "Input" : "Output"}`, true, false];
|
|
424
144
|
}
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
returnSchemas.push(details.returnSchema);
|
|
145
|
+
if (attempt === 3) {
|
|
146
|
+
return [`${preferredName}${direction === "input" ? "Output" : "Input"}`, false, false];
|
|
428
147
|
}
|
|
148
|
+
return [`${preferredName}${attempt - 2}`, true, true];
|
|
429
149
|
}
|
|
430
|
-
return
|
|
150
|
+
return [`${preferredName}${attempt}`, true, true];
|
|
431
151
|
}
|
|
432
|
-
function
|
|
433
|
-
|
|
434
|
-
combineJsonObjectSchemaEntries([
|
|
435
|
-
["event", { const: "message" }, false],
|
|
436
|
-
["data", yieldSchema, yieldOptional],
|
|
437
|
-
["id", { type: "string" }, true],
|
|
438
|
-
["retry", { type: "number" }, true]
|
|
439
|
-
]),
|
|
440
|
-
combineJsonObjectSchemaEntries([
|
|
441
|
-
["event", { const: "close" }, false],
|
|
442
|
-
["data", returnSchema, returnOptional],
|
|
443
|
-
["id", { type: "string" }, true],
|
|
444
|
-
["retry", { type: "number" }, true]
|
|
445
|
-
]),
|
|
446
|
-
{
|
|
447
|
-
type: "object",
|
|
448
|
-
properties: {
|
|
449
|
-
event: { const: "error" },
|
|
450
|
-
data: {},
|
|
451
|
-
id: { type: "string" },
|
|
452
|
-
retry: { type: "number" }
|
|
453
|
-
},
|
|
454
|
-
required: ["event"]
|
|
455
|
-
}
|
|
456
|
-
]);
|
|
457
|
-
return {
|
|
458
|
-
"text/event-stream": {
|
|
459
|
-
schema: toOpenAPISchema(schema, doc, options)
|
|
460
|
-
}
|
|
461
|
-
};
|
|
152
|
+
function definedKeysOf(object) {
|
|
153
|
+
return Object.keys(object).filter((key) => object[key] !== void 0).sort();
|
|
462
154
|
}
|
|
463
|
-
function
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
}
|
|
469
|
-
const contentMediaType = s.contentMediaType ?? "*/*";
|
|
470
|
-
const schemas = fileSchemasByMediaType.get(contentMediaType);
|
|
471
|
-
if (schemas) {
|
|
472
|
-
schemas.push(s);
|
|
473
|
-
} else {
|
|
474
|
-
fileSchemasByMediaType.set(contentMediaType, [s]);
|
|
475
|
-
}
|
|
155
|
+
function areSchemasEquivalentForReuse(candidate, existing, candidateRootSchema, existingRootSchema, candidateSchemas, existingSchemas, candidateToExistingComponentNames, existingToCandidateComponentNames, visited = /* @__PURE__ */ new WeakMap()) {
|
|
156
|
+
if (candidate === existing) {
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
if (typeof candidate !== typeof existing) {
|
|
476
160
|
return false;
|
|
477
|
-
});
|
|
478
|
-
const content = {};
|
|
479
|
-
if (rest.length > 0) {
|
|
480
|
-
const restSchema = fileSchemasByMediaType.size ? combineJsonSchemasWithComposition("anyOf", rest) : schema;
|
|
481
|
-
const hasNestedFiles = findDeepMatches(
|
|
482
|
-
(v) => isPlainObject(v) && isJsonFileSchema(v),
|
|
483
|
-
restSchema
|
|
484
|
-
).values.length > 0;
|
|
485
|
-
const contentType = hasNestedFiles ? "multipart/form-data" : "application/json";
|
|
486
|
-
const fileSchemas = fileSchemasByMediaType.get(contentType);
|
|
487
|
-
fileSchemasByMediaType.delete(contentType);
|
|
488
|
-
content[contentType] = {
|
|
489
|
-
schema: toOpenAPISchema(combineJsonSchemasWithComposition("anyOf", [restSchema, ...toArray(fileSchemas)]), doc, options)
|
|
490
|
-
};
|
|
491
161
|
}
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
schema: toOpenAPISchema(combineJsonSchemasWithComposition("anyOf", schemas), doc, options)
|
|
495
|
-
};
|
|
162
|
+
if (candidate === null || existing === null) {
|
|
163
|
+
return candidate === existing;
|
|
496
164
|
}
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
function hoistDefs(schema, doc, options) {
|
|
500
|
-
if (typeof schema !== "object") {
|
|
501
|
-
return schema;
|
|
165
|
+
if (typeof candidate !== "object" || typeof existing !== "object") {
|
|
166
|
+
return isDeepEqual(candidate, existing);
|
|
502
167
|
}
|
|
503
|
-
|
|
504
|
-
|
|
168
|
+
const seenExisting = visited.get(candidate);
|
|
169
|
+
if (seenExisting?.has(existing)) {
|
|
170
|
+
return true;
|
|
505
171
|
}
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
const normalized = normalizeHoistedDefSchema(defSchema);
|
|
515
|
-
if (value(options.shouldHoistDef, defName, normalized) !== false) {
|
|
516
|
-
hoistedDefs[defName] = normalized;
|
|
517
|
-
} else {
|
|
518
|
-
localDefs[defName] = normalized;
|
|
172
|
+
if (seenExisting) {
|
|
173
|
+
seenExisting.add(existing);
|
|
174
|
+
} else {
|
|
175
|
+
visited.set(candidate, new WeakSet([existing]));
|
|
176
|
+
}
|
|
177
|
+
if (Array.isArray(candidate) || Array.isArray(existing)) {
|
|
178
|
+
if (!Array.isArray(candidate) || !Array.isArray(existing) || candidate.length !== existing.length) {
|
|
179
|
+
return false;
|
|
519
180
|
}
|
|
181
|
+
return candidate.every((item, index) => areSchemasEquivalentForReuse(
|
|
182
|
+
item,
|
|
183
|
+
existing[index],
|
|
184
|
+
candidateRootSchema,
|
|
185
|
+
existingRootSchema,
|
|
186
|
+
candidateSchemas,
|
|
187
|
+
existingSchemas,
|
|
188
|
+
candidateToExistingComponentNames,
|
|
189
|
+
existingToCandidateComponentNames,
|
|
190
|
+
visited
|
|
191
|
+
));
|
|
520
192
|
}
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
const componentsSchemas = doc.components.schemas;
|
|
528
|
-
const identityRenameMap = Object.fromEntries(
|
|
529
|
-
Object.keys(hoistedDefs).map((defName) => [defName, defName])
|
|
530
|
-
);
|
|
531
|
-
const renameMap = {};
|
|
532
|
-
const pendingSchemas = [];
|
|
533
|
-
for (const defName of Object.keys(hoistedDefs)) {
|
|
534
|
-
const cleanSchema = hoistedDefs[defName];
|
|
535
|
-
const existingSchema = componentsSchemas[defName];
|
|
536
|
-
const candidateSchemas = Object.fromEntries(
|
|
537
|
-
Object.keys(hoistedDefs).map((currentDefName) => [
|
|
538
|
-
currentDefName,
|
|
539
|
-
rewriteComponentSchemaRefs(
|
|
540
|
-
withReferencedLocalDefs(hoistedDefs[currentDefName], localDefs),
|
|
541
|
-
{
|
|
542
|
-
...identityRenameMap,
|
|
543
|
-
...renameMap
|
|
544
|
-
}
|
|
545
|
-
)
|
|
546
|
-
])
|
|
547
|
-
);
|
|
548
|
-
const prelimSchema = candidateSchemas[defName];
|
|
549
|
-
if (existingSchema !== void 0) {
|
|
550
|
-
const reusableComponentName = findReusableComponentName(componentsSchemas, defName, prelimSchema, candidateSchemas);
|
|
551
|
-
if (reusableComponentName !== void 0) {
|
|
552
|
-
renameMap[defName] = reusableComponentName;
|
|
553
|
-
continue;
|
|
554
|
-
}
|
|
555
|
-
const componentName = findUniqueComponentName(componentsSchemas, defName);
|
|
556
|
-
renameMap[defName] = componentName;
|
|
557
|
-
pendingSchemas.push({ cleanSchema, componentName });
|
|
558
|
-
} else {
|
|
559
|
-
const reusableComponentName = findReusableComponentName(componentsSchemas, defName, prelimSchema, candidateSchemas);
|
|
560
|
-
if (reusableComponentName !== void 0) {
|
|
561
|
-
renameMap[defName] = reusableComponentName;
|
|
562
|
-
continue;
|
|
563
|
-
}
|
|
564
|
-
renameMap[defName] = defName;
|
|
565
|
-
pendingSchemas.push({ cleanSchema, componentName: defName });
|
|
566
|
-
}
|
|
567
|
-
}
|
|
568
|
-
for (const { cleanSchema, componentName } of pendingSchemas) {
|
|
569
|
-
componentsSchemas[componentName] = rewriteComponentSchemaRefs(
|
|
570
|
-
withReferencedLocalDefs(cleanSchema, localDefs),
|
|
571
|
-
renameMap
|
|
572
|
-
);
|
|
573
|
-
}
|
|
574
|
-
return rewriteComponentSchemaRefs(withReferencedLocalDefs(rest, localDefs), renameMap);
|
|
575
|
-
}
|
|
576
|
-
function normalizeHoistedDefSchema(schema) {
|
|
577
|
-
let cleanSchema = typeof schema === "boolean" ? schema ? {} : { not: {} } : { ...schema };
|
|
578
|
-
if (cleanSchema.additionalProperties === false) {
|
|
579
|
-
const { additionalProperties: _ignored, ...withoutAdditionalProperties } = cleanSchema;
|
|
580
|
-
cleanSchema = withoutAdditionalProperties;
|
|
581
|
-
}
|
|
582
|
-
return cleanSchema;
|
|
583
|
-
}
|
|
584
|
-
function hoistReferencedLocalDefs(hoistedDefs, localDefs) {
|
|
585
|
-
const queue = Object.values(hoistedDefs);
|
|
586
|
-
while (queue.length > 0) {
|
|
587
|
-
const current = queue.shift();
|
|
588
|
-
if (current === void 0) {
|
|
589
|
-
continue;
|
|
590
|
-
}
|
|
591
|
-
visitSchemaRefs(current, (refName) => {
|
|
592
|
-
const referenced = localDefs[refName];
|
|
593
|
-
if (referenced === void 0) {
|
|
594
|
-
return;
|
|
595
|
-
}
|
|
596
|
-
hoistedDefs[refName] = referenced;
|
|
597
|
-
delete localDefs[refName];
|
|
598
|
-
queue.push(referenced);
|
|
599
|
-
});
|
|
600
|
-
}
|
|
601
|
-
}
|
|
602
|
-
function withReferencedLocalDefs(schema, localDefs) {
|
|
603
|
-
const referencedLocalDefs = collectReferencedLocalDefNames(schema, localDefs);
|
|
604
|
-
if (referencedLocalDefs.length === 0) {
|
|
605
|
-
return schema;
|
|
606
|
-
}
|
|
607
|
-
const mergedDefs = {
|
|
608
|
-
...schema.$defs
|
|
609
|
-
};
|
|
610
|
-
for (const defName of referencedLocalDefs) {
|
|
611
|
-
mergedDefs[defName] = localDefs[defName];
|
|
612
|
-
}
|
|
613
|
-
return {
|
|
614
|
-
...schema,
|
|
615
|
-
$defs: mergedDefs
|
|
616
|
-
};
|
|
617
|
-
}
|
|
618
|
-
function collectReferencedLocalDefNames(schema, localDefs) {
|
|
619
|
-
if (Object.keys(localDefs).length === 0) {
|
|
620
|
-
return [];
|
|
621
|
-
}
|
|
622
|
-
const referenced = /* @__PURE__ */ new Set();
|
|
623
|
-
const queued = /* @__PURE__ */ new Set();
|
|
624
|
-
const queue = [schema];
|
|
625
|
-
while (queue.length > 0) {
|
|
626
|
-
const current = queue.shift();
|
|
627
|
-
if (current === void 0) {
|
|
628
|
-
continue;
|
|
629
|
-
}
|
|
630
|
-
visitSchemaRefs(current, (refName) => {
|
|
631
|
-
if (localDefs[refName] === void 0 || referenced.has(refName)) {
|
|
632
|
-
return;
|
|
633
|
-
}
|
|
634
|
-
referenced.add(refName);
|
|
635
|
-
if (!queued.has(refName)) {
|
|
636
|
-
queued.add(refName);
|
|
637
|
-
queue.push(localDefs[refName]);
|
|
638
|
-
}
|
|
639
|
-
});
|
|
640
|
-
}
|
|
641
|
-
return [...referenced];
|
|
642
|
-
}
|
|
643
|
-
function visitSchemaRefs(schema, onRef, seen = /* @__PURE__ */ new Set()) {
|
|
644
|
-
if (typeof schema !== "object" || schema === null) {
|
|
645
|
-
return;
|
|
646
|
-
}
|
|
647
|
-
if (seen.has(schema)) {
|
|
648
|
-
return;
|
|
649
|
-
}
|
|
650
|
-
seen.add(schema);
|
|
651
|
-
if (typeof schema.$ref === "string") {
|
|
652
|
-
const refName = parseLocalDefRefName(schema.$ref);
|
|
653
|
-
if (refName !== void 0) {
|
|
654
|
-
onRef(refName);
|
|
655
|
-
}
|
|
656
|
-
}
|
|
657
|
-
for (const keyword of ["allOf", "anyOf", "oneOf"]) {
|
|
658
|
-
if (Array.isArray(schema[keyword])) {
|
|
659
|
-
for (const item of schema[keyword]) {
|
|
660
|
-
visitSchemaRefs(item, onRef, seen);
|
|
661
|
-
}
|
|
662
|
-
}
|
|
663
|
-
}
|
|
664
|
-
if (schema.properties) {
|
|
665
|
-
for (const property of Object.values(schema.properties)) {
|
|
666
|
-
visitSchemaRefs(property, onRef, seen);
|
|
667
|
-
}
|
|
668
|
-
}
|
|
669
|
-
if (schema.items !== void 0) {
|
|
670
|
-
visitSchemaRefs(schema.items, onRef, seen);
|
|
671
|
-
}
|
|
672
|
-
if (typeof schema.additionalProperties === "object" && schema.additionalProperties !== null) {
|
|
673
|
-
visitSchemaRefs(schema.additionalProperties, onRef, seen);
|
|
674
|
-
}
|
|
675
|
-
if (schema.not !== void 0) {
|
|
676
|
-
visitSchemaRefs(schema.not, onRef, seen);
|
|
677
|
-
}
|
|
678
|
-
if (schema.if !== void 0) {
|
|
679
|
-
visitSchemaRefs(schema.if, onRef, seen);
|
|
680
|
-
}
|
|
681
|
-
if (schema.then !== void 0) {
|
|
682
|
-
visitSchemaRefs(schema.then, onRef, seen);
|
|
683
|
-
}
|
|
684
|
-
if (schema.else !== void 0) {
|
|
685
|
-
visitSchemaRefs(schema.else, onRef, seen);
|
|
686
|
-
}
|
|
687
|
-
if (Array.isArray(schema.prefixItems)) {
|
|
688
|
-
for (const item of schema.prefixItems) {
|
|
689
|
-
visitSchemaRefs(item, onRef, seen);
|
|
690
|
-
}
|
|
691
|
-
}
|
|
692
|
-
if (schema.$defs) {
|
|
693
|
-
for (const def of Object.values(schema.$defs)) {
|
|
694
|
-
if (def !== void 0) {
|
|
695
|
-
visitSchemaRefs(def, onRef, seen);
|
|
696
|
-
}
|
|
697
|
-
}
|
|
698
|
-
}
|
|
699
|
-
}
|
|
700
|
-
function findUniqueComponentName(componentsSchemas, baseName) {
|
|
701
|
-
const candidate = `${baseName}`;
|
|
702
|
-
if (componentsSchemas[candidate] === void 0)
|
|
703
|
-
return candidate;
|
|
704
|
-
let i = 2;
|
|
705
|
-
while (componentsSchemas[`${baseName}${i}`] !== void 0) {
|
|
706
|
-
i++;
|
|
707
|
-
}
|
|
708
|
-
return `${baseName}${i}`;
|
|
709
|
-
}
|
|
710
|
-
function findReusableComponentName(componentsSchemas, defName, schema, candidateSchemas) {
|
|
711
|
-
const exactMatch = componentsSchemas[defName];
|
|
712
|
-
if (exactMatch !== void 0 && areSchemasEquivalentForReuse(
|
|
713
|
-
schema,
|
|
714
|
-
exactMatch,
|
|
715
|
-
schema,
|
|
716
|
-
exactMatch,
|
|
717
|
-
candidateSchemas,
|
|
718
|
-
componentsSchemas,
|
|
719
|
-
/* @__PURE__ */ new Map([[defName, defName]]),
|
|
720
|
-
/* @__PURE__ */ new Map([[defName, defName]])
|
|
721
|
-
)) {
|
|
722
|
-
return defName;
|
|
723
|
-
}
|
|
724
|
-
for (const [componentName, componentSchema] of Object.entries(componentsSchemas)) {
|
|
725
|
-
if (componentName === defName) {
|
|
726
|
-
continue;
|
|
727
|
-
}
|
|
728
|
-
if (areSchemasEquivalentForReuse(
|
|
729
|
-
schema,
|
|
730
|
-
componentSchema,
|
|
731
|
-
schema,
|
|
732
|
-
componentSchema,
|
|
733
|
-
candidateSchemas,
|
|
734
|
-
componentsSchemas,
|
|
735
|
-
/* @__PURE__ */ new Map([[defName, componentName]]),
|
|
736
|
-
/* @__PURE__ */ new Map([[componentName, defName]])
|
|
737
|
-
)) {
|
|
738
|
-
return componentName;
|
|
739
|
-
}
|
|
740
|
-
}
|
|
741
|
-
return void 0;
|
|
742
|
-
}
|
|
743
|
-
function areSchemasEquivalentForReuse(candidate, existing, candidateRootSchema, existingRootSchema, candidateSchemas, existingSchemas, candidateToExistingComponentNames, existingToCandidateComponentNames, visited = /* @__PURE__ */ new WeakMap()) {
|
|
744
|
-
if (candidate === existing) {
|
|
745
|
-
return true;
|
|
746
|
-
}
|
|
747
|
-
if (typeof candidate !== typeof existing) {
|
|
748
|
-
return false;
|
|
749
|
-
}
|
|
750
|
-
if (candidate === null || existing === null) {
|
|
751
|
-
return candidate === existing;
|
|
752
|
-
}
|
|
753
|
-
if (typeof candidate !== "object" || typeof existing !== "object") {
|
|
754
|
-
return isDeepEqual(candidate, existing);
|
|
755
|
-
}
|
|
756
|
-
const seenExisting = visited.get(candidate);
|
|
757
|
-
if (seenExisting?.has(existing)) {
|
|
758
|
-
return true;
|
|
759
|
-
}
|
|
760
|
-
if (seenExisting) {
|
|
761
|
-
seenExisting.add(existing);
|
|
762
|
-
} else {
|
|
763
|
-
visited.set(candidate, new WeakSet([existing]));
|
|
764
|
-
}
|
|
765
|
-
if (Array.isArray(candidate) || Array.isArray(existing)) {
|
|
766
|
-
if (!Array.isArray(candidate) || !Array.isArray(existing) || candidate.length !== existing.length) {
|
|
767
|
-
return false;
|
|
768
|
-
}
|
|
769
|
-
return candidate.every((item, index) => areSchemasEquivalentForReuse(
|
|
770
|
-
item,
|
|
771
|
-
existing[index],
|
|
772
|
-
candidateRootSchema,
|
|
773
|
-
existingRootSchema,
|
|
774
|
-
candidateSchemas,
|
|
775
|
-
existingSchemas,
|
|
776
|
-
candidateToExistingComponentNames,
|
|
777
|
-
existingToCandidateComponentNames,
|
|
778
|
-
visited
|
|
779
|
-
));
|
|
780
|
-
}
|
|
781
|
-
const candidateObject = candidate;
|
|
782
|
-
const existingObject = existing;
|
|
783
|
-
const candidateKeys = Object.keys(candidateObject).sort();
|
|
784
|
-
const existingKeys = Object.keys(existingObject).sort();
|
|
785
|
-
if (!isDeepEqual(candidateKeys, existingKeys)) {
|
|
786
|
-
return false;
|
|
193
|
+
const candidateObject = candidate;
|
|
194
|
+
const existingObject = existing;
|
|
195
|
+
const candidateKeys = definedKeysOf(candidateObject);
|
|
196
|
+
const existingKeys = definedKeysOf(existingObject);
|
|
197
|
+
if (!isDeepEqual(candidateKeys, existingKeys)) {
|
|
198
|
+
return false;
|
|
787
199
|
}
|
|
788
200
|
return candidateKeys.every((key) => {
|
|
789
201
|
const candidateValue = candidateObject[key];
|
|
@@ -898,4 +310,550 @@ function rewriteComponentSchemaRefs(schema, renameMap) {
|
|
|
898
310
|
});
|
|
899
311
|
}
|
|
900
312
|
|
|
901
|
-
|
|
313
|
+
class OpenAPIGeneratorError extends TypeError {
|
|
314
|
+
}
|
|
315
|
+
function toOpenAPIPath(path, dynamicPathParams) {
|
|
316
|
+
if (!dynamicPathParams?.length) {
|
|
317
|
+
return path;
|
|
318
|
+
}
|
|
319
|
+
let normalized = "";
|
|
320
|
+
let currentIndex = 0;
|
|
321
|
+
for (const param of dynamicPathParams) {
|
|
322
|
+
normalized += path.slice(currentIndex, param.startIndex);
|
|
323
|
+
normalized += `{${param.parameterName}}`;
|
|
324
|
+
currentIndex = param.startIndex + param.segment.length;
|
|
325
|
+
}
|
|
326
|
+
normalized += path.slice(currentIndex);
|
|
327
|
+
return normalized;
|
|
328
|
+
}
|
|
329
|
+
function buildRequest(ctx, operation, def, meta, dynamicPathParams) {
|
|
330
|
+
const method = meta?.method ?? DEFAULT_OPENAPI_METHOD;
|
|
331
|
+
const inputStructure = meta?.inputStructure ?? DEFAULT_OPENAPI_INPUT_STRUCTURE;
|
|
332
|
+
if (inputStructure === "compact") {
|
|
333
|
+
const iteratorDetails = getAsyncIteratorObjectDetails(def.inputSchemas);
|
|
334
|
+
if (iteratorDetails) {
|
|
335
|
+
operation.requestBody = {
|
|
336
|
+
required: true,
|
|
337
|
+
content: toAsyncIteratorObjectContent(
|
|
338
|
+
ctx,
|
|
339
|
+
"input",
|
|
340
|
+
ctx.convertSchemas(iteratorDetails[0], "input"),
|
|
341
|
+
ctx.convertSchemas(iteratorDetails[1], "input")
|
|
342
|
+
)
|
|
343
|
+
};
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
const dynamicParams = dynamicPathParams?.map((v) => v.parameterName);
|
|
348
|
+
const [schema, optional] = ctx.convertSchemas(def.inputSchemas, "input");
|
|
349
|
+
if (isUnconstrainedSchema(schema) && !dynamicParams?.length) {
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
const parts = inputStructure === "compact" ? extractCompactRequestParts(schema, optional, method, dynamicParams) : extractDetailedRequestParts(schema);
|
|
353
|
+
renderPathParameters(ctx, operation, dynamicParams, parts.paramsEntries, meta?.paramsStyles);
|
|
354
|
+
renderQueryParameters(ctx, operation, parts.queryEntries, meta?.queryStyles);
|
|
355
|
+
renderHeaderParameters(ctx, operation, parts.headersEntries);
|
|
356
|
+
if (parts.bodySchema !== void 0) {
|
|
357
|
+
operation.requestBody = {
|
|
358
|
+
required: parts.bodyOptional ? void 0 : true,
|
|
359
|
+
content: toBodyContent(ctx, "input", parts.bodySchema)
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
function extractCompactRequestParts(schema, optional, method, dynamicParams) {
|
|
364
|
+
const entries = extractJsonObjectSchemaEntries(schema);
|
|
365
|
+
if (!entries && isBodylessMethod(method)) {
|
|
366
|
+
throw new OpenAPIGeneratorError(
|
|
367
|
+
`method is ${method} but the input schema is not an object.
|
|
368
|
+
${method} sends every input field as a query parameter, so the input must be an object schema.
|
|
369
|
+
Fix: make the input an object, or use a method with a request body (POST, PUT, PATCH, DELETE).`
|
|
370
|
+
);
|
|
371
|
+
}
|
|
372
|
+
const paramsEntries = entries?.filter(([name]) => dynamicParams?.includes(name));
|
|
373
|
+
const restEntries = entries?.filter(([name]) => !dynamicParams?.includes(name));
|
|
374
|
+
const hasBody = !isBodylessMethod(method);
|
|
375
|
+
const bodySchema = !hasBody ? void 0 : !dynamicParams?.length ? schema : restEntries ? combineJsonObjectSchemaEntries(restEntries) : void 0;
|
|
376
|
+
return {
|
|
377
|
+
paramsEntries,
|
|
378
|
+
queryEntries: isBodylessMethod(method) ? restEntries : void 0,
|
|
379
|
+
headersEntries: void 0,
|
|
380
|
+
bodySchema,
|
|
381
|
+
bodyOptional: !dynamicParams?.length ? optional : restEntries?.every(([, , optional2]) => optional2)
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
function extractDetailedRequestParts(schema) {
|
|
385
|
+
const entries = extractJsonObjectSchemaEntries(schema);
|
|
386
|
+
if (!entries) {
|
|
387
|
+
throw new OpenAPIGeneratorError(
|
|
388
|
+
`inputStructure is "detailed" but the input schema is not an object.
|
|
389
|
+
Expected an object shaped like: { params?: object, query?: object, headers?: object, body?: unknown }`
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
const section = (name) => entries.find(([entryName]) => entryName === name);
|
|
393
|
+
return {
|
|
394
|
+
paramsEntries: extractJsonObjectSchemaEntries(section("params")?.[1] ?? false),
|
|
395
|
+
queryEntries: extractJsonObjectSchemaEntries(section("query")?.[1] ?? false),
|
|
396
|
+
headersEntries: extractJsonObjectSchemaEntries(section("headers")?.[1] ?? false),
|
|
397
|
+
bodySchema: section("body")?.[1],
|
|
398
|
+
bodyOptional: section("body")?.[2]
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
function renderPathParameters(ctx, operation, dynamicParams, paramsEntries, paramsStyles) {
|
|
402
|
+
if (!dynamicParams?.length) {
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
if (!paramsEntries) {
|
|
406
|
+
throw new OpenAPIGeneratorError(
|
|
407
|
+
`the route declares path params (${dynamicParams.map((p) => `{${p}}`).join(", ")}) but there is no object schema to source them from.
|
|
408
|
+
compact mode: the input schema must be an object containing each param.
|
|
409
|
+
detailed mode: the input's "params" section must be an object containing each param.`
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
for (const name of dynamicParams) {
|
|
413
|
+
const entry = paramsEntries.find(([entryName]) => entryName === name);
|
|
414
|
+
if (!entry) {
|
|
415
|
+
throw new OpenAPIGeneratorError(
|
|
416
|
+
`dynamic param "{${name}}" is missing from the input schema.
|
|
417
|
+
Route params: ${dynamicParams.map((p) => `{${p}}`).join(", ")}
|
|
418
|
+
Schema keys: ${paramsEntries.map(([n]) => n).join(", ") || "(none)"}`
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
if (entry[2]) {
|
|
422
|
+
throw new OpenAPIGeneratorError(
|
|
423
|
+
`dynamic param "${name}" is optional in the input schema.
|
|
424
|
+
OpenAPI requires path params to be required. Make "${name}" required.`
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
const style = paramsStyles?.[name];
|
|
428
|
+
const parameter = {
|
|
429
|
+
in: "path",
|
|
430
|
+
required: true,
|
|
431
|
+
name,
|
|
432
|
+
schema: ctx.registry.toOpenAPISchema(entry[1], "input")
|
|
433
|
+
};
|
|
434
|
+
if (style === "comma-delimited-array" || style === "comma-delimited-object") {
|
|
435
|
+
parameter.style = "simple";
|
|
436
|
+
parameter.explode = false;
|
|
437
|
+
}
|
|
438
|
+
operation.parameters ??= [];
|
|
439
|
+
operation.parameters.push(parameter);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
function renderQueryParameters(ctx, operation, queryEntries, queryStyles) {
|
|
443
|
+
for (const [name, schema, optional] of queryEntries ?? []) {
|
|
444
|
+
const style = queryStyles?.[name];
|
|
445
|
+
const parameter = {
|
|
446
|
+
in: "query",
|
|
447
|
+
name,
|
|
448
|
+
schema: ctx.registry.toOpenAPISchema(schema, "input"),
|
|
449
|
+
allowEmptyValue: true,
|
|
450
|
+
allowReserved: true
|
|
451
|
+
};
|
|
452
|
+
if (!optional) {
|
|
453
|
+
parameter.required = true;
|
|
454
|
+
}
|
|
455
|
+
if (style === "comma-delimited-array" || style === "comma-delimited-object") {
|
|
456
|
+
parameter.explode = false;
|
|
457
|
+
} else if (style === "pipe-delimited-array" || style === "pipe-delimited-object") {
|
|
458
|
+
parameter.style = "pipeDelimited";
|
|
459
|
+
} else if (style === "space-delimited-array" || style === "space-delimited-object") {
|
|
460
|
+
parameter.style = "spaceDelimited";
|
|
461
|
+
} else if (style === "json") {
|
|
462
|
+
parameter.content = {
|
|
463
|
+
"application/json": { schema: parameter.schema }
|
|
464
|
+
};
|
|
465
|
+
delete parameter.schema;
|
|
466
|
+
} else if (style === void 0) {
|
|
467
|
+
if (flattenJsonUnionSchema(schema).some((s) => !isJsonPrimitiveSchema(s))) {
|
|
468
|
+
const arrayable = matchArrayableJsonSchema(schema);
|
|
469
|
+
if (!arrayable || flattenJsonUnionSchema(arrayable[0]).some((s) => !isJsonPrimitiveSchema(s))) {
|
|
470
|
+
parameter.style = "deepObject";
|
|
471
|
+
parameter.explode = true;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
} else ;
|
|
475
|
+
operation.parameters ??= [];
|
|
476
|
+
operation.parameters.push(parameter);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
function renderHeaderParameters(ctx, operation, headersEntries) {
|
|
480
|
+
for (const [name, schema, optional] of headersEntries ?? []) {
|
|
481
|
+
operation.parameters ??= [];
|
|
482
|
+
operation.parameters.push({
|
|
483
|
+
in: "header",
|
|
484
|
+
name,
|
|
485
|
+
required: optional ? void 0 : true,
|
|
486
|
+
schema: ctx.registry.toOpenAPISchema(schema, "input")
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
function buildSuccessResponse(ctx, operation, def, meta) {
|
|
491
|
+
const status = meta?.successStatus ?? DEFAULT_SUCCESS_STATUS;
|
|
492
|
+
const description = meta?.successDescription ?? DEFAULT_OPENAPI_SUCCESS_DESCRIPTION;
|
|
493
|
+
const outputStructure = meta?.outputStructure ?? DEFAULT_OPENAPI_OUTPUT_STRUCTURE;
|
|
494
|
+
if (outputStructure === "compact") {
|
|
495
|
+
const iteratorDetails = getAsyncIteratorObjectDetails(def.outputSchemas);
|
|
496
|
+
if (iteratorDetails) {
|
|
497
|
+
operation.responses ??= {};
|
|
498
|
+
operation.responses[status] = {
|
|
499
|
+
description,
|
|
500
|
+
content: toAsyncIteratorObjectContent(
|
|
501
|
+
ctx,
|
|
502
|
+
"output",
|
|
503
|
+
ctx.convertSchemas(iteratorDetails[0], "output"),
|
|
504
|
+
ctx.convertSchemas(iteratorDetails[1], "output")
|
|
505
|
+
)
|
|
506
|
+
};
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
const [schema] = ctx.convertSchemas(def.outputSchemas, "output");
|
|
511
|
+
if (isUnconstrainedSchema(schema) || outputStructure === "compact") {
|
|
512
|
+
operation.responses ??= {};
|
|
513
|
+
operation.responses[status] = {
|
|
514
|
+
description,
|
|
515
|
+
content: toBodyContent(ctx, "output", schema)
|
|
516
|
+
};
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
for (const [responseStatus, parts] of extractDetailedResponseParts(schema, status)) {
|
|
520
|
+
const responseObject = {
|
|
521
|
+
description: parts.descriptions.length ? parts.descriptions.join(", ") : description
|
|
522
|
+
};
|
|
523
|
+
if (parts.bodies.length) {
|
|
524
|
+
responseObject.content = toBodyContent(ctx, "output", combineJsonSchemasWithComposition("anyOf", parts.bodies));
|
|
525
|
+
}
|
|
526
|
+
if (parts.headers.length) {
|
|
527
|
+
const entries = extractJsonObjectSchemaEntries(combineJsonSchemasWithComposition("anyOf", parts.headers));
|
|
528
|
+
entries?.forEach(([name, schema2, optional]) => {
|
|
529
|
+
responseObject.headers ??= {};
|
|
530
|
+
responseObject.headers[name] = {
|
|
531
|
+
required: optional ? void 0 : true,
|
|
532
|
+
schema: ctx.registry.toOpenAPISchema(schema2, "output")
|
|
533
|
+
};
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
operation.responses ??= {};
|
|
537
|
+
operation.responses[responseStatus] = responseObject;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
function extractDetailedResponseParts(schema, defaultStatus) {
|
|
541
|
+
const partsByStatus = /* @__PURE__ */ new Map();
|
|
542
|
+
for (const item of flattenJsonUnionSchema(schema)) {
|
|
543
|
+
const entries = extractJsonObjectSchemaEntries(item);
|
|
544
|
+
if (!entries) {
|
|
545
|
+
throw new OpenAPIGeneratorError(
|
|
546
|
+
`outputStructure is "detailed" but the output schema (or one of its union members) is not an object.
|
|
547
|
+
Expected each member shaped like: { status?: number (< 400), headers?: object, body?: unknown }`
|
|
548
|
+
);
|
|
549
|
+
}
|
|
550
|
+
const statusSchema = entries.find(([name]) => name === "status")?.[1];
|
|
551
|
+
if (statusSchema !== void 0 && (typeof statusSchema !== "object" || !Number.isInteger(statusSchema.const) || statusSchema.const >= 400)) {
|
|
552
|
+
throw new OpenAPIGeneratorError(
|
|
553
|
+
`invalid "status" field in the detailed output schema.
|
|
554
|
+
Expected: a literal (const) integer below 400
|
|
555
|
+
Received: ${stringifyJSON(statusSchema)}`
|
|
556
|
+
);
|
|
557
|
+
}
|
|
558
|
+
const status = (statusSchema?.const || void 0) ?? defaultStatus;
|
|
559
|
+
let parts = partsByStatus.get(status);
|
|
560
|
+
if (!parts) {
|
|
561
|
+
parts = { descriptions: [], bodies: [], headers: [] };
|
|
562
|
+
partsByStatus.set(status, parts);
|
|
563
|
+
}
|
|
564
|
+
if (statusSchema?.description !== void 0) {
|
|
565
|
+
parts.descriptions.push(statusSchema.description);
|
|
566
|
+
}
|
|
567
|
+
const headersSchema = entries.find(([name]) => name === "headers")?.[1];
|
|
568
|
+
if (headersSchema !== void 0) {
|
|
569
|
+
parts.headers.push(headersSchema);
|
|
570
|
+
}
|
|
571
|
+
const bodySchema = entries.find(([name]) => name === "body")?.[1];
|
|
572
|
+
if (bodySchema !== void 0) {
|
|
573
|
+
parts.bodies.push(bodySchema);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
return partsByStatus;
|
|
577
|
+
}
|
|
578
|
+
function buildErrorResponse(ctx, operation, def) {
|
|
579
|
+
const definitionsByStatus = /* @__PURE__ */ new Map();
|
|
580
|
+
for (const code in def.errorMap) {
|
|
581
|
+
const config = def.errorMap[code];
|
|
582
|
+
if (!config) {
|
|
583
|
+
continue;
|
|
584
|
+
}
|
|
585
|
+
const status = ctx.errorStatusMap[code] ?? DEFAULT_ERROR_STATUS;
|
|
586
|
+
const [dataJsonSchema, dataOptional] = ctx.convertSchemas(config.data !== void 0 ? [config.data] : void 0, "output");
|
|
587
|
+
let definitions = definitionsByStatus.get(status);
|
|
588
|
+
if (!definitions) {
|
|
589
|
+
definitions = [];
|
|
590
|
+
definitionsByStatus.set(status, definitions);
|
|
591
|
+
}
|
|
592
|
+
definitions.push({ code, dataJsonSchema, dataOptional, defaultMessage: config.message });
|
|
593
|
+
}
|
|
594
|
+
if (!definitionsByStatus.size) {
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
const undefinedErrorSchema = ctx.registry.register("UndefinedError", {
|
|
598
|
+
type: "object",
|
|
599
|
+
properties: {
|
|
600
|
+
defined: { const: false },
|
|
601
|
+
inferable: { type: "boolean" },
|
|
602
|
+
code: { type: "string" },
|
|
603
|
+
status: { type: "number" },
|
|
604
|
+
message: { type: "string" },
|
|
605
|
+
data: {}
|
|
606
|
+
},
|
|
607
|
+
required: ["defined", "inferable", "code", "status", "message"]
|
|
608
|
+
});
|
|
609
|
+
for (const [status, definitions] of definitionsByStatus.entries()) {
|
|
610
|
+
const descriptions = definitions.map(({ defaultMessage }) => defaultMessage).filter((m) => m !== void 0);
|
|
611
|
+
const customBodySchema = value(
|
|
612
|
+
ctx.customErrorResponseBodySchema,
|
|
613
|
+
definitions.map((def2) => ({ ...def2, dataJsonSchema: ctx.registry.hoistDefs(def2.dataJsonSchema, "output") })),
|
|
614
|
+
status
|
|
615
|
+
);
|
|
616
|
+
const responseSchema = customBodySchema ?? combineJsonSchemasWithComposition("oneOf", [
|
|
617
|
+
...definitions.map(({ code, dataJsonSchema, dataOptional }) => {
|
|
618
|
+
return ctx.registry.register(toErrorComponentName(code), combineJsonObjectSchemaEntries([
|
|
619
|
+
["defined", { const: true }, false],
|
|
620
|
+
["inferable", { type: "boolean" }, false],
|
|
621
|
+
["code", { const: code }, false],
|
|
622
|
+
["status", { const: status }, false],
|
|
623
|
+
// avoid using the defaultMessage here to improve component reusability
|
|
624
|
+
["message", { type: "string" }, false],
|
|
625
|
+
["data", ctx.registry.hoistDefs(dataJsonSchema, "output"), dataOptional]
|
|
626
|
+
]));
|
|
627
|
+
}),
|
|
628
|
+
undefinedErrorSchema
|
|
629
|
+
]);
|
|
630
|
+
operation.responses ??= {};
|
|
631
|
+
operation.responses[status] = {
|
|
632
|
+
description: descriptions.length ? descriptions.join(", ") : status.toString(),
|
|
633
|
+
content: {
|
|
634
|
+
"application/json": {
|
|
635
|
+
schema: ctx.registry.toOpenAPISchema(responseSchema, "output")
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
function toErrorComponentName(code) {
|
|
642
|
+
const name = code.split(/[^a-z0-9]+/i).filter(Boolean).map((part) => {
|
|
643
|
+
const rest = part.slice(1);
|
|
644
|
+
return part.charAt(0).toUpperCase() + (rest === rest.toUpperCase() ? rest.toLowerCase() : rest);
|
|
645
|
+
}).join("");
|
|
646
|
+
return name || "Error";
|
|
647
|
+
}
|
|
648
|
+
function getAsyncIteratorObjectDetails(schemas) {
|
|
649
|
+
if (!schemas || schemas.length === 0) {
|
|
650
|
+
return void 0;
|
|
651
|
+
}
|
|
652
|
+
const yieldSchemas = [];
|
|
653
|
+
const returnSchemas = [];
|
|
654
|
+
for (const s of schemas) {
|
|
655
|
+
const details = getAsyncIteratorObjectSchemaDetails(s);
|
|
656
|
+
if (!details) {
|
|
657
|
+
return void 0;
|
|
658
|
+
}
|
|
659
|
+
yieldSchemas.push(details.yieldSchema);
|
|
660
|
+
if (details.returnSchema) {
|
|
661
|
+
returnSchemas.push(details.returnSchema);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
return [yieldSchemas, returnSchemas];
|
|
665
|
+
}
|
|
666
|
+
function toAsyncIteratorObjectContent(ctx, direction, [yieldSchema, yieldOptional], [returnSchema, returnOptional]) {
|
|
667
|
+
const schema = combineJsonSchemasWithComposition("oneOf", [
|
|
668
|
+
combineJsonObjectSchemaEntries([
|
|
669
|
+
["event", { const: "message" }, false],
|
|
670
|
+
["data", yieldSchema, yieldOptional],
|
|
671
|
+
["id", { type: "string" }, true],
|
|
672
|
+
["retry", { type: "number" }, true]
|
|
673
|
+
]),
|
|
674
|
+
combineJsonObjectSchemaEntries([
|
|
675
|
+
["event", { const: "close" }, false],
|
|
676
|
+
["data", returnSchema, returnOptional],
|
|
677
|
+
["id", { type: "string" }, true],
|
|
678
|
+
["retry", { type: "number" }, true]
|
|
679
|
+
]),
|
|
680
|
+
{
|
|
681
|
+
type: "object",
|
|
682
|
+
properties: {
|
|
683
|
+
event: { const: "error" },
|
|
684
|
+
data: {},
|
|
685
|
+
id: { type: "string" },
|
|
686
|
+
retry: { type: "number" }
|
|
687
|
+
},
|
|
688
|
+
required: ["event"]
|
|
689
|
+
}
|
|
690
|
+
]);
|
|
691
|
+
return {
|
|
692
|
+
"text/event-stream": {
|
|
693
|
+
schema: ctx.registry.toOpenAPISchema(schema, direction)
|
|
694
|
+
}
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
function toBodyContent(ctx, direction, schema) {
|
|
698
|
+
const fileSchemasByMediaType = /* @__PURE__ */ new Map();
|
|
699
|
+
const rest = flattenJsonUnionSchema(schema).filter((s) => {
|
|
700
|
+
if (!isJsonFileSchema(s)) {
|
|
701
|
+
return !isUnconstrainedSchema(s);
|
|
702
|
+
}
|
|
703
|
+
const contentMediaType = s.contentMediaType ?? "*/*";
|
|
704
|
+
const schemas = fileSchemasByMediaType.get(contentMediaType);
|
|
705
|
+
if (schemas) {
|
|
706
|
+
schemas.push(s);
|
|
707
|
+
} else {
|
|
708
|
+
fileSchemasByMediaType.set(contentMediaType, [s]);
|
|
709
|
+
}
|
|
710
|
+
return false;
|
|
711
|
+
});
|
|
712
|
+
const content = {};
|
|
713
|
+
if (rest.length > 0) {
|
|
714
|
+
const restSchema = fileSchemasByMediaType.size ? combineJsonSchemasWithComposition("anyOf", rest) : schema;
|
|
715
|
+
const hasNestedFiles = findDeepMatches(
|
|
716
|
+
(v) => isPlainObject(v) && isJsonFileSchema(v),
|
|
717
|
+
restSchema
|
|
718
|
+
).values.length > 0;
|
|
719
|
+
const contentType = hasNestedFiles ? "multipart/form-data" : "application/json";
|
|
720
|
+
const fileSchemas = fileSchemasByMediaType.get(contentType);
|
|
721
|
+
fileSchemasByMediaType.delete(contentType);
|
|
722
|
+
content[contentType] = {
|
|
723
|
+
schema: ctx.registry.toOpenAPISchema(combineJsonSchemasWithComposition("anyOf", [restSchema, ...fileSchemas ?? []]), direction)
|
|
724
|
+
};
|
|
725
|
+
}
|
|
726
|
+
for (const [contentType, schemas] of fileSchemasByMediaType.entries()) {
|
|
727
|
+
content[contentType] = {
|
|
728
|
+
schema: ctx.registry.toOpenAPISchema(combineJsonSchemasWithComposition("anyOf", schemas), direction)
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
return content;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
class OpenAPIGenerator {
|
|
735
|
+
serializer;
|
|
736
|
+
converter;
|
|
737
|
+
constructor(options = {}) {
|
|
738
|
+
this.serializer = options.serializer ?? new OpenAPISerializer();
|
|
739
|
+
this.converter = new DelegatingJsonSchemaConverter([
|
|
740
|
+
...toArray(options.converters),
|
|
741
|
+
new StandardJsonSchemaConverter()
|
|
742
|
+
]);
|
|
743
|
+
}
|
|
744
|
+
async generate(router, options = {}) {
|
|
745
|
+
const doc = {
|
|
746
|
+
...clone(options.base),
|
|
747
|
+
openapi: options.base?.openapi ?? "3.1.2",
|
|
748
|
+
info: options.base?.info ?? { title: "API Reference", version: "0.0.0" }
|
|
749
|
+
};
|
|
750
|
+
const ctx = {
|
|
751
|
+
registry: new OpenAPIComponentRegistry(doc, options.customComponentName),
|
|
752
|
+
convertSchemas: (schemas, direction) => this.convertSchemas(schemas, direction),
|
|
753
|
+
errorStatusMap: options.errorStatusMap ?? COMMON_ERROR_STATUS_MAP,
|
|
754
|
+
customErrorResponseBodySchema: options.customErrorResponseBodySchema
|
|
755
|
+
};
|
|
756
|
+
const errors = [];
|
|
757
|
+
await walkProcedureContractsAsync(router, (contract, path) => {
|
|
758
|
+
if (value(options.filter, contract, path) === false) {
|
|
759
|
+
return;
|
|
760
|
+
}
|
|
761
|
+
try {
|
|
762
|
+
const def = contract["~orpc"];
|
|
763
|
+
const meta = getOpenAPIMeta(contract);
|
|
764
|
+
const method = (meta?.method ?? DEFAULT_OPENAPI_METHOD).toLowerCase();
|
|
765
|
+
const postPath = meta?.path ?? pathToHttpPath(path);
|
|
766
|
+
const httpPath = meta?.prefix ? mergeHttpPath(meta.prefix, postPath) : postPath;
|
|
767
|
+
const dynamicPathParams = getDynamicPathParams(httpPath);
|
|
768
|
+
const openApiPath = toOpenAPIPath(httpPath, dynamicPathParams);
|
|
769
|
+
let operation;
|
|
770
|
+
if (meta?.spec !== void 0 && typeof meta.spec !== "function") {
|
|
771
|
+
operation = meta.spec;
|
|
772
|
+
} else {
|
|
773
|
+
operation = {
|
|
774
|
+
operationId: meta?.operationId ?? path.join("."),
|
|
775
|
+
summary: meta?.summary,
|
|
776
|
+
description: meta?.description,
|
|
777
|
+
deprecated: meta?.deprecated,
|
|
778
|
+
tags: meta?.tags?.map((tag) => tag)
|
|
779
|
+
};
|
|
780
|
+
buildRequest(ctx, operation, def, meta, dynamicPathParams);
|
|
781
|
+
buildSuccessResponse(ctx, operation, def, meta);
|
|
782
|
+
buildErrorResponse(ctx, operation, def);
|
|
783
|
+
}
|
|
784
|
+
if (typeof meta?.spec === "function") {
|
|
785
|
+
operation = meta.spec(operation);
|
|
786
|
+
}
|
|
787
|
+
doc.paths ??= {};
|
|
788
|
+
doc.paths[openApiPath] ??= {};
|
|
789
|
+
doc.paths[openApiPath][method] = operation;
|
|
790
|
+
} catch (e) {
|
|
791
|
+
if (!(e instanceof OpenAPIGeneratorError)) {
|
|
792
|
+
throw e;
|
|
793
|
+
}
|
|
794
|
+
errors.push(`Procedure at ${path.join(".") || "(root)"}: ${e.message}`);
|
|
795
|
+
}
|
|
796
|
+
});
|
|
797
|
+
if (errors.length) {
|
|
798
|
+
throw new OpenAPIGeneratorError(
|
|
799
|
+
`[OpenAPIGenerator] Failed to generate the OpenAPI document (${errors.length} error${errors.length === 1 ? "" : "s"}):
|
|
800
|
+
|
|
801
|
+
${errors.join("\n\n")}`
|
|
802
|
+
);
|
|
803
|
+
}
|
|
804
|
+
return this.serializer.serialize(doc, { asFormData: false, useFormDataForBlobFields: false });
|
|
805
|
+
}
|
|
806
|
+
convertSchema(schema, direction) {
|
|
807
|
+
const [jsonSchema, optional] = this.converter.convert(schema, direction);
|
|
808
|
+
return [strip$schemaField(jsonSchema), optional];
|
|
809
|
+
}
|
|
810
|
+
convertSchemas(schemas, direction) {
|
|
811
|
+
if (!schemas || schemas.length <= 1) {
|
|
812
|
+
return this.convertSchema(schemas?.[0], direction);
|
|
813
|
+
}
|
|
814
|
+
const results = schemas.map((s) => this.convertSchema(s, direction));
|
|
815
|
+
return [
|
|
816
|
+
combineJsonSchemasWithComposition("allOf", results.map(([jsonSchema]) => jsonSchema)),
|
|
817
|
+
results.every(([, optional]) => optional)
|
|
818
|
+
];
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
function strip$schemaField(schema) {
|
|
822
|
+
if (typeof schema !== "object") {
|
|
823
|
+
return schema;
|
|
824
|
+
}
|
|
825
|
+
const { $schema, ...rest } = schema;
|
|
826
|
+
return rest;
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
function populateRouterContractOpenAPIPaths(router, options = {}) {
|
|
830
|
+
const path = toArray(options.path);
|
|
831
|
+
if (router instanceof ProcedureContract) {
|
|
832
|
+
if (getOpenAPIMeta(router)?.path !== void 0) {
|
|
833
|
+
return router;
|
|
834
|
+
}
|
|
835
|
+
const [meta, metaPlugins] = resolveMetaPlugins(
|
|
836
|
+
router["~orpc"].meta,
|
|
837
|
+
router["~orpc"].metaPlugins,
|
|
838
|
+
[openapi({ path: pathToHttpPath(path) })]
|
|
839
|
+
);
|
|
840
|
+
return new ProcedureContract({
|
|
841
|
+
...router["~orpc"],
|
|
842
|
+
meta,
|
|
843
|
+
metaPlugins
|
|
844
|
+
});
|
|
845
|
+
}
|
|
846
|
+
if (!isTypescriptObject(router)) {
|
|
847
|
+
return router;
|
|
848
|
+
}
|
|
849
|
+
const populated = {};
|
|
850
|
+
for (const key in router) {
|
|
851
|
+
populated[key] = populateRouterContractOpenAPIPaths(
|
|
852
|
+
router[key],
|
|
853
|
+
{ ...options, path: [...path, key] }
|
|
854
|
+
);
|
|
855
|
+
}
|
|
856
|
+
return populated;
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
export { DEFAULT_OPENAPI_INPUT_STRUCTURE, DEFAULT_OPENAPI_METHOD, DEFAULT_OPENAPI_OUTPUT_STRUCTURE, DEFAULT_OPENAPI_SUCCESS_DESCRIPTION, OpenAPIGenerator, OpenAPIGeneratorError, OpenAPISerializer, createContractJsonifiedClientFactory, getDynamicPathParams, getOpenAPIMeta, isBodylessMethod, openapi, populateRouterContractOpenAPIPaths };
|