validate.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. Object.defineProperty(exports, "ValidationError", {
  6. enumerable: true,
  7. get: function () {
  8. return _ValidationError.default;
  9. }
  10. });
  11. exports.disableValidation = disableValidation;
  12. exports.enableValidation = enableValidation;
  13. exports.needValidate = needValidate;
  14. exports.validate = validate;
  15. var _ValidationError = _interopRequireDefault(require("./ValidationError"));
  16. var _memorize = _interopRequireDefault(require("./util/memorize"));
  17. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  18. const getAjv = (0, _memorize.default)(() => {
  19. // Use CommonJS require for ajv libs so TypeScript consumers aren't locked into esModuleInterop (see #110).
  20. // eslint-disable-next-line global-require
  21. const Ajv = require("ajv").default;
  22. // eslint-disable-next-line global-require
  23. const ajvKeywords = require("ajv-keywords").default;
  24. // eslint-disable-next-line global-require
  25. const addFormats = require("ajv-formats").default;
  26. /**
  27. * @type {Ajv}
  28. */
  29. const ajv = new Ajv({
  30. strict: false,
  31. allErrors: true,
  32. verbose: true,
  33. $data: true
  34. });
  35. ajvKeywords(ajv, ["instanceof", "patternRequired"]);
  36. addFormats(ajv, {
  37. keywords: true
  38. });
  39. // Custom keywords
  40. // eslint-disable-next-line global-require
  41. const addAbsolutePathKeyword = require("./keywords/absolutePath").default;
  42. addAbsolutePathKeyword(ajv);
  43. const addUndefinedAsNullKeyword =
  44. // eslint-disable-next-line global-require
  45. require("./keywords/undefinedAsNull").default;
  46. addUndefinedAsNullKeyword(ajv);
  47. return ajv;
  48. });
  49. /** @typedef {import("json-schema").JSONSchema4} JSONSchema4 */
  50. /** @typedef {import("json-schema").JSONSchema6} JSONSchema6 */
  51. /** @typedef {import("json-schema").JSONSchema7} JSONSchema7 */
  52. /** @typedef {import("ajv").ErrorObject} ErrorObject */
  53. /**
  54. * @typedef {Object} Extend
  55. * @property {string=} formatMinimum
  56. * @property {string=} formatMaximum
  57. * @property {string=} formatExclusiveMinimum
  58. * @property {string=} formatExclusiveMaximum
  59. * @property {string=} link
  60. * @property {boolean=} undefinedAsNull
  61. */
  62. /** @typedef {(JSONSchema4 | JSONSchema6 | JSONSchema7) & Extend} Schema */
  63. /** @typedef {ErrorObject & { children?: Array<ErrorObject> }} SchemaUtilErrorObject */
  64. /**
  65. * @callback PostFormatter
  66. * @param {string} formattedError
  67. * @param {SchemaUtilErrorObject} error
  68. * @returns {string}
  69. */
  70. /**
  71. * @typedef {Object} ValidationErrorConfiguration
  72. * @property {string=} name
  73. * @property {string=} baseDataPath
  74. * @property {PostFormatter=} postFormatter
  75. */
  76. /**
  77. * @param {SchemaUtilErrorObject} error
  78. * @param {number} idx
  79. * @returns {SchemaUtilErrorObject}
  80. */
  81. function applyPrefix(error, idx) {
  82. // eslint-disable-next-line no-param-reassign
  83. error.instancePath = `[${idx}]${error.instancePath}`;
  84. if (error.children) {
  85. error.children.forEach(err => applyPrefix(err, idx));
  86. }
  87. return error;
  88. }
  89. let skipValidation = false;
  90. // We use `process.env.SKIP_VALIDATION` because you can have multiple `schema-utils` with different version,
  91. // so we want to disable it globally, `process.env` doesn't supported by browsers, so we have the local `skipValidation` variables
  92. // Enable validation
  93. function enableValidation() {
  94. skipValidation = false;
  95. // Disable validation for any versions
  96. if (process && process.env) {
  97. process.env.SKIP_VALIDATION = "n";
  98. }
  99. }
  100. // Disable validation
  101. function disableValidation() {
  102. skipValidation = true;
  103. if (process && process.env) {
  104. process.env.SKIP_VALIDATION = "y";
  105. }
  106. }
  107. // Check if we need to confirm
  108. function needValidate() {
  109. if (skipValidation) {
  110. return false;
  111. }
  112. if (process && process.env && process.env.SKIP_VALIDATION) {
  113. const value = process.env.SKIP_VALIDATION.trim();
  114. if (/^(?:y|yes|true|1|on)$/i.test(value)) {
  115. return false;
  116. }
  117. if (/^(?:n|no|false|0|off)$/i.test(value)) {
  118. return true;
  119. }
  120. }
  121. return true;
  122. }
  123. /**
  124. * @param {Schema} schema
  125. * @param {Array<object> | object} options
  126. * @param {ValidationErrorConfiguration=} configuration
  127. * @returns {void}
  128. */
  129. function validate(schema, options, configuration) {
  130. if (!needValidate()) {
  131. return;
  132. }
  133. let errors = [];
  134. if (Array.isArray(options)) {
  135. for (let i = 0; i <= options.length - 1; i++) {
  136. errors.push(...validateObject(schema, options[i]).map(err => applyPrefix(err, i)));
  137. }
  138. } else {
  139. errors = validateObject(schema, options);
  140. }
  141. if (errors.length > 0) {
  142. throw new _ValidationError.default(errors, schema, configuration);
  143. }
  144. }
  145. /**
  146. * @param {Schema} schema
  147. * @param {Array<object> | object} options
  148. * @returns {Array<SchemaUtilErrorObject>}
  149. */
  150. function validateObject(schema, options) {
  151. // Not need to cache, because `ajv@8` has built-in cache
  152. const compiledSchema = getAjv().compile(schema);
  153. const valid = compiledSchema(options);
  154. if (valid) return [];
  155. return compiledSchema.errors ? filterErrors(compiledSchema.errors) : [];
  156. }
  157. /**
  158. * @param {Array<ErrorObject>} errors
  159. * @returns {Array<SchemaUtilErrorObject>}
  160. */
  161. function filterErrors(errors) {
  162. /** @type {Array<SchemaUtilErrorObject>} */
  163. let newErrors = [];
  164. for (const error of /** @type {Array<SchemaUtilErrorObject>} */errors) {
  165. const {
  166. instancePath
  167. } = error;
  168. /** @type {Array<SchemaUtilErrorObject>} */
  169. let children = [];
  170. newErrors = newErrors.filter(oldError => {
  171. if (oldError.instancePath.includes(instancePath)) {
  172. if (oldError.children) {
  173. children = children.concat(oldError.children.slice(0));
  174. }
  175. // eslint-disable-next-line no-undefined, no-param-reassign
  176. oldError.children = undefined;
  177. children.push(oldError);
  178. return false;
  179. }
  180. return true;
  181. });
  182. if (children.length) {
  183. error.children = children;
  184. }
  185. newErrors.push(error);
  186. }
  187. return newErrors;
  188. }