-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
397 lines (357 loc) · 11.2 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
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/**
* @copyright Copyright 2017-2019 Kevin Locke <[email protected]>
* @license MIT
* @module modulename
*/
'use strict';
const fs = require('node:fs');
const http = require('node:http');
const https = require('node:https');
// stream.Writable (and therefore http.ClientRequest) accept any Uint8Array
const { types: { isUint8Array } } = require('node:util');
const packageJson = require('./package.json');
/** @exports swagger-spec-validator */
const swaggerSpecValidator = {};
/** JSON Content-Type accepted by validator.swagger.io.
*
* @constant
* @private
*/
const JSON_CONTENT_TYPE = 'application/json';
/** YAML Content-Type accepted by validator.swagger.io.
* See https://github.com/swagger-api/validator-badge/issues/136
*
* @constant
* @private
*/
const YAML_CONTENT_TYPE = 'application/yaml';
/** Default URL to which validation requests are sent.
*
* @constant
*/
const DEFAULT_URL = 'https://validator.swagger.io/validator/debug';
swaggerSpecValidator.DEFAULT_URL = DEFAULT_URL;
/** Default headers sent with API requests.
*
* @constant
*/
const DEFAULT_HEADERS = Object.freeze({
Accept: JSON_CONTENT_TYPE,
'User-Agent': `${packageJson.name}/${packageJson.version} `
+ `Node.js/${process.version.slice(1)}`,
});
swaggerSpecValidator.DEFAULT_HEADERS = DEFAULT_HEADERS;
/** Combines HTTP headers objects.
* With the capitalization and value of the last occurrence.
*
* @private
*/
function combineHeaders(...args) {
const combinedLower = {};
const combined = {};
args.reverse();
for (const headers of args) {
if (headers) {
for (const name of Object.keys(headers)) {
const nameLower = name.toLowerCase();
if (!Object.hasOwn(combinedLower, nameLower)) {
combinedLower[nameLower] = true;
combined[name] = headers[name];
}
}
}
}
return combined;
}
/** Reads all data from a stream.Readable.
*
* @private
* @param {!module:stream.Readable} stream Stream from which to read all data.
* @returns {string|Buffer} Data from stream, if any.
*/
function getStreamData(stream) {
return new Promise((resolve, reject) => {
const chunks = [];
stream
.on('data', (chunk) => chunks.push(chunk))
.once('error', reject)
.once(
'end',
() => resolve(
chunks.length === 0 ? undefined
: Buffer.isBuffer(chunks[0]) ? Buffer.concat(chunks)
: typeof chunks[0] === 'string' ? chunks.join('')
: chunks,
),
);
});
}
/** Makes an HTTP(S) request and parses the JSON response.
*
* @private
*/
function requestJson(url, options, callback) {
const protocol = options.protocol || url.protocol;
const proto = protocol === 'https:' ? https
: protocol === 'http:' ? http
: undefined;
if (!proto) {
callback(
new Error(`Unsupported protocol "${protocol}" for validator URL`),
);
return;
}
// http.request and https.request only accept string or URL as url argument.
// This module allows url object since it is unambiguous in named options.
// If url is not a URL, combine with options.
const req =
url instanceof URL ? proto.request(url, options)
: proto.request({
...url,
...options,
});
req
.once('error', callback)
.once('response', (res) => {
res.on('error', callback);
const bodyData = [];
res.on('data', (data) => { bodyData.push(data); });
res.on('end', () => {
const resBody = Buffer.concat(bodyData);
let err, resBodyObj;
try {
resBodyObj = JSON.parse(resBody.toString());
} catch (errJson) {
err = new SyntaxError(
`Error parsing server response as JSON: ${errJson.message}`,
);
}
// Note: Could redirect using follow-redirects, axios, got, node-fetch
// No known use case, since user should update -u to avoid overhead.
// If you have a use case, feel free to open an issue.
if (res.statusCode >= 300) {
let errMessage = `HTTP ${res.statusCode}`;
if (res.statusMessage) {
errMessage += `: ${res.statusMessage}`;
}
const { location } = res.headers;
if (location) {
errMessage += `: ${location}`;
}
err = new Error(errMessage);
}
if (err) {
err.statusCode = res.statusCode;
err.statusMessage = res.statusMessage;
err.headers = res.headers;
err.trailers = res.trailers;
err.body = resBodyObj !== undefined ? resBodyObj : resBody;
callback(err);
} else {
// Use null to preserve current API.
// eslint-disable-next-line unicorn/no-null
callback(null, resBodyObj);
}
});
});
const { body } = options;
if (typeof body === 'string' || isUint8Array(body)) {
req.end(body);
} else {
body.on('error', (err) => {
req.abort();
callback(err);
});
body.pipe(req);
}
}
/** Guesses Content-Type of OpenAPI/Swagger spec data.
*
* @private
* @param {string|!Uint8Array} spec OpenAPI/Swagger API specification content.
* @returns {string} Content type of spec.
*/
function guessSpecDataContentType(spec, options) {
try {
JSON.parse(spec);
return JSON_CONTENT_TYPE;
} catch {
if (options.verbosity >= 1) {
options.err.write(
'Unable to parse spec content as JSON. Assuming YAML.\n',
);
}
return YAML_CONTENT_TYPE;
}
}
/** Guesses Content-Type of OpenAPI/Swagger spec data or stream.
*
* Note: All current versions of the OpenAPI Specification require OpenAPI
* documents to be JSON or YAML, so this function attempts to distinguish
* between only those two types.
*
* @private
* @param {string|!Uint8Array|!module:stream.Readable} spec OpenAPI/Swagger API
* specification content.
*/
function guessSpecContentType(spec, options) {
let contentType;
if (typeof spec === 'string' || isUint8Array(spec)) {
contentType = guessSpecDataContentType(spec, options);
} else if (spec.path) {
// fs.ReadStream#path is string or Buffer with file path.
if (/\.json$/i.test(spec.path)) {
contentType = JSON_CONTENT_TYPE;
} else if (/\.ya?ml$/i.test(spec.path)) {
contentType = YAML_CONTENT_TYPE;
}
}
if (contentType) {
return Promise.resolve({ contentType });
}
if (options.verbosity >= 1) {
options.err.write(
'Content-Type not specified and can\'t be inferred from filename.\n'
+ 'Reading spec content...\n',
);
}
return getStreamData(spec)
.then((specContent) => ({
contentType: guessSpecDataContentType(specContent, options),
specContent,
}));
}
/** Validation options
*
* @typedef {{
* err: (module:stream.Writable|undefined),
* request: (object|undefined),
* url: (URL|object|string|undefined),
* verbosity: (number|undefined)
* }} ValidateOptions
* @property {module:stream.Writable=} err Stream to which errors (and
* non-output status messages) are written.
* (default: <code>process.stderr</code>)
* @property {object=} request Options passed to <code>http.request()</code>.
* @property {URL|object|string=} url URL passed to <code>http.request()</code>.
* @property {number=} verbosity Amount of output to produce. Larger numbers
* produce more output.
*/
// var ValidateOptions;
/** Validates an OpenAPI/Swagger API specification.
*
* @param {string|!Uint8Array|!module:stream.Readable} spec OpenAPI/Swagger API
* specification content.
* @param {ValidateOptions=} options Validation options.
* @param {?function(Error, object=)=} callback Callback for the validation
* results object.
* @returns {Promise<object>|undefined} If <code>callback</code> is not given,
* a <code>Promise</code> with the validation results or <code>Error</code>.
*/
swaggerSpecValidator.validate =
function validate(spec, options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = undefined;
}
if (!callback) {
return new Promise((resolve, reject) => {
validate(spec, options, (err, result) => {
if (err) { reject(err); } else { resolve(result); }
});
});
}
if (typeof callback !== 'function') {
throw new TypeError('callback must be a function');
}
try {
if (spec === undefined
|| spec === null
|| (typeof spec !== 'string'
&& !isUint8Array(spec)
&& typeof spec.pipe !== 'function')) {
throw new TypeError('spec must be a string, Uint8Array, or Readable');
}
if (options !== undefined && options !== null) {
if (typeof options !== 'object') {
throw new TypeError('options must be an object');
}
if (options.err !== undefined
&& options.err !== null
&& typeof options.err.write !== 'function') {
throw new TypeError('options.err must be a stream.Writable');
}
}
} catch (err) {
queueMicrotask(() => callback(err));
return undefined;
}
options = { ...options };
options.err ||= process.stderr;
// Note: Options on URL object are ignored by https.request()
// Don't combine into single options object without conversion to generic obj.
const reqUrl =
!options.url ? new URL(DEFAULT_URL)
: typeof options.url === 'object' ? options.url
: new URL(options.url);
const reqOpts = {
method: 'POST',
...options.request,
body: spec,
};
reqOpts.headers =
reqOpts.headers
? combineHeaders(DEFAULT_HEADERS, reqOpts.headers || reqUrl.headers)
: { ...DEFAULT_HEADERS };
let calledBack = false;
function callbackOnce(...args) {
if (!calledBack) {
calledBack = true;
callback.apply(this, args);
}
}
let contentInfoP;
if (!Object.keys(reqOpts.headers)
.some((name) => name.toLowerCase() === 'content-type')) {
contentInfoP = guessSpecContentType(spec, options);
} else {
// Use null to preserve current API.
// eslint-disable-next-line unicorn/no-null
contentInfoP = Promise.resolve(null);
}
contentInfoP
.then((contentInfo) => {
if (contentInfo) {
const { contentType, specContent } = contentInfo;
reqOpts.headers['Content-Type'] = contentType;
if (specContent) {
reqOpts.body = specContent;
}
}
requestJson(reqUrl, reqOpts, callbackOnce);
})
.catch(callbackOnce);
return undefined;
};
/** Validates an OpenAPI/Swagger API specification file.
*
* If not specified, the Content-Type header will be set for <code>.json</code>
* and <code>.yaml</code>/<code>.yml</code> files.
*
* @param {string} specPath Path of OpenAPI/Swagger API specification file.
* @param {ValidateOptions=} options Validation options.
* @param {?function(Error, object=)=} callback Callback for the validation
* results object.
* @returns {Promise<object>|undefined} If <code>callback</code> is not given,
* a <code>Promise</code> with the validation results or <code>Error</code>.
*/
swaggerSpecValidator.validateFile =
function validateFile(specPath, options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = undefined;
}
const specStream = fs.createReadStream(specPath);
return swaggerSpecValidator.validate(specStream, options, callback);
};
module.exports = swaggerSpecValidator;