forked from wework/json-schema-to-openapi-schema
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathindex.ts
312 lines (281 loc) · 7.74 KB
/
index.ts
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
import type { JSONSchema } from '@apidevtools/json-schema-ref-parser';
import type {
JSONSchema4,
JSONSchema6Definition,
JSONSchema7Definition,
} from 'json-schema';
import type { Options, SchemaType, SchemaTypeKeys } from './types.js';
import { Walker } from 'json-schema-walker';
import { allowedKeywords } from './const.js';
import type { OpenAPIV3 } from 'openapi-types';
class InvalidTypeError extends Error {
constructor(message: string) {
super(message);
this.name = 'InvalidTypeError';
this.message = message;
}
}
const oasExtensionPrefix = 'x-';
const handleDefinition = async <T extends JSONSchema = JSONSchema>(
def: JSONSchema7Definition | JSONSchema6Definition | JSONSchema4,
schema: T
) => {
if (typeof def !== 'object') {
return def;
}
const type = def.type;
if (type) {
// Walk just the definitions types
const walker = new Walker<T>();
await walker.loadSchema(
{
definitions: schema['definitions'] || [],
...def,
$schema: schema['$schema'],
} as any,
{
dereference: true,
cloneSchema: true,
dereferenceOptions: {
dereference: {
circular: 'ignore',
},
},
}
);
await walker.walk(convertSchema, walker.vocabularies.DRAFT_07);
if ('definitions' in walker.rootSchema) {
delete (<any>walker.rootSchema).definitions;
}
return walker.rootSchema;
} else if (Array.isArray(def)) {
// if it's an array, we might want to reconstruct the type;
const typeArr = def;
const hasNull = typeArr.includes('null');
if (hasNull) {
const actualTypes = typeArr.filter((l) => l !== 'null');
return {
type: actualTypes.length === 1 ? actualTypes[0] : actualTypes,
nullable: true,
// this is incorrect but thats ok, we are in the inbetween phase here
} as JSONSchema7Definition | JSONSchema6Definition | JSONSchema4;
}
}
return def;
};
const convert = async <T extends JSONSchema = JSONSchema>(
schema: T,
options?: Options
): Promise<OpenAPIV3.Document> => {
const walker = new Walker<T>();
const convertDefs = options?.convertUnreferencedDefinitions ?? true;
await walker.loadSchema(schema, options);
await walker.walk(convertSchema, walker.vocabularies.DRAFT_07);
// if we want to convert unreferenced definitions, we need to do it iteratively here
const rootSchema = walker.rootSchema as unknown as JSONSchema;
if (convertDefs && rootSchema?.definitions) {
for (const defName in rootSchema.definitions) {
const def = rootSchema.definitions[defName];
rootSchema.definitions[defName] = await handleDefinition(def, schema);
}
}
return rootSchema as OpenAPIV3.Document;
};
function stripIllegalKeywords(schema: SchemaType) {
if (typeof schema !== 'object') {
return schema;
}
delete schema['$schema'];
delete schema['$id'];
if ('id' in schema) {
delete schema['id'];
}
return schema;
}
function convertSchema(schema: SchemaType | undefined) {
if (!schema) {
return schema;
}
schema = stripIllegalKeywords(schema);
schema = convertTypes(schema);
schema = rewriteConst(schema);
schema = convertDependencies(schema);
schema = rewriteIfThenElse(schema);
schema = rewriteExclusiveMinMax(schema);
schema = convertExamples(schema);
if (typeof schema['patternProperties'] === 'object') {
schema = convertPatternProperties(schema);
}
if (schema.type === 'array' && typeof schema.items === 'undefined') {
schema.items = {};
}
// should be called last
schema = convertIllegalKeywordsAsExtensions(schema);
return schema;
}
const validTypes = new Set([
'null',
'boolean',
'object',
'array',
'number',
'string',
'integer',
]);
function validateType(type: any) {
if (typeof type === 'object' && !Array.isArray(type)) {
// Refs are allowed because they fix circular references
if (type.$ref) {
return;
}
// this is a de-referenced circular ref
if (type.properties) {
return;
}
}
const types = Array.isArray(type) ? type : [type];
types.forEach((type) => {
if (type && !validTypes.has(type))
throw new InvalidTypeError('Type "' + type + '" is not a valid type');
});
}
function convertDependencies(schema: SchemaType) {
const deps = schema.dependencies;
if (typeof deps !== 'object') {
return schema;
}
// Turns the dependencies keyword into an allOf of oneOf's
// "dependencies": {
// "post-office-box": ["street-address"]
// },
//
// becomes
//
// "allOf": [
// {
// "oneOf": [
// {"not": {"required": ["post-office-box"]}},
// {"required": ["post-office-box", "street-address"]}
// ]
// }
//
delete schema['dependencies'];
if (!Array.isArray(schema.allOf)) {
schema.allOf = [];
}
for (const key in deps) {
const foo: (JSONSchema4 & JSONSchema6Definition) & JSONSchema7Definition = {
oneOf: [
{
not: {
required: [key],
},
},
{
required: [key, deps[key]].flat() as string[],
},
],
};
schema.allOf.push(foo);
}
return schema;
}
function convertTypes(schema: SchemaType) {
if (typeof schema !== 'object') {
return schema;
}
if (schema.type === undefined) {
return schema;
}
validateType(schema.type);
if (Array.isArray(schema.type)) {
if (schema.type.includes('null')) {
schema.nullable = true;
}
const typesWithoutNull = schema.type.filter((type) => type !== 'null');
if (typesWithoutNull.length === 0) {
delete schema.type;
} else if (typesWithoutNull.length === 1) {
schema.type = typesWithoutNull[0];
} else {
delete schema.type;
schema.anyOf = typesWithoutNull.map((type) => ({ type }));
}
} else if (schema.type === 'null') {
delete schema.type;
schema.nullable = true;
}
return schema;
}
// "patternProperties did not make it into OpenAPI v3.0"
// https://github.com/OAI/OpenAPI-Specification/issues/687
function convertPatternProperties(schema: SchemaType) {
schema['x-patternProperties'] = schema['patternProperties'];
delete schema['patternProperties'];
schema.additionalProperties ??= true;
return schema;
}
// keywords (or property names) that are not recognized within OAS3 are rewritten into extensions.
function convertIllegalKeywordsAsExtensions(schema: SchemaType) {
const keys = Object.keys(schema) as SchemaTypeKeys[];
keys
.filter(
(keyword) =>
!keyword.startsWith(oasExtensionPrefix) &&
!allowedKeywords.includes(keyword)
)
.forEach((keyword: SchemaTypeKeys) => {
const key = `${oasExtensionPrefix}${keyword}` as keyof SchemaType;
schema[key] = schema[keyword];
delete schema[keyword];
});
return schema;
}
function convertExamples(schema: SchemaType) {
if (schema['examples'] && Array.isArray(schema['examples'])) {
schema['example'] = schema['examples'][0];
delete schema['examples'];
}
return schema;
}
function rewriteConst(schema: SchemaType) {
if (Object.hasOwnProperty.call(schema, 'const')) {
schema.enum = [schema.const];
delete schema.const;
}
return schema;
}
function rewriteIfThenElse(schema: SchemaType) {
if (typeof schema !== 'object') {
return schema;
}
/* @handrews https://github.com/OAI/OpenAPI-Specification/pull/1766#issuecomment-442652805
if and the *Of keywords
There is a really easy solution for implementations, which is that
if: X, then: Y, else: Z
is equivalent to
oneOf: [allOf: [X, Y], allOf: [not: X, Z]]
*/
if ('if' in schema && schema.if && schema.then) {
schema.oneOf = [
{ allOf: [schema.if, schema.then].filter(Boolean) },
{ allOf: [{ not: schema.if }, schema.else].filter(Boolean) },
];
delete schema.if;
delete schema.then;
delete schema.else;
}
return schema;
}
function rewriteExclusiveMinMax(schema: SchemaType) {
if (typeof schema.exclusiveMaximum === 'number') {
schema.maximum = schema.exclusiveMaximum;
schema.exclusiveMaximum = true;
}
if (typeof schema.exclusiveMinimum === 'number') {
schema.minimum = schema.exclusiveMinimum;
schema.exclusiveMinimum = true;
}
return schema;
}
export default convert;