-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvalidate-openapi.ts
More file actions
317 lines (272 loc) · 8.45 KB
/
validate-openapi.ts
File metadata and controls
317 lines (272 loc) · 8.45 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
317
#!/usr/bin/env node
/**
* OpenAPI Spec Validator
* Checks for common issues that prevent client generation
*/
import * as fs from "fs";
import * as path from "path";
import * as yaml from "js-yaml";
interface OpenAPISpec {
openapi: string;
info: any;
paths: any;
components?: {
schemas?: Record<string, any>;
[key: string]: any;
};
[key: string]: any;
}
class OpenAPIValidator {
private spec: OpenAPISpec | null = null;
private errors: string[] = [];
private warnings: string[] = [];
constructor(private specFile: string) {}
loadSpec(): boolean {
try {
const content = fs.readFileSync(this.specFile, "utf8");
if (this.specFile.endsWith(".yaml") || this.specFile.endsWith(".yml")) {
this.spec = yaml.load(content) as OpenAPISpec;
} else {
this.spec = JSON.parse(content);
}
return true;
} catch (error) {
this.errors.push(`Failed to load spec file: ${error}`);
return false;
}
}
validateBasicStructure(): void {
if (!this.spec) return;
const requiredFields = ["openapi", "info", "paths"];
for (const field of requiredFields) {
if (!(field in this.spec)) {
this.errors.push(`Missing required field: ${field}`);
}
}
if ("openapi" in this.spec) {
const version = this.spec.openapi;
if (!version.startsWith("3.")) {
this.warnings.push(
`OpenAPI version ${version} might have compatibility issues`
);
}
}
}
extractRefs(obj: any, refs: Set<string>, path: string = ""): void {
if (obj && typeof obj === "object") {
if (Array.isArray(obj)) {
obj.forEach((item, i) => {
this.extractRefs(item, refs, `${path}[${i}]`);
});
} else {
for (const [key, value] of Object.entries(obj)) {
if (key === "$ref" && typeof value === "string") {
refs.add(value);
} else {
this.extractRefs(value, refs, `${path}.${key}`);
}
}
}
}
}
validateReferences(): void {
if (!this.spec) return;
// Extract all references
const allRefs = new Set<string>();
this.extractRefs(this.spec, allRefs);
// Check each reference
for (const ref of allRefs) {
if (!ref.startsWith("#/")) {
this.warnings.push(`External reference found: ${ref}`);
continue;
}
// Remove the leading '#/' and split by '/'
const refPath = ref.substring(2).split("/");
// Navigate through the spec to check if reference exists
let current: any = this.spec;
for (let i = 0; i < refPath.length; i++) {
const part = refPath[i];
if (current && typeof current === "object" && part in current) {
current = current[part];
} else {
this.errors.push(
`Missing schema definition: ${ref} (failed at '${part}')`
);
break;
}
}
}
}
validateDiscriminators(): void {
if (!this.spec) return;
const checkDiscriminators = (obj: any, path: string = ""): void => {
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
if ("discriminator" in obj && ("oneOf" in obj || "anyOf" in obj)) {
const discriminator = obj.discriminator;
if (
typeof discriminator === "object" &&
"propertyName" in discriminator
) {
const propName = discriminator.propertyName;
// Check if all schemas in oneOf/anyOf have the discriminator property
const schemas = obj.oneOf || obj.anyOf || [];
schemas.forEach((schema: any, i: number) => {
if (
schema &&
typeof schema === "object" &&
"properties" in schema
) {
if (!(propName in (schema.properties || {}))) {
this.warnings.push(
`Discriminator property '${propName}' not found in schema at ${path}.oneOf[${i}]`
);
}
}
});
}
}
for (const [key, value] of Object.entries(obj)) {
checkDiscriminators(value, `${path}.${key}`);
}
} else if (Array.isArray(obj)) {
obj.forEach((item, i) => {
checkDiscriminators(item, `${path}[${i}]`);
});
}
};
if (this.spec.components?.schemas) {
checkDiscriminators(this.spec.components.schemas, "components.schemas");
}
}
validateRequiredProperties(): void {
if (!this.spec) return;
const checkSchema = (schema: any, path: string): void => {
if (
schema &&
typeof schema === "object" &&
"required" in schema &&
"properties" in schema
) {
const required = schema.required;
const properties = schema.properties;
for (const prop of required) {
if (!(prop in properties)) {
this.errors.push(
`Required property '${prop}' not defined in schema at ${path}`
);
}
}
}
// Check nested schemas
if (schema && typeof schema === "object" && "properties" in schema) {
for (const [propName, propSchema] of Object.entries(
schema.properties
)) {
if (propSchema && typeof propSchema === "object") {
checkSchema(propSchema, `${path}.properties.${propName}`);
}
}
}
};
if (this.spec.components?.schemas) {
for (const [schemaName, schema] of Object.entries(
this.spec.components.schemas
)) {
if (schema && typeof schema === "object") {
checkSchema(schema, `components.schemas.${schemaName}`);
}
}
}
}
checkUnusedSchemas(): void {
if (!this.spec) return;
// Get all defined schemas
const definedSchemas = new Set<string>();
if (this.spec.components?.schemas) {
Object.keys(this.spec.components.schemas).forEach((key) =>
definedSchemas.add(key)
);
}
// Get all referenced schemas
const allRefs = new Set<string>();
this.extractRefs(this.spec, allRefs);
const referencedSchemas = new Set<string>();
for (const ref of allRefs) {
if (ref.startsWith("#/components/schemas/")) {
const schemaName = ref.split("/").pop();
if (schemaName) {
referencedSchemas.add(schemaName);
}
}
}
// Find unused schemas
const unused = [...definedSchemas].filter(
(schema) => !referencedSchemas.has(schema)
);
for (const schema of unused) {
this.warnings.push(`Unused schema definition: ${schema}`);
}
}
validate(): boolean {
if (!this.loadSpec()) {
return false;
}
console.log(`Validating OpenAPI spec: ${this.specFile}`);
console.log("-".repeat(60));
this.validateBasicStructure();
this.validateReferences();
this.validateDiscriminators();
this.validateRequiredProperties();
this.checkUnusedSchemas();
// Print results
if (this.errors.length > 0) {
console.log(`\n❌ Found ${this.errors.length} error(s):`);
for (const error of this.errors) {
console.log(` • ${error}`);
}
}
if (this.warnings.length > 0) {
console.log(`\n⚠️ Found ${this.warnings.length} warning(s):`);
for (const warning of this.warnings) {
console.log(` • ${warning}`);
}
}
if (this.errors.length === 0 && this.warnings.length === 0) {
console.log("\n✅ OpenAPI spec is valid!");
}
console.log("\n" + "-".repeat(60));
console.log(
`Summary: ${this.errors.length} errors, ${this.warnings.length} warnings`
);
return this.errors.length === 0;
}
}
function main(): void {
const args = process.argv.slice(2);
if (args.length === 0) {
console.error(
"Usage: node validate-openapi.js <spec-file> [<spec-file>...]"
);
console.error("Options:");
console.error(" --strict Treat warnings as errors");
process.exit(1);
}
const isStrict = args.includes("--strict");
const specFiles = args.filter((arg) => arg !== "--strict");
let allValid = true;
for (const specFile of specFiles) {
const validator = new OpenAPIValidator(specFile);
const isValid = validator.validate();
if (isStrict && validator["warnings"].length > 0) {
allValid = false;
} else {
allValid = allValid && isValid;
}
console.log("\n");
}
process.exit(allValid ? 0 : 1);
}
// Run if called directly
if (require.main === module) {
main();
}