|
1
|
import { OpenAPIV3 } from "openapi-types" |
|
2
|
import { OpenApiSchema } from "../../types/index.js" |
|
3
|
import Formatter from "./formatter.js" |
|
4
|
import { join } from "path" |
|
5
|
import { TAG_SCHEMA_NAME_OVERRIDES } from "../../constants.js" |
|
6
|
import docblockToYaml from "../../utils/docblock-to-yaml.js" |
|
7
|
import ts from "typescript" |
|
8
|
import { getOasOutputBasePath } from "../../utils/get-output-base-paths.js" |
|
9
|
import { parse } from "yaml" |
|
10
|
import formatOas from "../../utils/format-oas.js" |
|
11
|
import pluralize from "pluralize" |
|
12
|
import { capitalize, wordsToPascal } from "utils" |
|
13
|
import chalk from "chalk" |
|
14
|
import { OasArea } from "../kinds/oas.js" |
|
15
|
import { |
|
16
|
isLevelExceeded, |
|
17
|
maybeIncrementLevel, |
|
18
|
} from "../../utils/level-utils.js" |
|
19
|
|
|
20
|
export type ParsedSchema = { |
|
21
|
schema: OpenApiSchema |
|
22
|
schemaPrefix: string |
|
23
|
} |
|
24
|
|
|
25
|
/** |
|
26
|
* Class providing helper methods for OAS Schemas |
|
27
|
*/ |
|
28
|
class OasSchemaHelper { |
|
29
|
/** |
|
30
|
* This map collects schemas created while generating the OAS, then, once the generation process |
|
31
|
* finishes, it checks if it should be added to the base OAS document. |
|
32
|
*/ |
|
33
|
private schemas: Map<string, OpenApiSchema> |
|
34
|
protected schemaRefPrefix = "#/components/schemas/" |
|
35
|
protected formatter: Formatter |
|
36
|
private MAX_LEVEL = 7 |
|
37
|
/** |
|
38
|
* The path to the directory holding the base YAML files. |
|
39
|
*/ |
|
40
|
protected baseOutputPath: string |
|
41
|
|
|
42
|
constructor() { |
|
43
|
this.schemas = new Map() |
|
44
|
this.formatter = new Formatter() |
|
45
|
this.baseOutputPath = getOasOutputBasePath() |
|
46
|
} |
|
47
|
|
|
48
|
/** |
|
49
|
* Initialize the {@link schemas} property. Helpful when resetting the property. |
|
50
|
*/ |
|
51
|
init() { |
|
52
|
this.schemas = new Map() |
|
53
|
} |
|
54
|
|
|
55
|
/** |
|
56
|
* Retrieve schema as a reference object and add the schema to the {@link schemas} property. |
|
57
|
* |
|
58
|
* @param schema - The schema to convert and add to the schemas property. |
|
59
|
* @param level - The current depth level. Used to avoid maximum call stack size exceeded. |
|
60
|
* @returns The schema as a reference. If the schema doesn't have the x-schemaName property set, |
|
61
|
* the schema isn't converted and `undefined` is returned. |
|
62
|
*/ |
|
63
|
namedSchemaToReference( |
|
64
|
schema: OpenApiSchema, |
|
65
|
level = 1 |
|
66
|
): OpenAPIV3.ReferenceObject | undefined { |
|
67
|
if (isLevelExceeded(level, this.MAX_LEVEL)) { |
|
68
|
return |
|
69
|
} |
|
70
|
|
|
71
|
if (!schema["x-schemaName"]) { |
|
72
|
return |
|
73
|
} |
|
74
|
schema["x-schemaName"] = this.normalizeSchemaName(schema["x-schemaName"]) |
|
75
|
|
|
76
|
// check if schema has child schemas |
|
77
|
// and convert those |
|
78
|
const properties = schema.properties |
|
79
|
? schema.properties |
|
80
|
: schema.additionalProperties && |
|
81
|
typeof schema.additionalProperties !== "boolean" && |
|
82
|
!this.isRefObject(schema.additionalProperties) |
|
83
|
? schema.additionalProperties.properties |
|
84
|
: undefined |
|
85
|
if (properties) { |
|
86
|
Object.keys(properties).forEach((property) => { |
|
87
|
const propertySchema = properties![property] |
|
88
|
if ("$ref" in propertySchema) { |
|
89
|
return |
|
90
|
} |
|
91
|
|
|
92
|
// if the property is an array, possibly convert its items schema |
|
93
|
// to a reference. |
|
94
|
if ( |
|
95
|
propertySchema.type === "array" && |
|
96
|
propertySchema.items && |
|
97
|
!("$ref" in propertySchema.items) |
|
98
|
) { |
|
99
|
const arrayLevel = maybeIncrementLevel(level, "array") |
|
100
|
propertySchema.items = |
|
101
|
this.namedSchemaToReference(propertySchema.items, arrayLevel) || |
|
102
|
this.schemaChildrenToRefs(propertySchema.items, arrayLevel) |
|
103
|
} else if ( |
|
104
|
propertySchema.oneOf || |
|
105
|
propertySchema.allOf || |
|
106
|
propertySchema.anyOf |
|
107
|
) { |
|
108
|
// if the property is a combination of types, go through each of |
|
109
|
// the types and try to convert them to references. Fall back to |
|
110
|
// `schemaChildrenToRefs` so nested named schemas inside an |
|
111
|
// unnamed composed entry (e.g. an `allOf` member from an |
|
112
|
// intersection) still get extracted to `$ref`. |
|
113
|
const schemaTarget = |
|
114
|
propertySchema.oneOf || propertySchema.allOf || propertySchema.anyOf |
|
115
|
schemaTarget!.forEach((item, index) => { |
|
116
|
if ("$ref" in item) { |
|
117
|
return |
|
118
|
} |
|
119
|
|
|
120
|
const composedLevel = maybeIncrementLevel(level, "allOf") |
|
121
|
schemaTarget![index] = |
|
122
|
this.namedSchemaToReference(item, composedLevel) || |
|
123
|
this.schemaChildrenToRefs(item, composedLevel) |
|
124
|
}) |
|
125
|
} |
|
126
|
|
|
127
|
const objectLevel = maybeIncrementLevel(level, "object") |
|
128
|
properties![property] = |
|
129
|
this.namedSchemaToReference( |
|
130
|
propertySchema as OpenApiSchema, |
|
131
|
objectLevel |
|
132
|
) || |
|
133
|
this.schemaChildrenToRefs( |
|
134
|
propertySchema as OpenApiSchema, |
|
135
|
objectLevel |
|
136
|
) |
|
137
|
}) |
|
138
|
} |
|
139
|
|
|
140
|
if (this.canAddSchema(schema)) { |
|
141
|
this.schemas.set(schema["x-schemaName"], schema) |
|
142
|
} |
|
143
|
|
|
144
|
return { |
|
145
|
$ref: this.constructSchemaReference(schema["x-schemaName"]), |
|
146
|
} |
|
147
|
} |
|
148
|
|
|
149
|
schemaChildrenToRefs(schema: OpenApiSchema, level = 1): OpenApiSchema { |
|
150
|
if (isLevelExceeded(level, this.MAX_LEVEL)) { |
|
151
|
return schema |
|
152
|
} |
|
153
|
|
|
154
|
const clonedSchema = Object.assign({}, schema) |
|
155
|
|
|
156
|
if (clonedSchema.allOf) { |
|
157
|
clonedSchema.allOf = clonedSchema.allOf.map((item) => { |
|
158
|
if (this.isRefObject(item)) { |
|
159
|
return item |
|
160
|
} |
|
161
|
|
|
162
|
const transformChildItems = this.schemaChildrenToRefs( |
|
163
|
item, |
|
164
|
maybeIncrementLevel(level, "allOf") |
|
165
|
) |
|
166
|
return ( |
|
167
|
this.namedSchemaToReference(transformChildItems) || |
|
168
|
transformChildItems |
|
169
|
) |
|
170
|
}) |
|
171
|
} else if (clonedSchema.oneOf) { |
|
172
|
clonedSchema.oneOf = clonedSchema.oneOf.map((item) => { |
|
173
|
if (this.isRefObject(item)) { |
|
174
|
return item |
|
175
|
} |
|
176
|
|
|
177
|
const transformChildItems = this.schemaChildrenToRefs( |
|
178
|
item, |
|
179
|
maybeIncrementLevel(level, "oneOf") |
|
180
|
) |
|
181
|
return ( |
|
182
|
this.namedSchemaToReference(transformChildItems) || |
|
183
|
transformChildItems |
|
184
|
) |
|
185
|
}) |
|
186
|
} else if ( |
|
187
|
clonedSchema.type === "array" && |
|
188
|
!this.isRefObject(clonedSchema.items) |
|
189
|
) { |
|
190
|
const transformedChildItems = this.schemaChildrenToRefs( |
|
191
|
clonedSchema.items, |
|
192
|
maybeIncrementLevel(level, "array") |
|
193
|
) |
|
194
|
clonedSchema.items = |
|
195
|
this.namedSchemaToReference(transformedChildItems) || |
|
196
|
transformedChildItems |
|
197
|
} else if (clonedSchema.properties && !clonedSchema["x-schemaName"]) { |
|
198
|
Object.entries(clonedSchema.properties).forEach(([key, property]) => { |
|
199
|
if (this.isRefObject(property)) { |
|
200
|
return |
|
201
|
} |
|
202
|
|
|
203
|
const transformedProperty = this.schemaChildrenToRefs( |
|
204
|
property, |
|
205
|
maybeIncrementLevel(level, "object") |
|
206
|
) |
|
207
|
schema.properties![key] = |
|
208
|
this.namedSchemaToReference(transformedProperty) || |
|
209
|
transformedProperty |
|
210
|
}) |
|
211
|
} else if ( |
|
212
|
clonedSchema.additionalProperties && |
|
213
|
typeof clonedSchema.additionalProperties !== "boolean" && |
|
214
|
!this.isRefObject(clonedSchema.additionalProperties) && |
|
215
|
clonedSchema.additionalProperties.properties |
|
216
|
) { |
|
217
|
const additionalProps = schema.additionalProperties as OpenApiSchema |
|
218
|
Object.entries(clonedSchema.additionalProperties.properties).forEach( |
|
219
|
([key, property]) => { |
|
220
|
if (this.isRefObject(property)) { |
|
221
|
return |
|
222
|
} |
|
223
|
|
|
224
|
const transformedProperty = this.schemaChildrenToRefs( |
|
225
|
property, |
|
226
|
maybeIncrementLevel(level, "object") |
|
227
|
) |
|
228
|
additionalProps.properties![key] = |
|
229
|
this.namedSchemaToReference(transformedProperty) || |
|
230
|
transformedProperty |
|
231
|
} |
|
232
|
) |
|
233
|
} |
|
234
|
|
|
235
|
return clonedSchema |
|
236
|
} |
|
237
|
|
|
238
|
isSchemaEmpty(schema?: OpenApiSchema): boolean { |
|
239
|
if (!schema || !Object.keys(schema).length) { |
|
240
|
return true |
|
241
|
} |
|
242
|
switch (schema.type) { |
|
243
|
case "object": |
|
244
|
const isPropertiesEmpty = |
|
245
|
schema.properties === undefined || |
|
246
|
Object.keys(schema.properties).length === 0 |
|
247
|
const isAdditionalPropertiesEmpty = |
|
248
|
schema.additionalProperties === undefined || |
|
249
|
typeof schema.additionalProperties === "boolean" || |
|
250
|
(!this.isRefObject(schema.additionalProperties) && |
|
251
|
(schema.additionalProperties.properties === undefined || |
|
252
|
Object.keys(schema.additionalProperties.properties).length == 0)) |
|
253
|
|
|
254
|
return isPropertiesEmpty && isAdditionalPropertiesEmpty |
|
255
|
case "array": |
|
256
|
return ( |
|
257
|
!this.isRefObject(schema.items) && this.isSchemaEmpty(schema.items) |
|
258
|
) |
|
259
|
default: |
|
260
|
return false |
|
261
|
} |
|
262
|
} |
|
263
|
|
|
264
|
canAddSchema(schema: OpenApiSchema): boolean { |
|
265
|
if (!schema["x-schemaName"]) { |
|
266
|
return false |
|
267
|
} |
|
268
|
|
|
269
|
const existingSchema = this.schemas.get(schema["x-schemaName"]) |
|
270
|
|
|
271
|
if (!existingSchema) { |
|
272
|
return true |
|
273
|
} |
|
274
|
|
|
275
|
return this.isSchemaEmpty(existingSchema) && !this.isSchemaEmpty(schema) |
|
276
|
} |
|
277
|
|
|
278
|
/** |
|
279
|
* Retrieve the expected file name of the schema. |
|
280
|
* |
|
281
|
* @param name - The schema's name |
|
282
|
* @returns The schema's file name |
|
283
|
*/ |
|
284
|
getSchemaFileName(name: string, shouldNormalizeName = true): string { |
|
285
|
return join( |
|
286
|
this.baseOutputPath, |
|
287
|
"schemas", |
|
288
|
`${shouldNormalizeName ? this.normalizeSchemaName(name) : name}.ts` |
|
289
|
) |
|
290
|
} |
|
291
|
|
|
292
|
/** |
|
293
|
* Retrieve the schema by its name. If the schema is in the {@link schemas} map, it'll be retrieved from |
|
294
|
* there. Otherwise, the method will try to retrieve it from an outputted schema file, if available. |
|
295
|
* |
|
296
|
* @param name - The schema's name. |
|
297
|
* @returns The parsed schema, if found. |
|
298
|
*/ |
|
299
|
getSchemaByName( |
|
300
|
name: string, |
|
301
|
shouldNormalizeName = true, |
|
302
|
isUpdating = false |
|
303
|
): ParsedSchema | undefined { |
|
304
|
const schemaName = shouldNormalizeName |
|
305
|
? this.normalizeSchemaName(name) |
|
306
|
: name |
|
307
|
// check if it already exists in the schemas map |
|
308
|
if (this.schemas.has(schemaName) && !isUpdating) { |
|
309
|
return { |
|
310
|
schema: JSON.parse(JSON.stringify(this.schemas.get(schemaName)!)), |
|
311
|
schemaPrefix: `@schema ${schemaName}`, |
|
312
|
} |
|
313
|
} |
|
314
|
const schemaFile = this.getSchemaFileName(schemaName, shouldNormalizeName) |
|
315
|
const schemaFileContent = ts.sys.readFile(schemaFile) |
|
316
|
|
|
317
|
if (!schemaFileContent) { |
|
318
|
return |
|
319
|
} |
|
320
|
|
|
321
|
return this.parseSchema(schemaFileContent, true) |
|
322
|
} |
|
323
|
|
|
324
|
/** |
|
325
|
* Parses a schema comment string. |
|
326
|
* |
|
327
|
* @param content - The schema comment string |
|
328
|
* @returns If the schema is valid and parsed successfully, the schema and its prefix are retrieved. |
|
329
|
*/ |
|
330
|
parseSchema( |
|
331
|
content: string, |
|
332
|
failOnParseError = false |
|
333
|
): ParsedSchema | undefined { |
|
334
|
const schemaFileContent = docblockToYaml(content) |
|
335
|
|
|
336
|
if (!schemaFileContent.startsWith("@schema")) { |
|
337
|
return |
|
338
|
} |
|
339
|
|
|
340
|
const splitContent = schemaFileContent.split("\n") |
|
341
|
const schemaPrefix = splitContent[0] |
|
342
|
let schema: OpenApiSchema | undefined |
|
343
|
|
|
344
|
try { |
|
345
|
schema = parse(splitContent.slice(1).join("\n")) |
|
346
|
} catch (e) { |
|
347
|
if (failOnParseError) { |
|
348
|
throw e |
|
349
|
} |
|
350
|
|
|
351
|
console.error(chalk.red(e)) |
|
352
|
} |
|
353
|
|
|
354
|
return schema |
|
355
|
? { |
|
356
|
schema, |
|
357
|
schemaPrefix, |
|
358
|
} |
|
359
|
: undefined |
|
360
|
} |
|
361
|
|
|
362
|
/** |
|
363
|
* Retrieve the normalized schema name. A schema's name must be normalized before saved. |
|
364
|
* |
|
365
|
* @param name - The original name. |
|
366
|
* @returns The normalized name. |
|
367
|
*/ |
|
368
|
normalizeSchemaName(name: string): string { |
|
369
|
return name |
|
370
|
.replace("DTO", "") |
|
371
|
.replace(this.schemaRefPrefix, "") |
|
372
|
.replace( |
|
373
|
/(?<!(AdminProduct|CreateProduct|UpdateProduct|StoreShippingOption|AdminShippingOption|CreateShippingOption|BaseProduct|StoreProduct|AdminCreateShippingOption|AdminUpdateShippingOption))Type$/, |
|
374
|
"" |
|
375
|
) |
|
376
|
} |
|
377
|
|
|
378
|
/** |
|
379
|
* Construct a reference string to a schema. |
|
380
|
* |
|
381
|
* @param name - The name of the schema. For cautionary reasons, the name is normalized using the {@link normalizeSchemaName} method. |
|
382
|
* @returns The schema reference. |
|
383
|
*/ |
|
384
|
constructSchemaReference(name: string): string { |
|
385
|
return `${this.schemaRefPrefix}${this.normalizeSchemaName(name)}` |
|
386
|
} |
|
387
|
|
|
388
|
/** |
|
389
|
* Checks whether a schema was already written to a file with content that |
|
390
|
* isn't empty. |
|
391
|
* |
|
392
|
* @param normalizedName - The schema's normalized name. |
|
393
|
* @returns Whether the schema's file has content that isn't empty. |
|
394
|
*/ |
|
395
|
private hasSchemaFileContent(normalizedName: string): boolean { |
|
396
|
try { |
|
397
|
const existingSchema = this.getSchemaByName(normalizedName, false, true) |
|
398
|
|
|
399
|
return ( |
|
400
|
existingSchema !== undefined && |
|
401
|
!this.isSchemaEmpty(existingSchema.schema) |
|
402
|
) |
|
403
|
} catch (e) { |
|
404
|
// the schema's file can't be parsed, so consider it not existent. |
|
405
|
return false |
|
406
|
} |
|
407
|
} |
|
408
|
|
|
409
|
/** |
|
410
|
* Writes schemas in the {@link schemas} property to the file path retrieved using the {@link getSchemaFileName} method. |
|
411
|
*/ |
|
412
|
writeNewSchemas() { |
|
413
|
this.schemas.forEach((schema) => { |
|
414
|
if (!schema["x-schemaName"]) { |
|
415
|
return |
|
416
|
} |
|
417
|
const normalizedName = this.normalizeSchemaName(schema["x-schemaName"]) |
|
418
|
const schemaFileName = this.getSchemaFileName(normalizedName) |
|
419
|
|
|
420
|
if ( |
|
421
|
this.isSchemaEmpty(schema) && |
|
422
|
this.hasSchemaFileContent(normalizedName) |
|
423
|
) { |
|
424
|
// the schema was only reached in a context where its properties were |
|
425
|
// cut off, such as beyond the maximum level, so writing it would |
|
426
|
// remove the properties of the previously written schema. |
|
427
|
return |
|
428
|
} |
|
429
|
|
|
430
|
ts.sys.writeFile( |
|
431
|
schemaFileName, |
|
432
|
this.formatter.addCommentsToSourceFile( |
|
433
|
formatOas(schema, `@schema ${normalizedName}`), |
|
434
|
"" |
|
435
|
) |
|
436
|
) |
|
437
|
}) |
|
438
|
} |
|
439
|
|
|
440
|
/** |
|
441
|
* Checks whether an object is a reference object. |
|
442
|
* |
|
443
|
* @param schema - The schema object to check. |
|
444
|
* @returns Whether the object is a reference object. |
|
445
|
*/ |
|
446
|
isRefObject( |
|
447
|
schema: |
|
448
|
| OpenAPIV3.ReferenceObject |
|
449
|
| OpenApiSchema |
|
450
|
| OpenAPIV3.RequestBodyObject |
|
451
|
| OpenAPIV3.ResponseObject |
|
452
|
| OpenAPIV3.ParameterObject |
|
453
|
| undefined |
|
454
|
): schema is OpenAPIV3.ReferenceObject { |
|
455
|
return schema !== undefined && "$ref" in schema |
|
456
|
} |
|
457
|
|
|
458
|
/** |
|
459
|
* Converts a tag name to a schema name. Can be used to try and retrieve the schema |
|
460
|
* associated with a tag. |
|
461
|
* |
|
462
|
* @param tagName - The name of the tag. |
|
463
|
* @returns The possible names of the associated schema. |
|
464
|
*/ |
|
465
|
tagNameToSchemaName(tagName: string, area: OasArea): string { |
|
466
|
const overrideName = TAG_SCHEMA_NAME_OVERRIDES[`${area}:${tagName}`] |
|
467
|
|
|
468
|
if (overrideName) { |
|
469
|
return overrideName |
|
470
|
} |
|
471
|
|
|
472
|
const mainSchemaName = wordsToPascal(pluralize.singular(tagName)) |
|
473
|
return `${capitalize(area)}${mainSchemaName}` |
|
474
|
} |
|
475
|
} |
|
476
|
|
|
477
|
export default OasSchemaHelper |