-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
188 lines (174 loc) · 4.99 KB
/
index.js
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
import { readFileSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { URL, fileURLToPath } from "node:url";
import Ajv04 from "ajv-draft-04";
import addFormats from "ajv-formats";
import Ajv2020 from "ajv/dist/2020.js";
import { JSON_SCHEMA, load } from "js-yaml";
import { checkRefs, replaceRefs } from "./resolve.js";
const openApiVersions = new Set(["2.0", "3.0", "3.1"]);
const ajvVersions = {
"http://json-schema.org/draft-04/schema#": Ajv04,
"https://json-schema.org/draft/2020-12/schema": Ajv2020,
};
const inlinedRefs = "x-inlined-refs";
function localFile(fileName) {
return fileURLToPath(new URL(fileName, import.meta.url));
}
function importJSON(file) {
return JSON.parse(readFileSync(localFile(file)));
}
function getOpenApiVersion(specification) {
for (const version of openApiVersions) {
const specificationType = version === "2.0" ? "swagger" : "openapi";
const prop = specification[specificationType];
if (typeof prop === "string" && prop.startsWith(version)) {
return {
version,
specificationType,
specificationVersion: prop,
};
}
}
return {
version: undefined,
specificationType: undefined,
specificationVersion: undefined,
};
}
async function getSpecFromData(data) {
const yamlOpts = { schema: JSON_SCHEMA };
if (typeof data === "object") {
return data;
}
if (typeof data === "string") {
if (data.match(/\n/)) {
try {
return load(data, yamlOpts);
} catch (_) {
return undefined;
}
}
try {
const fileData = await readFile(data, "utf-8");
return load(fileData, yamlOpts);
} catch (_) {
return undefined;
}
}
return undefined;
}
export class Validator {
constructor(ajvOptions = {}) {
// AJV is a bit too strict in its strict validation of openAPI schemas
// so switch strict mode and validateFormats off
if (ajvOptions.strict !== "log") {
ajvOptions.strict = false;
}
this.ajvOptions = ajvOptions;
this.ajvValidators = {};
this.externalRefs = {};
}
static supportedVersions = openApiVersions;
resolveRefs(opts = {}) {
return replaceRefs(this.specification || opts.specification);
}
async addSpecRef(data, uri) {
const spec = await getSpecFromData(data);
if (spec === undefined) {
throw new Error("Cannot find JSON, YAML or filename in data");
}
const newUri = uri || spec["$id"];
if (typeof newUri !== "string") {
throw new Error("uri parameter or $id attribute must be a string");
}
spec["$id"] = newUri;
this.externalRefs[newUri] = spec;
}
async validate(data) {
const specification = await getSpecFromData(data);
this.specification = specification;
if (specification === undefined || specification === null) {
return {
valid: false,
errors: "Cannot find JSON, YAML or filename in data",
};
}
if (Object.keys(this.externalRefs).length > 0) {
specification[inlinedRefs] = this.externalRefs;
}
const { version, specificationType, specificationVersion } =
getOpenApiVersion(specification);
this.version = version;
this.specificationVersion = specificationVersion;
this.specificationType = specificationType;
if (!version) {
return {
valid: false,
errors:
"Cannot find supported swagger/openapi version in specification, version must be a string.",
};
}
const validateSchema = this.getAjvValidator(version);
// check if the specification matches the JSONschema
const schemaResult = validateSchema(specification);
// check if the references are valid as those can't be validated bu JSONschema
if (schemaResult) {
return checkRefs(specification);
}
const result = {
valid: schemaResult,
};
if (validateSchema.errors) {
result.errors = validateSchema.errors;
}
return result;
}
async validateBundle(data) {
let specification = undefined;
if (!Array.isArray(data)) {
return {
valid: false,
errors: "Parameter data must be an array",
};
}
for (const item of data) {
const spec = await getSpecFromData(item);
let fileName = undefined;
if (typeof item === "string" && !item.match(/\n/)) {
// item is a filename
fileName = item;
}
if (spec === undefined) {
throw new Error(
`Cannot find JSON, YAML or filename in ${fileName || "data"}`,
);
}
const { version } = getOpenApiVersion(spec);
if (!version) {
// it is not the main openApi specification, but a subschema
this.addSpecRef(spec, spec.$id || fileName);
continue;
}
if (specification) {
throw new Error(
"Only one openApi specification can be validated at a time",
);
}
specification = spec;
}
return this.validate(specification);
}
getAjvValidator(version) {
if (!this.ajvValidators[version]) {
const schema = importJSON(`./schemas/v${version}/schema.json`);
const schemaVersion = schema.$schema;
const AjvClass = ajvVersions[schemaVersion];
const ajv = new AjvClass(this.ajvOptions);
addFormats(ajv);
ajv.addFormat("media-range", true); // used in 3.1
this.ajvValidators[version] = ajv.compile(schema);
}
return this.ajvValidators[version];
}
}