UNPKG

jaywalk

Version:
83 lines 2.59 kB
"use strict"; var Promise = require('any-promise'); var Types = require('./types/index'); exports.Types = Types; var Formats = require('./formats/index'); exports.Formats = Formats; var Parsers = require('./parsers/index'); exports.Parsers = Parsers; var Utils = require('./utils'); exports.Utils = Utils; var error_1 = require('./support/error'); function compile(rootSchema) { var test = rootSchema._compile(); return function (root) { var errors = []; var context = { root: root, rootSchema: rootSchema, error: error }; function error(path, type, keyword, assertion, value) { var err = new error_1.ValidationError(path, type, keyword, assertion, value); errors.push(err); return err; } return test(root, [], context, Utils.identity) .catch(function (error) { if (!(error instanceof error_1.ValidationError)) { return Promise.reject(error); } return Promise.reject(errors.length ? new error_1.MultiError(errors) : error); }); }; } exports.compile = compile; function assert(rootSchema, root) { var context = { root: root, rootSchema: rootSchema, error: error }; function error(path, type, keyword, assertion, value) { return new error_1.ValidationError(path, type, keyword, assertion, value); } return rootSchema._isType(root, [], context); } exports.assert = assert; function is(schema, value) { try { return assert(schema, value); } catch (err) { return 0; } } exports.is = is; function bestSchema(schemas, value) { var type; var score = 0; for (var _i = 0, schemas_1 = schemas; _i < schemas_1.length; _i++) { var schema = schemas_1[_i]; var subscore = is(schema, value); if (subscore > score) { type = schema; score = subscore; } } if (score === 0) { throw new TypeError('Value does not match any schemas in set'); } return type; } exports.bestSchema = bestSchema; function bestValue(list) { var result; var score = 0; for (var _i = 0, list_1 = list; _i < list_1.length; _i++) { var _a = list_1[_i], schema = _a[0], value = _a[1]; var subscore = is(schema, value); if (subscore > score) { result = value; score = subscore; } } if (score === 0) { throw new TypeError('No matching values found in set'); } return result; } exports.bestValue = bestValue; //# sourceMappingURL=index.js.map