forked from middleapi/orpc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenapi-utils.ts
More file actions
316 lines (269 loc) · 9.28 KB
/
openapi-utils.ts
File metadata and controls
316 lines (269 loc) · 9.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
import type { HTTPMethod, HTTPPath } from '@orpc/client'
import type { OpenAPI } from '@orpc/contract'
import type { FileSchema, JSONSchema, ObjectSchema } from './schema'
import { standardizeHTTPPath } from '@orpc/openapi-client/standard'
import { findDeepMatches, isObject, stringifyJSON, toArray } from '@orpc/shared'
import { expandArrayableSchema, filterSchemaBranches, isAnySchema, isFileSchema, isNeverSchema, isObjectSchema, isPrimitiveSchema } from './schema-utils'
/**
* @internal
*/
export function toOpenAPIPath(path: HTTPPath): string {
return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, '/{$1}')
}
/**
* @internal
*/
export function toOpenAPIMethod(method: HTTPMethod): Lowercase<HTTPMethod> {
return method.toLocaleLowerCase() as Lowercase<HTTPMethod>
}
/**
* @internal
*/
export function toOpenAPIContent(schema: JSONSchema): Record<string, OpenAPI.MediaTypeObject> {
const content: Record<string, OpenAPI.MediaTypeObject> = {}
const [matches, restSchema] = filterSchemaBranches(schema, isFileSchema)
for (const file of matches as FileSchema[]) {
content[file.contentMediaType] = {
schema: toOpenAPISchema(file),
}
}
if (restSchema !== undefined && !isAnySchema(restSchema) && !isNeverSchema(restSchema)) {
content['application/json'] = {
schema: toOpenAPISchema(restSchema),
}
const isStillHasFileSchema = findDeepMatches(v => isObject(v) && isFileSchema(v), restSchema).values.length > 0
if (isStillHasFileSchema) {
content['multipart/form-data'] = {
schema: toOpenAPISchema(restSchema),
}
}
}
return content
}
/**
* @internal
*/
export function toOpenAPIEventIteratorContent(
[yieldsRequired, yieldsSchema]: [boolean, JSONSchema],
[returnsRequired, returnsSchema]: [boolean, JSONSchema],
): Record<string, OpenAPI.MediaTypeObject> {
return {
'text/event-stream': {
schema: toOpenAPISchema({
oneOf: [
{
type: 'object',
properties: {
event: { const: 'message' },
data: yieldsSchema,
id: { type: 'string' },
retry: { type: 'number' },
},
required: yieldsRequired ? ['event', 'data'] : ['event'],
},
{
type: 'object',
properties: {
event: { const: 'done' },
data: returnsSchema,
id: { type: 'string' },
retry: { type: 'number' },
},
required: returnsRequired ? ['event', 'data'] : ['event'],
},
{
type: 'object',
properties: {
event: { const: 'error' },
data: {},
id: { type: 'string' },
retry: { type: 'number' },
},
required: ['event'],
},
],
}),
},
}
}
/**
* @internal
*/
export function toOpenAPIParameters(schema: ObjectSchema, parameterIn: 'path' | 'query' | 'header' | 'cookie'): OpenAPI.ParameterObject[] {
const parameters: OpenAPI.ParameterObject[] = []
for (const key in schema.properties) {
const keySchema = schema.properties[key]!
let isDeepObjectStyle = true
if (parameterIn !== 'query') {
isDeepObjectStyle = false
}
else if (isPrimitiveSchema(keySchema)) {
isDeepObjectStyle = false
}
else {
const [item] = expandArrayableSchema(keySchema) ?? []
if (item !== undefined && isPrimitiveSchema(item)) {
isDeepObjectStyle = false
}
}
parameters.push({
name: key,
in: parameterIn,
required: schema.required?.includes(key),
schema: toOpenAPISchema(keySchema) as any,
style: isDeepObjectStyle ? 'deepObject' : undefined,
explode: isDeepObjectStyle ? true : undefined,
allowEmptyValue: parameterIn === 'query' ? true : undefined,
allowReserved: parameterIn === 'query' ? true : undefined,
})
}
return parameters
}
/**
* @internal
*/
export function checkParamsSchema(schema: ObjectSchema, params: string[]): boolean {
const properties = Object.keys(schema.properties ?? {})
const required = schema.required ?? []
if (properties.length !== params.length || properties.some(v => !params.includes(v))) {
return false
}
if (required.length !== params.length || required.some(v => !params.includes(v))) {
return false
}
return true
}
/**
* @internal
*/
export function toOpenAPISchema(schema: JSONSchema): OpenAPI.SchemaObject & object {
return schema === true
? {}
: schema === false
? { not: {} }
: schema as OpenAPI.SchemaObject
}
const OPENAPI_JSON_SCHEMA_REF_PREFIX = /* @__PURE__ */ '#/components/schemas/'
export function resolveOpenAPIJsonSchemaRef(doc: OpenAPI.Document, schema: JSONSchema): JSONSchema {
if (typeof schema !== 'object' || !schema.$ref?.startsWith(OPENAPI_JSON_SCHEMA_REF_PREFIX)) {
return schema
}
const name = schema.$ref.slice(OPENAPI_JSON_SCHEMA_REF_PREFIX.length)
const resolved = doc.components?.schemas?.[name]
return resolved as JSONSchema ?? schema
}
/**
* Simplifies composed object JSON Schemas (using anyOf, oneOf, allOf) by flattening nested compositions
*
* @warning The result is looser than the original schema and may not fully validate the same data.
*/
export function simplifyComposedObjectJsonSchemasAndRefs(schema: JSONSchema, doc?: OpenAPI.Document): JSONSchema {
if (doc) {
schema = resolveOpenAPIJsonSchemaRef(doc, schema)
}
if (typeof schema !== 'object' || (!schema.anyOf && !schema.oneOf && !schema.allOf)) {
return schema
}
const unionSchemas = [
...toArray(schema.anyOf?.map(s => simplifyComposedObjectJsonSchemasAndRefs(s, doc))),
...toArray(schema.oneOf?.map(s => simplifyComposedObjectJsonSchemasAndRefs(s, doc))),
]
const objectUnionSchemas: ObjectSchema[] = []
for (const u of unionSchemas) {
if (!isObjectSchema(u)) {
return schema
}
objectUnionSchemas.push(u)
}
const mergedUnionPropertyMap: Map<string, { required: boolean, schemas: JSONSchema[] }> = new Map()
for (const u of objectUnionSchemas) {
if (u.properties) {
for (const [key, value] of Object.entries(u.properties)) {
let entry = mergedUnionPropertyMap.get(key)
if (!entry) {
const required = objectUnionSchemas.every(s => s.required?.includes(key))
entry = { required, schemas: [] }
mergedUnionPropertyMap.set(key, entry)
}
entry.schemas.push(value)
}
}
}
const intersectionSchemas = toArray(schema.allOf?.map(s => simplifyComposedObjectJsonSchemasAndRefs(s, doc)))
const objectIntersectionSchemas: ObjectSchema[] = []
for (const u of intersectionSchemas) {
if (!isObjectSchema(u)) {
return schema
}
objectIntersectionSchemas.push(u)
}
// if object schema in the same level with anyOf/oneOf/allOf
if (isObjectSchema(schema)) {
objectIntersectionSchemas.push(schema)
}
const mergedInteractionPropertyMap: Map<string, { required: boolean, schemas: JSONSchema[] }> = new Map()
for (const u of objectIntersectionSchemas) {
if (u.properties) {
for (const [key, value] of Object.entries(u.properties)) {
let entry = mergedInteractionPropertyMap.get(key)
if (!entry) {
const required = objectIntersectionSchemas.some(s => s.required?.includes(key))
entry = { required, schemas: [] }
mergedInteractionPropertyMap.set(key, entry)
}
entry.schemas.push(value)
}
}
}
const resultObjectSchema: { type: 'object', properties: Record<string, JSONSchema>, required: string[] } = { type: 'object', properties: {}, required: [] }
const keys = new Set<string>([
...mergedUnionPropertyMap.keys(),
...mergedInteractionPropertyMap.keys(),
])
if (keys.size === 0) {
return schema
}
const deduplicateSchemas = (schemas: JSONSchema[]): JSONSchema[] => {
const seen = new Set<string>()
const result: JSONSchema[] = []
for (const schema of schemas) {
const key = stringifyJSON(schema)
if (!seen.has(key)) {
seen.add(key)
result.push(schema)
}
}
return result
}
for (const key of keys) {
const unionEntry = mergedUnionPropertyMap.get(key)
const intersectionEntry = mergedInteractionPropertyMap.get(key)
resultObjectSchema.properties[key] = (() => {
const dedupedUnionSchemas = unionEntry ? deduplicateSchemas(unionEntry.schemas) : []
const dedupedIntersectionSchemas = intersectionEntry ? deduplicateSchemas(intersectionEntry.schemas) : []
if (!dedupedUnionSchemas.length) {
return dedupedIntersectionSchemas.length === 1
? dedupedIntersectionSchemas[0]!
: { allOf: dedupedIntersectionSchemas }
}
if (!dedupedIntersectionSchemas.length) {
return dedupedUnionSchemas.length === 1
? dedupedUnionSchemas[0]!
: { anyOf: dedupedUnionSchemas }
}
const allOf = deduplicateSchemas([
...dedupedIntersectionSchemas,
dedupedUnionSchemas.length === 1
? dedupedUnionSchemas[0]!
: { anyOf: dedupedUnionSchemas },
])
return allOf.length === 1
? allOf[0]!
: { allOf }
})()
if (unionEntry?.required || intersectionEntry?.required) {
resultObjectSchema.required.push(key)
}
}
return resultObjectSchema
}