UNPKG

@stoplight/spectral

Version:

A flexible object linter with out of the box support for OpenAPI v2 and v3.

86 lines 3.14 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const json_1 = require("@stoplight/json"); const AJV = require("ajv"); const jsonSpecv4 = require("ajv/lib/refs/json-schema-draft-04.json"); const oasFormatValidator = require('ajv-oai/lib/format-validator'); const ajv = new AJV({ meta: false, schemaId: 'auto', jsonPointers: true, unknownFormats: 'ignore', }); ajv.addMetaSchema(jsonSpecv4); ajv._opts.defaultMeta = jsonSpecv4.id; ajv._refs['http://json-schema.org/schema'] = 'http://json-schema.org/draft-04/schema'; ajv.addFormat('int32', { type: 'number', validate: oasFormatValidator.int32 }); ajv.addFormat('int64', { type: 'number', validate: oasFormatValidator.int64 }); ajv.addFormat('float', { type: 'number', validate: oasFormatValidator.float }); ajv.addFormat('double', { type: 'number', validate: oasFormatValidator.double }); ajv.addFormat('byte', { type: 'string', validate: oasFormatValidator.byte }); const formatPath = (path) => path .split('/') .slice(1) .map(json_1.decodePointerFragment); const mergeErrors = (existingError, newError) => { switch (newError.keyword) { case 'additionalProperties': { const { additionalProperty } = newError.params; if (!new RegExp(`[:,] ${additionalProperty}`).test(existingError.message)) { existingError.message += `, ${newError.params.additionalProperty}`; } return true; } default: return existingError.message === newError.message; } }; exports.schema = (targetVal, opts, paths) => { const results = []; const path = paths.target || paths.given; if (!targetVal) return [ { path, message: `${paths ? path.join('.') : 'property'} does not exist`, }, ]; const { schema: schemaObj } = opts; try { if (!ajv.validate(schemaObj, targetVal) && ajv.errors) { const collectedErrors = []; for (const error of ajv.errors) { if (collectedErrors.length > 0) { const index = collectedErrors.indexOf(error.keyword); if (index !== -1) { if (mergeErrors(results[index], error)) continue; } } let message = error.message || ''; if (error.keyword === 'additionalProperties' && error.params.additionalProperty) { message += `: ${error.params.additionalProperty}`; } collectedErrors.push(error.keyword); results.push({ path: [...path, ...formatPath(error.dataPath)], message, }); } } } catch (ex) { if (ex instanceof AJV.MissingRefError) { results.push({ message: ex.message, path, }); } else { throw ex; } } return results; }; //# sourceMappingURL=schema.js.map