Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'oas-validator' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
let resultStr2 = yaml.stringify(result); // FIXME dropped 'noRefs:true' here
should(resultStr).not.be.exactly('{}','Result should not be empty');
should(resultStr).equal(resultStr2,'Result should have no object identity ref_s');
}
catch (ex) {
if (options.verbose>1) {
fs.writeFileSync('./debug.yaml',resultStr,'utf8');
console.warn('Result dumped to debug.yaml fixed.yaml');
let fix = reref(result);
fs.writeFileSync('./fixed.yaml',yaml.stringify(fix),'utf8');
}
should.fail(false,true,'Result cannot be represented safely in YAML');
}
}
validator.validate(result, options)
.then(function(options){
finalise(null,options);
})
.catch(function(ex){
finalise(ex,options);
});
}
catch (ex) {
console.warn(common.colour.normal + options.file);
console.warn(common.colour.red + (options.context.length ? options.context.pop() : 'No context')+ '\n' + ex.message);
if (ex.stack && ex.name !== 'AssertionError' && ex.name !== 'CLIError') {
console.warn(ex.stack);
}
options.valid = !options.expectFailure;
finalise(ex, options);
}
return __awaiter(this, void 0, void 0, function* () {
// CASE: translate
if (typeof spec.swagger === 'string' &&
spec.swagger === '2.0') {
preprocessingLog(`Received OpenAPI Specification 2.0 - going to translate...`);
const result = yield Swagger2OpenAPI.convertObj(spec, {});
return result.openapi;
// CASE: validate
}
else if (typeof spec.openapi === 'string' &&
/^3/.test(spec.openapi)) {
preprocessingLog(`Received OpenAPI Specification 3.0.x - going to validate...`);
const valid = OASValidator.validateSync(spec, {});
if (!valid) {
throw new Error(`Validation of OpenAPI Specification failed.`);
}
preprocessingLog(`OpenAPI Specification is validated`);
return spec;
}
else {
throw new Error(`Invalid specification provided`);
}
});
}
) {
preprocessingLog(
`Received OpenAPI Specification 2.0 - going to translate...`
)
const result: { openapi: Oas3 } = await Swagger2OpenAPI.convertObj(spec, {})
return result.openapi as Oas3
// CASE: validate
} else if (
typeof (spec as Oas3).openapi === 'string' &&
/^3/.test((spec as Oas3).openapi)
) {
preprocessingLog(
`Received OpenAPI Specification 3.0.x - going to validate...`
)
const valid = OASValidator.validateSync(spec, {})
if (!valid) {
throw new Error(`Validation of OpenAPI Specification failed.`)
}
preprocessingLog(`OpenAPI Specification is validated`)
return spec as Oas3
} else {
throw new Error(`Invalid specification provided`)
}
}
let editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showWarningMessage('You must have an open editor window to validate an OpenAPI document');
return; // No open text editor
}
if (resolve && editor.document.isUntitled) {
vscode.window.showWarningMessage('Document must be saved in order to resolve correctly');
return; // No open text editor
}
let text = editor.document.getText();
try {
let options = { lint: lint, resolve: resolve, fatal: true, source: editor.document.fileName };
let obj = yaml.parse(text);
validator.validate(obj, options)
.then(function(){
vscode.window.showInformationMessage('Your OpenAPI document is '+(lint ? 'excellent!' : 'valid.'));
})
.catch(function(ex){
dc.delete(editor.document.uri);
const diagnostics = [];
let range; // TODO
diagnostics.push(new vscode.Diagnostic(range, ex.message, vscode.DiagnosticSeverity.Error));
for (let warning of options.warnings||[]) {
diagnostics.push(new vscode.Diagnostic(range, warning.message + ' ' + warning.ruleName, vscode.DiagnosticSeverity.Warning));
}
dc.set(editor.document.uri, diagnostics);
});
}
catch (ex) {
vscode.window.showErrorMessage('Could not parse OpenAPI document as JSON or YAML!');
} catch (e) {
console.error('Can not dereference the JSON obtained from the content of the Swagger specification file');
console.error(e);
return;
}
try {
bundledJSON = await bundle(dereferencedJSON);
} catch (e) {
console.error('Can not bundle the JSON obtained from the content of the Swagger specification file');
console.error(e);
return;
}
try {
validator.validateSync(bundledJSON, {});
} catch (e) {
console.error('Invalid OpenAPI file');
console.error(e);
return;
}
return JSON.parse(JSON.stringify(bundledJSON));
}
exports.validate = function(spec, options = {}, cb) {
if (spec.openapi) {
const validator = require('oas-validator');
const validateOptions = { prettify: false, lint: false, validateSchema: 'first' };
let valid = false;
const paths = options.mainFile ? { mainFile: options.mainFile } : calcPaths(options.basedir);
try {
valid = validator.validateSync(spec, validateOptions);
} catch (e) {
if (e instanceof validator.JSONSchemaError) {
console.error(chalk.red('Failed OpenAPI3 schema validation:\n'));
const errors = JSON.parse(e.message.replace(/^.*\[/, '['));
betterErrors(errors, paths);
} else {
console.error(chalk.red(`Lint error:\n`));
e.keyword = '__lint';
e.dataPath = validateOptions.context.pop() || '';
if (e.dataPath.startsWith('#')) {
e.dataPath = e.dataPath.substring(1);
}
console.log(e.dataPath);
betterErrors([e], paths);
}
return cb(true, {});
}).then(async function(body) {
var obj = getObj(body,payload);
var options = { source: req.query.url, resolve:true };
try {
result.status = await validator.validateSync(obj,options);
result.openapi = options.openapi.openapi || false;
}
catch(ex) {
result.message = ex.message||'No message';
console.warn(ex);
result.context = options.context.pop();
result.openapi = obj.openapi || false;
}
if (badge) {
status.badges++;
if (result.status) {
res.redirect('https://img.shields.io/badge/OpenAPI3-Valid-brightgreen.svg');
}
else {
res.redirect('https://img.shields.io/badge/OpenAPI3-Invalid-red.svg');
}
argv.prettify = true;
}
if (argv.internal) {
argv.resolveInternal = true;
}
let options = {};
let result = false;
let jsonOutput = {};
try {
if (argv.source.startsWith('http')) {
options = await swagger2openapi.convertUrl(argv.source,argv);
}
else {
options = await swagger2openapi.convertFile(argv.source,argv);
}
result = await validator.validateSync(options.openapi,options);
}
catch (ex) {
let path;
if (options.context) {
path = options.context.pop();
}
if (options.json) {
jsonOutput.error = ex.message;
if (options.verbose > 1) jsonOutput.stacktrace = ex.stack;
if (path) {
jsonOutput.path = path;
}
}
else {
console.warn(ex.message);
if (options.verbose > 1) console.warn(ex.stack);
converter.convert(obj,options,async function(err,options){
if (err) {
result.message = err.message||'no message';
result.options = sanitise(result.options);
}
else {
result = options.openapi;
if (options.openapi && options.openapi.openapi && options.openapi.openapi.startsWith('3.')) payload.status = 200;
}
if (validate && !err) {
status.validations++;
try {
result = {};
result.status = await validator.validateSync(options.openapi,options);
if (result.status === true) payload.status = 200;
}
catch (ex) {
result.message = ex.message;
console.warn(ex);
if (options && options.context) {
result.context = options.context.pop();
}
}
}
finishConversion(res,result,payload);
});
}
if (defaults.verbose) console.log(message);
}
for (let w of result.warnings) {
let message = {};
message.level = 'Warning';
message.elementType = 'Path';
message.message = w.message;
message.elementId = w.path.join('/');
obj.messages.push(message);
if (defaults.verbose) console.log(message);
}
}
});
}
else try {
validator(api,vOptions);
message.level = 'Valid';
message.elementType = 'Context';
message.elementId = 'None';
message.message = 'No validation errors detected';
obj.messages.push(message);
if (defaults.verbose) console.log(message);
}
catch (ex) {
message.level = 'Error';
message.elementType = 'Context';
message.elementId = vOptions.context.pop();
message.message = ex.message;
obj.messages.push(message);
console.error(message);
}