tv4.js 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681
  1. /*
  2. Author: Geraint Luff and others
  3. Year: 2013
  4. This code is released into the "public domain" by its author(s). Anybody may use, alter and distribute the code without restriction. The author makes no guarantees, and takes no liability of any kind for use of this code.
  5. If you find a bug or make an improvement, it would be courteous to let the author know, but it is not compulsory.
  6. */
  7. (function (global, factory) {
  8. if (typeof define === 'function' && define.amd) {
  9. // AMD. Register as an anonymous module.
  10. define([], factory);
  11. } else if (typeof module !== 'undefined' && module.exports){
  12. // CommonJS. Define export.
  13. module.exports = factory();
  14. } else {
  15. // Browser globals
  16. global.tv4 = factory();
  17. }
  18. }(this, function () {
  19. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FObject%2Fkeys
  20. if (!Object.keys) {
  21. Object.keys = (function () {
  22. var hasOwnProperty = Object.prototype.hasOwnProperty,
  23. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  24. dontEnums = [
  25. 'toString',
  26. 'toLocaleString',
  27. 'valueOf',
  28. 'hasOwnProperty',
  29. 'isPrototypeOf',
  30. 'propertyIsEnumerable',
  31. 'constructor'
  32. ],
  33. dontEnumsLength = dontEnums.length;
  34. return function (obj) {
  35. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  36. throw new TypeError('Object.keys called on non-object');
  37. }
  38. var result = [];
  39. for (var prop in obj) {
  40. if (hasOwnProperty.call(obj, prop)) {
  41. result.push(prop);
  42. }
  43. }
  44. if (hasDontEnumBug) {
  45. for (var i=0; i < dontEnumsLength; i++) {
  46. if (hasOwnProperty.call(obj, dontEnums[i])) {
  47. result.push(dontEnums[i]);
  48. }
  49. }
  50. }
  51. return result;
  52. };
  53. })();
  54. }
  55. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
  56. if (!Object.create) {
  57. Object.create = (function(){
  58. function F(){}
  59. return function(o){
  60. if (arguments.length !== 1) {
  61. throw new Error('Object.create implementation only accepts one parameter.');
  62. }
  63. F.prototype = o;
  64. return new F();
  65. };
  66. })();
  67. }
  68. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2FisArray
  69. if(!Array.isArray) {
  70. Array.isArray = function (vArg) {
  71. return Object.prototype.toString.call(vArg) === "[object Array]";
  72. };
  73. }
  74. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2FindexOf
  75. if (!Array.prototype.indexOf) {
  76. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  77. if (this === null) {
  78. throw new TypeError();
  79. }
  80. var t = Object(this);
  81. var len = t.length >>> 0;
  82. if (len === 0) {
  83. return -1;
  84. }
  85. var n = 0;
  86. if (arguments.length > 1) {
  87. n = Number(arguments[1]);
  88. if (n !== n) { // shortcut for verifying if it's NaN
  89. n = 0;
  90. } else if (n !== 0 && n !== Infinity && n !== -Infinity) {
  91. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  92. }
  93. }
  94. if (n >= len) {
  95. return -1;
  96. }
  97. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  98. for (; k < len; k++) {
  99. if (k in t && t[k] === searchElement) {
  100. return k;
  101. }
  102. }
  103. return -1;
  104. };
  105. }
  106. // Grungey Object.isFrozen hack
  107. if (!Object.isFrozen) {
  108. Object.isFrozen = function (obj) {
  109. var key = "tv4_test_frozen_key";
  110. while (obj.hasOwnProperty(key)) {
  111. key += Math.random();
  112. }
  113. try {
  114. obj[key] = true;
  115. delete obj[key];
  116. return false;
  117. } catch (e) {
  118. return true;
  119. }
  120. };
  121. }
  122. // Based on: https://github.com/geraintluff/uri-templates, but with all the de-substitution stuff removed
  123. var uriTemplateGlobalModifiers = {
  124. "+": true,
  125. "#": true,
  126. ".": true,
  127. "/": true,
  128. ";": true,
  129. "?": true,
  130. "&": true
  131. };
  132. var uriTemplateSuffices = {
  133. "*": true
  134. };
  135. function notReallyPercentEncode(string) {
  136. return encodeURI(string).replace(/%25[0-9][0-9]/g, function (doubleEncoded) {
  137. return "%" + doubleEncoded.substring(3);
  138. });
  139. }
  140. function uriTemplateSubstitution(spec) {
  141. var modifier = "";
  142. if (uriTemplateGlobalModifiers[spec.charAt(0)]) {
  143. modifier = spec.charAt(0);
  144. spec = spec.substring(1);
  145. }
  146. var separator = "";
  147. var prefix = "";
  148. var shouldEscape = true;
  149. var showVariables = false;
  150. var trimEmptyString = false;
  151. if (modifier === '+') {
  152. shouldEscape = false;
  153. } else if (modifier === ".") {
  154. prefix = ".";
  155. separator = ".";
  156. } else if (modifier === "/") {
  157. prefix = "/";
  158. separator = "/";
  159. } else if (modifier === '#') {
  160. prefix = "#";
  161. shouldEscape = false;
  162. } else if (modifier === ';') {
  163. prefix = ";";
  164. separator = ";";
  165. showVariables = true;
  166. trimEmptyString = true;
  167. } else if (modifier === '?') {
  168. prefix = "?";
  169. separator = "&";
  170. showVariables = true;
  171. } else if (modifier === '&') {
  172. prefix = "&";
  173. separator = "&";
  174. showVariables = true;
  175. }
  176. var varNames = [];
  177. var varList = spec.split(",");
  178. var varSpecs = [];
  179. var varSpecMap = {};
  180. for (var i = 0; i < varList.length; i++) {
  181. var varName = varList[i];
  182. var truncate = null;
  183. if (varName.indexOf(":") !== -1) {
  184. var parts = varName.split(":");
  185. varName = parts[0];
  186. truncate = parseInt(parts[1], 10);
  187. }
  188. var suffices = {};
  189. while (uriTemplateSuffices[varName.charAt(varName.length - 1)]) {
  190. suffices[varName.charAt(varName.length - 1)] = true;
  191. varName = varName.substring(0, varName.length - 1);
  192. }
  193. var varSpec = {
  194. truncate: truncate,
  195. name: varName,
  196. suffices: suffices
  197. };
  198. varSpecs.push(varSpec);
  199. varSpecMap[varName] = varSpec;
  200. varNames.push(varName);
  201. }
  202. var subFunction = function (valueFunction) {
  203. var result = "";
  204. var startIndex = 0;
  205. for (var i = 0; i < varSpecs.length; i++) {
  206. var varSpec = varSpecs[i];
  207. var value = valueFunction(varSpec.name);
  208. if (value === null || value === undefined || (Array.isArray(value) && value.length === 0) || (typeof value === 'object' && Object.keys(value).length === 0)) {
  209. startIndex++;
  210. continue;
  211. }
  212. if (i === startIndex) {
  213. result += prefix;
  214. } else {
  215. result += (separator || ",");
  216. }
  217. if (Array.isArray(value)) {
  218. if (showVariables) {
  219. result += varSpec.name + "=";
  220. }
  221. for (var j = 0; j < value.length; j++) {
  222. if (j > 0) {
  223. result += varSpec.suffices['*'] ? (separator || ",") : ",";
  224. if (varSpec.suffices['*'] && showVariables) {
  225. result += varSpec.name + "=";
  226. }
  227. }
  228. result += shouldEscape ? encodeURIComponent(value[j]).replace(/!/g, "%21") : notReallyPercentEncode(value[j]);
  229. }
  230. } else if (typeof value === "object") {
  231. if (showVariables && !varSpec.suffices['*']) {
  232. result += varSpec.name + "=";
  233. }
  234. var first = true;
  235. for (var key in value) {
  236. if (!first) {
  237. result += varSpec.suffices['*'] ? (separator || ",") : ",";
  238. }
  239. first = false;
  240. result += shouldEscape ? encodeURIComponent(key).replace(/!/g, "%21") : notReallyPercentEncode(key);
  241. result += varSpec.suffices['*'] ? '=' : ",";
  242. result += shouldEscape ? encodeURIComponent(value[key]).replace(/!/g, "%21") : notReallyPercentEncode(value[key]);
  243. }
  244. } else {
  245. if (showVariables) {
  246. result += varSpec.name;
  247. if (!trimEmptyString || value !== "") {
  248. result += "=";
  249. }
  250. }
  251. if (varSpec.truncate != null) {
  252. value = value.substring(0, varSpec.truncate);
  253. }
  254. result += shouldEscape ? encodeURIComponent(value).replace(/!/g, "%21"): notReallyPercentEncode(value);
  255. }
  256. }
  257. return result;
  258. };
  259. subFunction.varNames = varNames;
  260. return {
  261. prefix: prefix,
  262. substitution: subFunction
  263. };
  264. }
  265. function UriTemplate(template) {
  266. if (!(this instanceof UriTemplate)) {
  267. return new UriTemplate(template);
  268. }
  269. var parts = template.split("{");
  270. var textParts = [parts.shift()];
  271. var prefixes = [];
  272. var substitutions = [];
  273. var varNames = [];
  274. while (parts.length > 0) {
  275. var part = parts.shift();
  276. var spec = part.split("}")[0];
  277. var remainder = part.substring(spec.length + 1);
  278. var funcs = uriTemplateSubstitution(spec);
  279. substitutions.push(funcs.substitution);
  280. prefixes.push(funcs.prefix);
  281. textParts.push(remainder);
  282. varNames = varNames.concat(funcs.substitution.varNames);
  283. }
  284. this.fill = function (valueFunction) {
  285. var result = textParts[0];
  286. for (var i = 0; i < substitutions.length; i++) {
  287. var substitution = substitutions[i];
  288. result += substitution(valueFunction);
  289. result += textParts[i + 1];
  290. }
  291. return result;
  292. };
  293. this.varNames = varNames;
  294. this.template = template;
  295. }
  296. UriTemplate.prototype = {
  297. toString: function () {
  298. return this.template;
  299. },
  300. fillFromObject: function (obj) {
  301. return this.fill(function (varName) {
  302. return obj[varName];
  303. });
  304. }
  305. };
  306. var ValidatorContext = function ValidatorContext(parent, collectMultiple, errorReporter, checkRecursive, trackUnknownProperties) {
  307. this.missing = [];
  308. this.missingMap = {};
  309. this.formatValidators = parent ? Object.create(parent.formatValidators) : {};
  310. this.schemas = parent ? Object.create(parent.schemas) : {};
  311. this.collectMultiple = collectMultiple;
  312. this.errors = [];
  313. this.handleError = collectMultiple ? this.collectError : this.returnError;
  314. if (checkRecursive) {
  315. this.checkRecursive = true;
  316. this.scanned = [];
  317. this.scannedFrozen = [];
  318. this.scannedFrozenSchemas = [];
  319. this.scannedFrozenValidationErrors = [];
  320. this.validatedSchemasKey = 'tv4_validation_id';
  321. this.validationErrorsKey = 'tv4_validation_errors_id';
  322. }
  323. if (trackUnknownProperties) {
  324. this.trackUnknownProperties = true;
  325. this.knownPropertyPaths = {};
  326. this.unknownPropertyPaths = {};
  327. }
  328. this.errorReporter = errorReporter || defaultErrorReporter('en');
  329. if (typeof this.errorReporter === 'string') {
  330. throw new Error('debug');
  331. }
  332. this.definedKeywords = {};
  333. if (parent) {
  334. for (var key in parent.definedKeywords) {
  335. this.definedKeywords[key] = parent.definedKeywords[key].slice(0);
  336. }
  337. }
  338. };
  339. ValidatorContext.prototype.defineKeyword = function (keyword, keywordFunction) {
  340. this.definedKeywords[keyword] = this.definedKeywords[keyword] || [];
  341. this.definedKeywords[keyword].push(keywordFunction);
  342. };
  343. ValidatorContext.prototype.createError = function (code, messageParams, dataPath, schemaPath, subErrors, data, schema) {
  344. var error = new ValidationError(code, messageParams, dataPath, schemaPath, subErrors);
  345. error.message = this.errorReporter(error, data, schema);
  346. return error;
  347. };
  348. ValidatorContext.prototype.returnError = function (error) {
  349. return error;
  350. };
  351. ValidatorContext.prototype.collectError = function (error) {
  352. if (error) {
  353. this.errors.push(error);
  354. }
  355. return null;
  356. };
  357. ValidatorContext.prototype.prefixErrors = function (startIndex, dataPath, schemaPath) {
  358. for (var i = startIndex; i < this.errors.length; i++) {
  359. this.errors[i] = this.errors[i].prefixWith(dataPath, schemaPath);
  360. }
  361. return this;
  362. };
  363. ValidatorContext.prototype.banUnknownProperties = function (data, schema) {
  364. for (var unknownPath in this.unknownPropertyPaths) {
  365. var error = this.createError(ErrorCodes.UNKNOWN_PROPERTY, {path: unknownPath}, unknownPath, "", null, data, schema);
  366. var result = this.handleError(error);
  367. if (result) {
  368. return result;
  369. }
  370. }
  371. return null;
  372. };
  373. ValidatorContext.prototype.addFormat = function (format, validator) {
  374. if (typeof format === 'object') {
  375. for (var key in format) {
  376. this.addFormat(key, format[key]);
  377. }
  378. return this;
  379. }
  380. this.formatValidators[format] = validator;
  381. };
  382. ValidatorContext.prototype.resolveRefs = function (schema, urlHistory) {
  383. if (schema['$ref'] !== undefined) {
  384. urlHistory = urlHistory || {};
  385. if (urlHistory[schema['$ref']]) {
  386. return this.createError(ErrorCodes.CIRCULAR_REFERENCE, {urls: Object.keys(urlHistory).join(', ')}, '', '', null, undefined, schema);
  387. }
  388. urlHistory[schema['$ref']] = true;
  389. schema = this.getSchema(schema['$ref'], urlHistory);
  390. }
  391. return schema;
  392. };
  393. ValidatorContext.prototype.getSchema = function (url, urlHistory) {
  394. var schema;
  395. if (this.schemas[url] !== undefined) {
  396. schema = this.schemas[url];
  397. return this.resolveRefs(schema, urlHistory);
  398. }
  399. var baseUrl = url;
  400. var fragment = "";
  401. if (url.indexOf('#') !== -1) {
  402. fragment = url.substring(url.indexOf("#") + 1);
  403. baseUrl = url.substring(0, url.indexOf("#"));
  404. }
  405. if (typeof this.schemas[baseUrl] === 'object') {
  406. schema = this.schemas[baseUrl];
  407. var pointerPath = decodeURIComponent(fragment);
  408. if (pointerPath === "") {
  409. return this.resolveRefs(schema, urlHistory);
  410. } else if (pointerPath.charAt(0) !== "/") {
  411. return undefined;
  412. }
  413. var parts = pointerPath.split("/").slice(1);
  414. for (var i = 0; i < parts.length; i++) {
  415. var component = parts[i].replace(/~1/g, "/").replace(/~0/g, "~");
  416. if (schema[component] === undefined) {
  417. schema = undefined;
  418. break;
  419. }
  420. schema = schema[component];
  421. }
  422. if (schema !== undefined) {
  423. return this.resolveRefs(schema, urlHistory);
  424. }
  425. }
  426. if (this.missing[baseUrl] === undefined) {
  427. this.missing.push(baseUrl);
  428. this.missing[baseUrl] = baseUrl;
  429. this.missingMap[baseUrl] = baseUrl;
  430. }
  431. };
  432. ValidatorContext.prototype.searchSchemas = function (schema, url) {
  433. if (Array.isArray(schema)) {
  434. for (var i = 0; i < schema.length; i++) {
  435. this.searchSchemas(schema[i], url);
  436. }
  437. } else if (schema && typeof schema === "object") {
  438. if (typeof schema.id === "string") {
  439. if (isTrustedUrl(url, schema.id)) {
  440. if (this.schemas[schema.id] === undefined) {
  441. this.schemas[schema.id] = schema;
  442. }
  443. }
  444. }
  445. for (var key in schema) {
  446. if (key !== "enum") {
  447. if (typeof schema[key] === "object") {
  448. this.searchSchemas(schema[key], url);
  449. } else if (key === "$ref") {
  450. var uri = getDocumentUri(schema[key]);
  451. if (uri && this.schemas[uri] === undefined && this.missingMap[uri] === undefined) {
  452. this.missingMap[uri] = uri;
  453. }
  454. }
  455. }
  456. }
  457. }
  458. };
  459. ValidatorContext.prototype.addSchema = function (url, schema) {
  460. //overload
  461. if (typeof url !== 'string' || typeof schema === 'undefined') {
  462. if (typeof url === 'object' && typeof url.id === 'string') {
  463. schema = url;
  464. url = schema.id;
  465. }
  466. else {
  467. return;
  468. }
  469. }
  470. if (url === getDocumentUri(url) + "#") {
  471. // Remove empty fragment
  472. url = getDocumentUri(url);
  473. }
  474. this.schemas[url] = schema;
  475. delete this.missingMap[url];
  476. normSchema(schema, url);
  477. this.searchSchemas(schema, url);
  478. };
  479. ValidatorContext.prototype.getSchemaMap = function () {
  480. var map = {};
  481. for (var key in this.schemas) {
  482. map[key] = this.schemas[key];
  483. }
  484. return map;
  485. };
  486. ValidatorContext.prototype.getSchemaUris = function (filterRegExp) {
  487. var list = [];
  488. for (var key in this.schemas) {
  489. if (!filterRegExp || filterRegExp.test(key)) {
  490. list.push(key);
  491. }
  492. }
  493. return list;
  494. };
  495. ValidatorContext.prototype.getMissingUris = function (filterRegExp) {
  496. var list = [];
  497. for (var key in this.missingMap) {
  498. if (!filterRegExp || filterRegExp.test(key)) {
  499. list.push(key);
  500. }
  501. }
  502. return list;
  503. };
  504. ValidatorContext.prototype.dropSchemas = function () {
  505. this.schemas = {};
  506. this.reset();
  507. };
  508. ValidatorContext.prototype.reset = function () {
  509. this.missing = [];
  510. this.missingMap = {};
  511. this.errors = [];
  512. };
  513. ValidatorContext.prototype.validateAll = function (data, schema, dataPathParts, schemaPathParts, dataPointerPath) {
  514. var topLevel;
  515. schema = this.resolveRefs(schema);
  516. if (!schema) {
  517. return null;
  518. } else if (schema instanceof ValidationError) {
  519. this.errors.push(schema);
  520. return schema;
  521. }
  522. var startErrorCount = this.errors.length;
  523. var frozenIndex, scannedFrozenSchemaIndex = null, scannedSchemasIndex = null;
  524. if (this.checkRecursive && data && typeof data === 'object') {
  525. topLevel = !this.scanned.length;
  526. if (data[this.validatedSchemasKey]) {
  527. var schemaIndex = data[this.validatedSchemasKey].indexOf(schema);
  528. if (schemaIndex !== -1) {
  529. this.errors = this.errors.concat(data[this.validationErrorsKey][schemaIndex]);
  530. return null;
  531. }
  532. }
  533. if (Object.isFrozen(data)) {
  534. frozenIndex = this.scannedFrozen.indexOf(data);
  535. if (frozenIndex !== -1) {
  536. var frozenSchemaIndex = this.scannedFrozenSchemas[frozenIndex].indexOf(schema);
  537. if (frozenSchemaIndex !== -1) {
  538. this.errors = this.errors.concat(this.scannedFrozenValidationErrors[frozenIndex][frozenSchemaIndex]);
  539. return null;
  540. }
  541. }
  542. }
  543. this.scanned.push(data);
  544. if (Object.isFrozen(data)) {
  545. if (frozenIndex === -1) {
  546. frozenIndex = this.scannedFrozen.length;
  547. this.scannedFrozen.push(data);
  548. this.scannedFrozenSchemas.push([]);
  549. }
  550. scannedFrozenSchemaIndex = this.scannedFrozenSchemas[frozenIndex].length;
  551. this.scannedFrozenSchemas[frozenIndex][scannedFrozenSchemaIndex] = schema;
  552. this.scannedFrozenValidationErrors[frozenIndex][scannedFrozenSchemaIndex] = [];
  553. } else {
  554. if (!data[this.validatedSchemasKey]) {
  555. try {
  556. Object.defineProperty(data, this.validatedSchemasKey, {
  557. value: [],
  558. configurable: true
  559. });
  560. Object.defineProperty(data, this.validationErrorsKey, {
  561. value: [],
  562. configurable: true
  563. });
  564. } catch (e) {
  565. //IE 7/8 workaround
  566. data[this.validatedSchemasKey] = [];
  567. data[this.validationErrorsKey] = [];
  568. }
  569. }
  570. scannedSchemasIndex = data[this.validatedSchemasKey].length;
  571. data[this.validatedSchemasKey][scannedSchemasIndex] = schema;
  572. data[this.validationErrorsKey][scannedSchemasIndex] = [];
  573. }
  574. }
  575. var errorCount = this.errors.length;
  576. var error = this.validateBasic(data, schema, dataPointerPath)
  577. || this.validateNumeric(data, schema, dataPointerPath)
  578. || this.validateString(data, schema, dataPointerPath)
  579. || this.validateArray(data, schema, dataPointerPath)
  580. || this.validateObject(data, schema, dataPointerPath)
  581. || this.validateCombinations(data, schema, dataPointerPath)
  582. || this.validateHypermedia(data, schema, dataPointerPath)
  583. || this.validateFormat(data, schema, dataPointerPath)
  584. || this.validateDefinedKeywords(data, schema, dataPointerPath)
  585. || null;
  586. if (topLevel) {
  587. while (this.scanned.length) {
  588. var item = this.scanned.pop();
  589. delete item[this.validatedSchemasKey];
  590. }
  591. this.scannedFrozen = [];
  592. this.scannedFrozenSchemas = [];
  593. }
  594. if (error || errorCount !== this.errors.length) {
  595. while ((dataPathParts && dataPathParts.length) || (schemaPathParts && schemaPathParts.length)) {
  596. var dataPart = (dataPathParts && dataPathParts.length) ? "" + dataPathParts.pop() : null;
  597. var schemaPart = (schemaPathParts && schemaPathParts.length) ? "" + schemaPathParts.pop() : null;
  598. if (error) {
  599. error = error.prefixWith(dataPart, schemaPart);
  600. }
  601. this.prefixErrors(errorCount, dataPart, schemaPart);
  602. }
  603. }
  604. if (scannedFrozenSchemaIndex !== null) {
  605. this.scannedFrozenValidationErrors[frozenIndex][scannedFrozenSchemaIndex] = this.errors.slice(startErrorCount);
  606. } else if (scannedSchemasIndex !== null) {
  607. data[this.validationErrorsKey][scannedSchemasIndex] = this.errors.slice(startErrorCount);
  608. }
  609. return this.handleError(error);
  610. };
  611. ValidatorContext.prototype.validateFormat = function (data, schema) {
  612. if (typeof schema.format !== 'string' || !this.formatValidators[schema.format]) {
  613. return null;
  614. }
  615. var errorMessage = this.formatValidators[schema.format].call(null, data, schema);
  616. if (typeof errorMessage === 'string' || typeof errorMessage === 'number') {
  617. return this.createError(ErrorCodes.FORMAT_CUSTOM, {message: errorMessage}, '', '/format', null, data, schema);
  618. } else if (errorMessage && typeof errorMessage === 'object') {
  619. return this.createError(ErrorCodes.FORMAT_CUSTOM, {message: errorMessage.message || "?"}, errorMessage.dataPath || '', errorMessage.schemaPath || "/format", null, data, schema);
  620. }
  621. return null;
  622. };
  623. ValidatorContext.prototype.validateDefinedKeywords = function (data, schema, dataPointerPath) {
  624. for (var key in this.definedKeywords) {
  625. if (typeof schema[key] === 'undefined') {
  626. continue;
  627. }
  628. var validationFunctions = this.definedKeywords[key];
  629. for (var i = 0; i < validationFunctions.length; i++) {
  630. var func = validationFunctions[i];
  631. var result = func(data, schema[key], schema, dataPointerPath);
  632. if (typeof result === 'string' || typeof result === 'number') {
  633. return this.createError(ErrorCodes.KEYWORD_CUSTOM, {key: key, message: result}, '', '', null, data, schema).prefixWith(null, key);
  634. } else if (result && typeof result === 'object') {
  635. var code = result.code;
  636. if (typeof code === 'string') {
  637. if (!ErrorCodes[code]) {
  638. throw new Error('Undefined error code (use defineError): ' + code);
  639. }
  640. code = ErrorCodes[code];
  641. } else if (typeof code !== 'number') {
  642. code = ErrorCodes.KEYWORD_CUSTOM;
  643. }
  644. var messageParams = (typeof result.message === 'object') ? result.message : {key: key, message: result.message || "?"};
  645. var schemaPath = result.schemaPath || ("/" + key.replace(/~/g, '~0').replace(/\//g, '~1'));
  646. return this.createError(code, messageParams, result.dataPath || null, schemaPath, null, data, schema);
  647. }
  648. }
  649. }
  650. return null;
  651. };
  652. function recursiveCompare(A, B) {
  653. if (A === B) {
  654. return true;
  655. }
  656. if (A && B && typeof A === "object" && typeof B === "object") {
  657. if (Array.isArray(A) !== Array.isArray(B)) {
  658. return false;
  659. } else if (Array.isArray(A)) {
  660. if (A.length !== B.length) {
  661. return false;
  662. }
  663. for (var i = 0; i < A.length; i++) {
  664. if (!recursiveCompare(A[i], B[i])) {
  665. return false;
  666. }
  667. }
  668. } else {
  669. var key;
  670. for (key in A) {
  671. if (B[key] === undefined && A[key] !== undefined) {
  672. return false;
  673. }
  674. }
  675. for (key in B) {
  676. if (A[key] === undefined && B[key] !== undefined) {
  677. return false;
  678. }
  679. }
  680. for (key in A) {
  681. if (!recursiveCompare(A[key], B[key])) {
  682. return false;
  683. }
  684. }
  685. }
  686. return true;
  687. }
  688. return false;
  689. }
  690. ValidatorContext.prototype.validateBasic = function validateBasic(data, schema, dataPointerPath) {
  691. var error;
  692. if (error = this.validateType(data, schema, dataPointerPath)) {
  693. return error.prefixWith(null, "type");
  694. }
  695. if (error = this.validateEnum(data, schema, dataPointerPath)) {
  696. return error.prefixWith(null, "type");
  697. }
  698. return null;
  699. };
  700. ValidatorContext.prototype.validateType = function validateType(data, schema) {
  701. if (schema.type === undefined) {
  702. return null;
  703. }
  704. var dataType = typeof data;
  705. if (data === null) {
  706. dataType = "null";
  707. } else if (Array.isArray(data)) {
  708. dataType = "array";
  709. }
  710. var allowedTypes = schema.type;
  711. if (!Array.isArray(allowedTypes)) {
  712. allowedTypes = [allowedTypes];
  713. }
  714. for (var i = 0; i < allowedTypes.length; i++) {
  715. var type = allowedTypes[i];
  716. if (type === dataType || (type === "integer" && dataType === "number" && (data % 1 === 0))) {
  717. return null;
  718. }
  719. }
  720. return this.createError(ErrorCodes.INVALID_TYPE, {type: dataType, expected: allowedTypes.join("/")}, '', '', null, data, schema);
  721. };
  722. ValidatorContext.prototype.validateEnum = function validateEnum(data, schema) {
  723. if (schema["enum"] === undefined) {
  724. return null;
  725. }
  726. for (var i = 0; i < schema["enum"].length; i++) {
  727. var enumVal = schema["enum"][i];
  728. if (recursiveCompare(data, enumVal)) {
  729. return null;
  730. }
  731. }
  732. return this.createError(ErrorCodes.ENUM_MISMATCH, {value: (typeof JSON !== 'undefined') ? JSON.stringify(data) : data}, '', '', null, data, schema);
  733. };
  734. ValidatorContext.prototype.validateNumeric = function validateNumeric(data, schema, dataPointerPath) {
  735. return this.validateMultipleOf(data, schema, dataPointerPath)
  736. || this.validateMinMax(data, schema, dataPointerPath)
  737. || this.validateNaN(data, schema, dataPointerPath)
  738. || null;
  739. };
  740. var CLOSE_ENOUGH_LOW = Math.pow(2, -51);
  741. var CLOSE_ENOUGH_HIGH = 1 - CLOSE_ENOUGH_LOW;
  742. ValidatorContext.prototype.validateMultipleOf = function validateMultipleOf(data, schema) {
  743. var multipleOf = schema.multipleOf || schema.divisibleBy;
  744. if (multipleOf === undefined) {
  745. return null;
  746. }
  747. if (typeof data === "number") {
  748. var remainder = (data/multipleOf)%1;
  749. if (remainder >= CLOSE_ENOUGH_LOW && remainder < CLOSE_ENOUGH_HIGH) {
  750. return this.createError(ErrorCodes.NUMBER_MULTIPLE_OF, {value: data, multipleOf: multipleOf}, '', '', null, data, schema);
  751. }
  752. }
  753. return null;
  754. };
  755. ValidatorContext.prototype.validateMinMax = function validateMinMax(data, schema) {
  756. if (typeof data !== "number") {
  757. return null;
  758. }
  759. if (schema.minimum !== undefined) {
  760. if (data < schema.minimum) {
  761. return this.createError(ErrorCodes.NUMBER_MINIMUM, {value: data, minimum: schema.minimum}, '', '/minimum', null, data, schema);
  762. }
  763. if (schema.exclusiveMinimum && data === schema.minimum) {
  764. return this.createError(ErrorCodes.NUMBER_MINIMUM_EXCLUSIVE, {value: data, minimum: schema.minimum}, '', '/exclusiveMinimum', null, data, schema);
  765. }
  766. }
  767. if (schema.maximum !== undefined) {
  768. if (data > schema.maximum) {
  769. return this.createError(ErrorCodes.NUMBER_MAXIMUM, {value: data, maximum: schema.maximum}, '', '/maximum', null, data, schema);
  770. }
  771. if (schema.exclusiveMaximum && data === schema.maximum) {
  772. return this.createError(ErrorCodes.NUMBER_MAXIMUM_EXCLUSIVE, {value: data, maximum: schema.maximum}, '', '/exclusiveMaximum', null, data, schema);
  773. }
  774. }
  775. return null;
  776. };
  777. ValidatorContext.prototype.validateNaN = function validateNaN(data, schema) {
  778. if (typeof data !== "number") {
  779. return null;
  780. }
  781. if (isNaN(data) === true || data === Infinity || data === -Infinity) {
  782. return this.createError(ErrorCodes.NUMBER_NOT_A_NUMBER, {value: data}, '', '/type', null, data, schema);
  783. }
  784. return null;
  785. };
  786. ValidatorContext.prototype.validateString = function validateString(data, schema, dataPointerPath) {
  787. return this.validateStringLength(data, schema, dataPointerPath)
  788. || this.validateStringPattern(data, schema, dataPointerPath)
  789. || null;
  790. };
  791. ValidatorContext.prototype.validateStringLength = function validateStringLength(data, schema) {
  792. if (typeof data !== "string") {
  793. return null;
  794. }
  795. if (schema.minLength !== undefined) {
  796. if (data.length < schema.minLength) {
  797. return this.createError(ErrorCodes.STRING_LENGTH_SHORT, {length: data.length, minimum: schema.minLength}, '', '/minLength', null, data, schema);
  798. }
  799. }
  800. if (schema.maxLength !== undefined) {
  801. if (data.length > schema.maxLength) {
  802. return this.createError(ErrorCodes.STRING_LENGTH_LONG, {length: data.length, maximum: schema.maxLength}, '', '/maxLength', null, data, schema);
  803. }
  804. }
  805. return null;
  806. };
  807. ValidatorContext.prototype.validateStringPattern = function validateStringPattern(data, schema) {
  808. if (typeof data !== "string" || (typeof schema.pattern !== "string" && !(schema.pattern instanceof RegExp))) {
  809. return null;
  810. }
  811. var regexp;
  812. if (schema.pattern instanceof RegExp) {
  813. regexp = schema.pattern;
  814. }
  815. else {
  816. var body, flags = '';
  817. // Check for regular expression literals
  818. // @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5
  819. var literal = schema.pattern.match(/^\/(.+)\/([img]*)$/);
  820. if (literal) {
  821. body = literal[1];
  822. flags = literal[2];
  823. }
  824. else {
  825. body = schema.pattern;
  826. }
  827. regexp = new RegExp(body, flags);
  828. }
  829. if (!regexp.test(data)) {
  830. return this.createError(ErrorCodes.STRING_PATTERN, {pattern: schema.pattern}, '', '/pattern', null, data, schema);
  831. }
  832. return null;
  833. };
  834. ValidatorContext.prototype.validateArray = function validateArray(data, schema, dataPointerPath) {
  835. if (!Array.isArray(data)) {
  836. return null;
  837. }
  838. return this.validateArrayLength(data, schema, dataPointerPath)
  839. || this.validateArrayUniqueItems(data, schema, dataPointerPath)
  840. || this.validateArrayItems(data, schema, dataPointerPath)
  841. || null;
  842. };
  843. ValidatorContext.prototype.validateArrayLength = function validateArrayLength(data, schema) {
  844. var error;
  845. if (schema.minItems !== undefined) {
  846. if (data.length < schema.minItems) {
  847. error = this.createError(ErrorCodes.ARRAY_LENGTH_SHORT, {length: data.length, minimum: schema.minItems}, '', '/minItems', null, data, schema);
  848. if (this.handleError(error)) {
  849. return error;
  850. }
  851. }
  852. }
  853. if (schema.maxItems !== undefined) {
  854. if (data.length > schema.maxItems) {
  855. error = this.createError(ErrorCodes.ARRAY_LENGTH_LONG, {length: data.length, maximum: schema.maxItems}, '', '/maxItems', null, data, schema);
  856. if (this.handleError(error)) {
  857. return error;
  858. }
  859. }
  860. }
  861. return null;
  862. };
  863. ValidatorContext.prototype.validateArrayUniqueItems = function validateArrayUniqueItems(data, schema) {
  864. if (schema.uniqueItems) {
  865. for (var i = 0; i < data.length; i++) {
  866. for (var j = i + 1; j < data.length; j++) {
  867. if (recursiveCompare(data[i], data[j])) {
  868. var error = this.createError(ErrorCodes.ARRAY_UNIQUE, {match1: i, match2: j}, '', '/uniqueItems', null, data, schema);
  869. if (this.handleError(error)) {
  870. return error;
  871. }
  872. }
  873. }
  874. }
  875. }
  876. return null;
  877. };
  878. ValidatorContext.prototype.validateArrayItems = function validateArrayItems(data, schema, dataPointerPath) {
  879. if (schema.items === undefined) {
  880. return null;
  881. }
  882. var error, i;
  883. if (Array.isArray(schema.items)) {
  884. for (i = 0; i < data.length; i++) {
  885. if (i < schema.items.length) {
  886. if (error = this.validateAll(data[i], schema.items[i], [i], ["items", i], dataPointerPath + "/" + i)) {
  887. return error;
  888. }
  889. } else if (schema.additionalItems !== undefined) {
  890. if (typeof schema.additionalItems === "boolean") {
  891. if (!schema.additionalItems) {
  892. error = (this.createError(ErrorCodes.ARRAY_ADDITIONAL_ITEMS, {}, '/' + i, '/additionalItems', null, data, schema));
  893. if (this.handleError(error)) {
  894. return error;
  895. }
  896. }
  897. } else if (error = this.validateAll(data[i], schema.additionalItems, [i], ["additionalItems"], dataPointerPath + "/" + i)) {
  898. return error;
  899. }
  900. }
  901. }
  902. } else {
  903. for (i = 0; i < data.length; i++) {
  904. if (error = this.validateAll(data[i], schema.items, [i], ["items"], dataPointerPath + "/" + i)) {
  905. return error;
  906. }
  907. }
  908. }
  909. return null;
  910. };
  911. ValidatorContext.prototype.validateObject = function validateObject(data, schema, dataPointerPath) {
  912. if (typeof data !== "object" || data === null || Array.isArray(data)) {
  913. return null;
  914. }
  915. return this.validateObjectMinMaxProperties(data, schema, dataPointerPath)
  916. || this.validateObjectRequiredProperties(data, schema, dataPointerPath)
  917. || this.validateObjectProperties(data, schema, dataPointerPath)
  918. || this.validateObjectDependencies(data, schema, dataPointerPath)
  919. || null;
  920. };
  921. ValidatorContext.prototype.validateObjectMinMaxProperties = function validateObjectMinMaxProperties(data, schema) {
  922. var keys = Object.keys(data);
  923. var error;
  924. if (schema.minProperties !== undefined) {
  925. if (keys.length < schema.minProperties) {
  926. error = this.createError(ErrorCodes.OBJECT_PROPERTIES_MINIMUM, {propertyCount: keys.length, minimum: schema.minProperties}, '', '/minProperties', null, data, schema);
  927. if (this.handleError(error)) {
  928. return error;
  929. }
  930. }
  931. }
  932. if (schema.maxProperties !== undefined) {
  933. if (keys.length > schema.maxProperties) {
  934. error = this.createError(ErrorCodes.OBJECT_PROPERTIES_MAXIMUM, {propertyCount: keys.length, maximum: schema.maxProperties}, '', '/maxProperties', null, data, schema);
  935. if (this.handleError(error)) {
  936. return error;
  937. }
  938. }
  939. }
  940. return null;
  941. };
  942. ValidatorContext.prototype.validateObjectRequiredProperties = function validateObjectRequiredProperties(data, schema) {
  943. if (schema.required !== undefined) {
  944. for (var i = 0; i < schema.required.length; i++) {
  945. var key = schema.required[i];
  946. if (data[key] === undefined) {
  947. var error = this.createError(ErrorCodes.OBJECT_REQUIRED, {key: key}, '', '/required/' + i, null, data, schema);
  948. if (this.handleError(error)) {
  949. return error;
  950. }
  951. }
  952. }
  953. }
  954. return null;
  955. };
  956. ValidatorContext.prototype.validateObjectProperties = function validateObjectProperties(data, schema, dataPointerPath) {
  957. var error;
  958. for (var key in data) {
  959. var keyPointerPath = dataPointerPath + "/" + key.replace(/~/g, '~0').replace(/\//g, '~1');
  960. var foundMatch = false;
  961. if (schema.properties !== undefined && schema.properties[key] !== undefined) {
  962. foundMatch = true;
  963. if (error = this.validateAll(data[key], schema.properties[key], [key], ["properties", key], keyPointerPath)) {
  964. return error;
  965. }
  966. }
  967. if (schema.patternProperties !== undefined) {
  968. for (var patternKey in schema.patternProperties) {
  969. var regexp = new RegExp(patternKey);
  970. if (regexp.test(key)) {
  971. foundMatch = true;
  972. if (error = this.validateAll(data[key], schema.patternProperties[patternKey], [key], ["patternProperties", patternKey], keyPointerPath)) {
  973. return error;
  974. }
  975. }
  976. }
  977. }
  978. if (!foundMatch) {
  979. if (schema.additionalProperties !== undefined) {
  980. if (this.trackUnknownProperties) {
  981. this.knownPropertyPaths[keyPointerPath] = true;
  982. delete this.unknownPropertyPaths[keyPointerPath];
  983. }
  984. if (typeof schema.additionalProperties === "boolean") {
  985. if (!schema.additionalProperties) {
  986. error = this.createError(ErrorCodes.OBJECT_ADDITIONAL_PROPERTIES, {key: key}, '', '/additionalProperties', null, data, schema).prefixWith(key, null);
  987. if (this.handleError(error)) {
  988. return error;
  989. }
  990. }
  991. } else {
  992. if (error = this.validateAll(data[key], schema.additionalProperties, [key], ["additionalProperties"], keyPointerPath)) {
  993. return error;
  994. }
  995. }
  996. } else if (this.trackUnknownProperties && !this.knownPropertyPaths[keyPointerPath]) {
  997. this.unknownPropertyPaths[keyPointerPath] = true;
  998. }
  999. } else if (this.trackUnknownProperties) {
  1000. this.knownPropertyPaths[keyPointerPath] = true;
  1001. delete this.unknownPropertyPaths[keyPointerPath];
  1002. }
  1003. }
  1004. return null;
  1005. };
  1006. ValidatorContext.prototype.validateObjectDependencies = function validateObjectDependencies(data, schema, dataPointerPath) {
  1007. var error;
  1008. if (schema.dependencies !== undefined) {
  1009. for (var depKey in schema.dependencies) {
  1010. if (data[depKey] !== undefined) {
  1011. var dep = schema.dependencies[depKey];
  1012. if (typeof dep === "string") {
  1013. if (data[dep] === undefined) {
  1014. error = this.createError(ErrorCodes.OBJECT_DEPENDENCY_KEY, {key: depKey, missing: dep}, '', '', null, data, schema).prefixWith(null, depKey).prefixWith(null, "dependencies");
  1015. if (this.handleError(error)) {
  1016. return error;
  1017. }
  1018. }
  1019. } else if (Array.isArray(dep)) {
  1020. for (var i = 0; i < dep.length; i++) {
  1021. var requiredKey = dep[i];
  1022. if (data[requiredKey] === undefined) {
  1023. error = this.createError(ErrorCodes.OBJECT_DEPENDENCY_KEY, {key: depKey, missing: requiredKey}, '', '/' + i, null, data, schema).prefixWith(null, depKey).prefixWith(null, "dependencies");
  1024. if (this.handleError(error)) {
  1025. return error;
  1026. }
  1027. }
  1028. }
  1029. } else {
  1030. if (error = this.validateAll(data, dep, [], ["dependencies", depKey], dataPointerPath)) {
  1031. return error;
  1032. }
  1033. }
  1034. }
  1035. }
  1036. }
  1037. return null;
  1038. };
  1039. ValidatorContext.prototype.validateCombinations = function validateCombinations(data, schema, dataPointerPath) {
  1040. return this.validateAllOf(data, schema, dataPointerPath)
  1041. || this.validateAnyOf(data, schema, dataPointerPath)
  1042. || this.validateOneOf(data, schema, dataPointerPath)
  1043. || this.validateNot(data, schema, dataPointerPath)
  1044. || null;
  1045. };
  1046. ValidatorContext.prototype.validateAllOf = function validateAllOf(data, schema, dataPointerPath) {
  1047. if (schema.allOf === undefined) {
  1048. return null;
  1049. }
  1050. var error;
  1051. for (var i = 0; i < schema.allOf.length; i++) {
  1052. var subSchema = schema.allOf[i];
  1053. if (error = this.validateAll(data, subSchema, [], ["allOf", i], dataPointerPath)) {
  1054. return error;
  1055. }
  1056. }
  1057. return null;
  1058. };
  1059. ValidatorContext.prototype.validateAnyOf = function validateAnyOf(data, schema, dataPointerPath) {
  1060. if (schema.anyOf === undefined) {
  1061. return null;
  1062. }
  1063. var errors = [];
  1064. var startErrorCount = this.errors.length;
  1065. var oldUnknownPropertyPaths, oldKnownPropertyPaths;
  1066. if (this.trackUnknownProperties) {
  1067. oldUnknownPropertyPaths = this.unknownPropertyPaths;
  1068. oldKnownPropertyPaths = this.knownPropertyPaths;
  1069. }
  1070. var errorAtEnd = true;
  1071. for (var i = 0; i < schema.anyOf.length; i++) {
  1072. if (this.trackUnknownProperties) {
  1073. this.unknownPropertyPaths = {};
  1074. this.knownPropertyPaths = {};
  1075. }
  1076. var subSchema = schema.anyOf[i];
  1077. var errorCount = this.errors.length;
  1078. var error = this.validateAll(data, subSchema, [], ["anyOf", i], dataPointerPath);
  1079. if (error === null && errorCount === this.errors.length) {
  1080. this.errors = this.errors.slice(0, startErrorCount);
  1081. if (this.trackUnknownProperties) {
  1082. for (var knownKey in this.knownPropertyPaths) {
  1083. oldKnownPropertyPaths[knownKey] = true;
  1084. delete oldUnknownPropertyPaths[knownKey];
  1085. }
  1086. for (var unknownKey in this.unknownPropertyPaths) {
  1087. if (!oldKnownPropertyPaths[unknownKey]) {
  1088. oldUnknownPropertyPaths[unknownKey] = true;
  1089. }
  1090. }
  1091. // We need to continue looping so we catch all the property definitions, but we don't want to return an error
  1092. errorAtEnd = false;
  1093. continue;
  1094. }
  1095. return null;
  1096. }
  1097. if (error) {
  1098. errors.push(error.prefixWith(null, "" + i).prefixWith(null, "anyOf"));
  1099. }
  1100. }
  1101. if (this.trackUnknownProperties) {
  1102. this.unknownPropertyPaths = oldUnknownPropertyPaths;
  1103. this.knownPropertyPaths = oldKnownPropertyPaths;
  1104. }
  1105. if (errorAtEnd) {
  1106. errors = errors.concat(this.errors.slice(startErrorCount));
  1107. this.errors = this.errors.slice(0, startErrorCount);
  1108. return this.createError(ErrorCodes.ANY_OF_MISSING, {}, "", "/anyOf", errors, data, schema);
  1109. }
  1110. };
  1111. ValidatorContext.prototype.validateOneOf = function validateOneOf(data, schema, dataPointerPath) {
  1112. if (schema.oneOf === undefined) {
  1113. return null;
  1114. }
  1115. var validIndex = null;
  1116. var errors = [];
  1117. var startErrorCount = this.errors.length;
  1118. var oldUnknownPropertyPaths, oldKnownPropertyPaths;
  1119. if (this.trackUnknownProperties) {
  1120. oldUnknownPropertyPaths = this.unknownPropertyPaths;
  1121. oldKnownPropertyPaths = this.knownPropertyPaths;
  1122. }
  1123. for (var i = 0; i < schema.oneOf.length; i++) {
  1124. if (this.trackUnknownProperties) {
  1125. this.unknownPropertyPaths = {};
  1126. this.knownPropertyPaths = {};
  1127. }
  1128. var subSchema = schema.oneOf[i];
  1129. var errorCount = this.errors.length;
  1130. var error = this.validateAll(data, subSchema, [], ["oneOf", i], dataPointerPath);
  1131. if (error === null && errorCount === this.errors.length) {
  1132. if (validIndex === null) {
  1133. validIndex = i;
  1134. } else {
  1135. this.errors = this.errors.slice(0, startErrorCount);
  1136. return this.createError(ErrorCodes.ONE_OF_MULTIPLE, {index1: validIndex, index2: i}, "", "/oneOf", null, data, schema);
  1137. }
  1138. if (this.trackUnknownProperties) {
  1139. for (var knownKey in this.knownPropertyPaths) {
  1140. oldKnownPropertyPaths[knownKey] = true;
  1141. delete oldUnknownPropertyPaths[knownKey];
  1142. }
  1143. for (var unknownKey in this.unknownPropertyPaths) {
  1144. if (!oldKnownPropertyPaths[unknownKey]) {
  1145. oldUnknownPropertyPaths[unknownKey] = true;
  1146. }
  1147. }
  1148. }
  1149. } else if (error) {
  1150. errors.push(error);
  1151. }
  1152. }
  1153. if (this.trackUnknownProperties) {
  1154. this.unknownPropertyPaths = oldUnknownPropertyPaths;
  1155. this.knownPropertyPaths = oldKnownPropertyPaths;
  1156. }
  1157. if (validIndex === null) {
  1158. errors = errors.concat(this.errors.slice(startErrorCount));
  1159. this.errors = this.errors.slice(0, startErrorCount);
  1160. return this.createError(ErrorCodes.ONE_OF_MISSING, {}, "", "/oneOf", errors, data, schema);
  1161. } else {
  1162. this.errors = this.errors.slice(0, startErrorCount);
  1163. }
  1164. return null;
  1165. };
  1166. ValidatorContext.prototype.validateNot = function validateNot(data, schema, dataPointerPath) {
  1167. if (schema.not === undefined) {
  1168. return null;
  1169. }
  1170. var oldErrorCount = this.errors.length;
  1171. var oldUnknownPropertyPaths, oldKnownPropertyPaths;
  1172. if (this.trackUnknownProperties) {
  1173. oldUnknownPropertyPaths = this.unknownPropertyPaths;
  1174. oldKnownPropertyPaths = this.knownPropertyPaths;
  1175. this.unknownPropertyPaths = {};
  1176. this.knownPropertyPaths = {};
  1177. }
  1178. var error = this.validateAll(data, schema.not, null, null, dataPointerPath);
  1179. var notErrors = this.errors.slice(oldErrorCount);
  1180. this.errors = this.errors.slice(0, oldErrorCount);
  1181. if (this.trackUnknownProperties) {
  1182. this.unknownPropertyPaths = oldUnknownPropertyPaths;
  1183. this.knownPropertyPaths = oldKnownPropertyPaths;
  1184. }
  1185. if (error === null && notErrors.length === 0) {
  1186. return this.createError(ErrorCodes.NOT_PASSED, {}, "", "/not", null, data, schema);
  1187. }
  1188. return null;
  1189. };
  1190. ValidatorContext.prototype.validateHypermedia = function validateCombinations(data, schema, dataPointerPath) {
  1191. if (!schema.links) {
  1192. return null;
  1193. }
  1194. var error;
  1195. for (var i = 0; i < schema.links.length; i++) {
  1196. var ldo = schema.links[i];
  1197. if (ldo.rel === "describedby") {
  1198. var template = new UriTemplate(ldo.href);
  1199. var allPresent = true;
  1200. for (var j = 0; j < template.varNames.length; j++) {
  1201. if (!(template.varNames[j] in data)) {
  1202. allPresent = false;
  1203. break;
  1204. }
  1205. }
  1206. if (allPresent) {
  1207. var schemaUrl = template.fillFromObject(data);
  1208. var subSchema = {"$ref": schemaUrl};
  1209. if (error = this.validateAll(data, subSchema, [], ["links", i], dataPointerPath)) {
  1210. return error;
  1211. }
  1212. }
  1213. }
  1214. }
  1215. };
  1216. // parseURI() and resolveUrl() are from https://gist.github.com/1088850
  1217. // - released as public domain by author ("Yaffle") - see comments on gist
  1218. function parseURI(url) {
  1219. var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
  1220. // authority = '//' + user + ':' + pass '@' + hostname + ':' port
  1221. return (m ? {
  1222. href : m[0] || '',
  1223. protocol : m[1] || '',
  1224. authority: m[2] || '',
  1225. host : m[3] || '',
  1226. hostname : m[4] || '',
  1227. port : m[5] || '',
  1228. pathname : m[6] || '',
  1229. search : m[7] || '',
  1230. hash : m[8] || ''
  1231. } : null);
  1232. }
  1233. function resolveUrl(base, href) {// RFC 3986
  1234. function removeDotSegments(input) {
  1235. var output = [];
  1236. input.replace(/^(\.\.?(\/|$))+/, '')
  1237. .replace(/\/(\.(\/|$))+/g, '/')
  1238. .replace(/\/\.\.$/, '/../')
  1239. .replace(/\/?[^\/]*/g, function (p) {
  1240. if (p === '/..') {
  1241. output.pop();
  1242. } else {
  1243. output.push(p);
  1244. }
  1245. });
  1246. return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : '');
  1247. }
  1248. href = parseURI(href || '');
  1249. base = parseURI(base || '');
  1250. return !href || !base ? null : (href.protocol || base.protocol) +
  1251. (href.protocol || href.authority ? href.authority : base.authority) +
  1252. removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) +
  1253. (href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
  1254. href.hash;
  1255. }
  1256. function getDocumentUri(uri) {
  1257. return uri.split('#')[0];
  1258. }
  1259. function normSchema(schema, baseUri) {
  1260. if (schema && typeof schema === "object") {
  1261. if (baseUri === undefined) {
  1262. baseUri = schema.id;
  1263. } else if (typeof schema.id === "string") {
  1264. baseUri = resolveUrl(baseUri, schema.id);
  1265. schema.id = baseUri;
  1266. }
  1267. if (Array.isArray(schema)) {
  1268. for (var i = 0; i < schema.length; i++) {
  1269. normSchema(schema[i], baseUri);
  1270. }
  1271. } else {
  1272. if (typeof schema['$ref'] === "string") {
  1273. schema['$ref'] = resolveUrl(baseUri, schema['$ref']);
  1274. }
  1275. for (var key in schema) {
  1276. if (key !== "enum") {
  1277. normSchema(schema[key], baseUri);
  1278. }
  1279. }
  1280. }
  1281. }
  1282. }
  1283. function defaultErrorReporter(language) {
  1284. language = language || 'en';
  1285. var errorMessages = languages[language];
  1286. return function (error) {
  1287. var messageTemplate = errorMessages[error.code] || ErrorMessagesDefault[error.code];
  1288. if (typeof messageTemplate !== 'string') {
  1289. return "Unknown error code " + error.code + ": " + JSON.stringify(error.messageParams);
  1290. }
  1291. var messageParams = error.params;
  1292. // Adapted from Crockford's supplant()
  1293. return messageTemplate.replace(/\{([^{}]*)\}/g, function (whole, varName) {
  1294. var subValue = messageParams[varName];
  1295. return typeof subValue === 'string' || typeof subValue === 'number' ? subValue : whole;
  1296. });
  1297. };
  1298. }
  1299. var ErrorCodes = {
  1300. INVALID_TYPE: 0,
  1301. ENUM_MISMATCH: 1,
  1302. ANY_OF_MISSING: 10,
  1303. ONE_OF_MISSING: 11,
  1304. ONE_OF_MULTIPLE: 12,
  1305. NOT_PASSED: 13,
  1306. // Numeric errors
  1307. NUMBER_MULTIPLE_OF: 100,
  1308. NUMBER_MINIMUM: 101,
  1309. NUMBER_MINIMUM_EXCLUSIVE: 102,
  1310. NUMBER_MAXIMUM: 103,
  1311. NUMBER_MAXIMUM_EXCLUSIVE: 104,
  1312. NUMBER_NOT_A_NUMBER: 105,
  1313. // String errors
  1314. STRING_LENGTH_SHORT: 200,
  1315. STRING_LENGTH_LONG: 201,
  1316. STRING_PATTERN: 202,
  1317. // Object errors
  1318. OBJECT_PROPERTIES_MINIMUM: 300,
  1319. OBJECT_PROPERTIES_MAXIMUM: 301,
  1320. OBJECT_REQUIRED: 302,
  1321. OBJECT_ADDITIONAL_PROPERTIES: 303,
  1322. OBJECT_DEPENDENCY_KEY: 304,
  1323. // Array errors
  1324. ARRAY_LENGTH_SHORT: 400,
  1325. ARRAY_LENGTH_LONG: 401,
  1326. ARRAY_UNIQUE: 402,
  1327. ARRAY_ADDITIONAL_ITEMS: 403,
  1328. // Custom/user-defined errors
  1329. FORMAT_CUSTOM: 500,
  1330. KEYWORD_CUSTOM: 501,
  1331. // Schema structure
  1332. CIRCULAR_REFERENCE: 600,
  1333. // Non-standard validation options
  1334. UNKNOWN_PROPERTY: 1000
  1335. };
  1336. var ErrorCodeLookup = {};
  1337. for (var key in ErrorCodes) {
  1338. ErrorCodeLookup[ErrorCodes[key]] = key;
  1339. }
  1340. var ErrorMessagesDefault = {
  1341. INVALID_TYPE: "Invalid type: {type} (expected {expected})",
  1342. ENUM_MISMATCH: "No enum match for: {value}",
  1343. ANY_OF_MISSING: "Data does not match any schemas from \"anyOf\"",
  1344. ONE_OF_MISSING: "Data does not match any schemas from \"oneOf\"",
  1345. ONE_OF_MULTIPLE: "Data is valid against more than one schema from \"oneOf\": indices {index1} and {index2}",
  1346. NOT_PASSED: "Data matches schema from \"not\"",
  1347. // Numeric errors
  1348. NUMBER_MULTIPLE_OF: "Value {value} is not a multiple of {multipleOf}",
  1349. NUMBER_MINIMUM: "Value {value} is less than minimum {minimum}",
  1350. NUMBER_MINIMUM_EXCLUSIVE: "Value {value} is equal to exclusive minimum {minimum}",
  1351. NUMBER_MAXIMUM: "Value {value} is greater than maximum {maximum}",
  1352. NUMBER_MAXIMUM_EXCLUSIVE: "Value {value} is equal to exclusive maximum {maximum}",
  1353. NUMBER_NOT_A_NUMBER: "Value {value} is not a valid number",
  1354. // String errors
  1355. STRING_LENGTH_SHORT: "String is too short ({length} chars), minimum {minimum}",
  1356. STRING_LENGTH_LONG: "String is too long ({length} chars), maximum {maximum}",
  1357. STRING_PATTERN: "String does not match pattern: {pattern}",
  1358. // Object errors
  1359. OBJECT_PROPERTIES_MINIMUM: "Too few properties defined ({propertyCount}), minimum {minimum}",
  1360. OBJECT_PROPERTIES_MAXIMUM: "Too many properties defined ({propertyCount}), maximum {maximum}",
  1361. OBJECT_REQUIRED: "Missing required property: {key}",
  1362. OBJECT_ADDITIONAL_PROPERTIES: "Additional properties not allowed",
  1363. OBJECT_DEPENDENCY_KEY: "Dependency failed - key must exist: {missing} (due to key: {key})",
  1364. // Array errors
  1365. ARRAY_LENGTH_SHORT: "Array is too short ({length}), minimum {minimum}",
  1366. ARRAY_LENGTH_LONG: "Array is too long ({length}), maximum {maximum}",
  1367. ARRAY_UNIQUE: "Array items are not unique (indices {match1} and {match2})",
  1368. ARRAY_ADDITIONAL_ITEMS: "Additional items not allowed",
  1369. // Format errors
  1370. FORMAT_CUSTOM: "Format validation failed ({message})",
  1371. KEYWORD_CUSTOM: "Keyword failed: {key} ({message})",
  1372. // Schema structure
  1373. CIRCULAR_REFERENCE: "Circular $refs: {urls}",
  1374. // Non-standard validation options
  1375. UNKNOWN_PROPERTY: "Unknown property (not in schema)"
  1376. };
  1377. function ValidationError(code, params, dataPath, schemaPath, subErrors) {
  1378. Error.call(this);
  1379. if (code === undefined) {
  1380. throw new Error ("No error code supplied: " + schemaPath);
  1381. }
  1382. this.message = '';
  1383. this.params = params;
  1384. this.code = code;
  1385. this.dataPath = dataPath || "";
  1386. this.schemaPath = schemaPath || "";
  1387. this.subErrors = subErrors || null;
  1388. var err = new Error(this.message);
  1389. this.stack = err.stack || err.stacktrace;
  1390. if (!this.stack) {
  1391. try {
  1392. throw err;
  1393. }
  1394. catch(err) {
  1395. this.stack = err.stack || err.stacktrace;
  1396. }
  1397. }
  1398. }
  1399. ValidationError.prototype = Object.create(Error.prototype);
  1400. ValidationError.prototype.constructor = ValidationError;
  1401. ValidationError.prototype.name = 'ValidationError';
  1402. ValidationError.prototype.prefixWith = function (dataPrefix, schemaPrefix) {
  1403. if (dataPrefix !== null) {
  1404. dataPrefix = dataPrefix.replace(/~/g, "~0").replace(/\//g, "~1");
  1405. this.dataPath = "/" + dataPrefix + this.dataPath;
  1406. }
  1407. if (schemaPrefix !== null) {
  1408. schemaPrefix = schemaPrefix.replace(/~/g, "~0").replace(/\//g, "~1");
  1409. this.schemaPath = "/" + schemaPrefix + this.schemaPath;
  1410. }
  1411. if (this.subErrors !== null) {
  1412. for (var i = 0; i < this.subErrors.length; i++) {
  1413. this.subErrors[i].prefixWith(dataPrefix, schemaPrefix);
  1414. }
  1415. }
  1416. return this;
  1417. };
  1418. function isTrustedUrl(baseUrl, testUrl) {
  1419. if(testUrl.substring(0, baseUrl.length) === baseUrl){
  1420. var remainder = testUrl.substring(baseUrl.length);
  1421. if ((testUrl.length > 0 && testUrl.charAt(baseUrl.length - 1) === "/")
  1422. || remainder.charAt(0) === "#"
  1423. || remainder.charAt(0) === "?") {
  1424. return true;
  1425. }
  1426. }
  1427. return false;
  1428. }
  1429. var languages = {};
  1430. function createApi(language) {
  1431. var globalContext = new ValidatorContext();
  1432. var currentLanguage;
  1433. var customErrorReporter;
  1434. var api = {
  1435. setErrorReporter: function (reporter) {
  1436. if (typeof reporter === 'string') {
  1437. return this.language(reporter);
  1438. }
  1439. customErrorReporter = reporter;
  1440. return true;
  1441. },
  1442. addFormat: function () {
  1443. globalContext.addFormat.apply(globalContext, arguments);
  1444. },
  1445. language: function (code) {
  1446. if (!code) {
  1447. return currentLanguage;
  1448. }
  1449. if (!languages[code]) {
  1450. code = code.split('-')[0]; // fall back to base language
  1451. }
  1452. if (languages[code]) {
  1453. currentLanguage = code;
  1454. return code; // so you can tell if fall-back has happened
  1455. }
  1456. return false;
  1457. },
  1458. addLanguage: function (code, messageMap) {
  1459. var key;
  1460. for (key in ErrorCodes) {
  1461. if (messageMap[key] && !messageMap[ErrorCodes[key]]) {
  1462. messageMap[ErrorCodes[key]] = messageMap[key];
  1463. }
  1464. }
  1465. var rootCode = code.split('-')[0];
  1466. if (!languages[rootCode]) { // use for base language if not yet defined
  1467. languages[code] = messageMap;
  1468. languages[rootCode] = messageMap;
  1469. } else {
  1470. languages[code] = Object.create(languages[rootCode]);
  1471. for (key in messageMap) {
  1472. if (typeof languages[rootCode][key] === 'undefined') {
  1473. languages[rootCode][key] = messageMap[key];
  1474. }
  1475. languages[code][key] = messageMap[key];
  1476. }
  1477. }
  1478. return this;
  1479. },
  1480. freshApi: function (language) {
  1481. var result = createApi();
  1482. if (language) {
  1483. result.language(language);
  1484. }
  1485. return result;
  1486. },
  1487. validate: function (data, schema, checkRecursive, banUnknownProperties) {
  1488. var def = defaultErrorReporter(currentLanguage);
  1489. var errorReporter = customErrorReporter ? function (error, data, schema) {
  1490. return customErrorReporter(error, data, schema) || def(error, data, schema);
  1491. } : def;
  1492. var context = new ValidatorContext(globalContext, false, errorReporter, checkRecursive, banUnknownProperties);
  1493. if (typeof schema === "string") {
  1494. schema = {"$ref": schema};
  1495. }
  1496. context.addSchema("", schema);
  1497. var error = context.validateAll(data, schema, null, null, "");
  1498. if (!error && banUnknownProperties) {
  1499. error = context.banUnknownProperties(data, schema);
  1500. }
  1501. this.error = error;
  1502. this.missing = context.missing;
  1503. this.valid = (error === null);
  1504. return this.valid;
  1505. },
  1506. validateResult: function () {
  1507. var result = {toString: function () {
  1508. return this.valid ? 'valid' : this.error.message;
  1509. }};
  1510. this.validate.apply(result, arguments);
  1511. return result;
  1512. },
  1513. validateMultiple: function (data, schema, checkRecursive, banUnknownProperties) {
  1514. var def = defaultErrorReporter(currentLanguage);
  1515. var errorReporter = customErrorReporter ? function (error, data, schema) {
  1516. return customErrorReporter(error, data, schema) || def(error, data, schema);
  1517. } : def;
  1518. var context = new ValidatorContext(globalContext, true, errorReporter, checkRecursive, banUnknownProperties);
  1519. if (typeof schema === "string") {
  1520. schema = {"$ref": schema};
  1521. }
  1522. context.addSchema("", schema);
  1523. context.validateAll(data, schema, null, null, "");
  1524. if (banUnknownProperties) {
  1525. context.banUnknownProperties(data, schema);
  1526. }
  1527. var result = {toString: function () {
  1528. return this.valid ? 'valid' : this.error.message;
  1529. }};
  1530. result.errors = context.errors;
  1531. result.missing = context.missing;
  1532. result.valid = (result.errors.length === 0);
  1533. return result;
  1534. },
  1535. addSchema: function () {
  1536. return globalContext.addSchema.apply(globalContext, arguments);
  1537. },
  1538. getSchema: function () {
  1539. return globalContext.getSchema.apply(globalContext, arguments);
  1540. },
  1541. getSchemaMap: function () {
  1542. return globalContext.getSchemaMap.apply(globalContext, arguments);
  1543. },
  1544. getSchemaUris: function () {
  1545. return globalContext.getSchemaUris.apply(globalContext, arguments);
  1546. },
  1547. getMissingUris: function () {
  1548. return globalContext.getMissingUris.apply(globalContext, arguments);
  1549. },
  1550. dropSchemas: function () {
  1551. globalContext.dropSchemas.apply(globalContext, arguments);
  1552. },
  1553. defineKeyword: function () {
  1554. globalContext.defineKeyword.apply(globalContext, arguments);
  1555. },
  1556. defineError: function (codeName, codeNumber, defaultMessage) {
  1557. if (typeof codeName !== 'string' || !/^[A-Z]+(_[A-Z]+)*$/.test(codeName)) {
  1558. throw new Error('Code name must be a string in UPPER_CASE_WITH_UNDERSCORES');
  1559. }
  1560. if (typeof codeNumber !== 'number' || codeNumber%1 !== 0 || codeNumber < 10000) {
  1561. throw new Error('Code number must be an integer > 10000');
  1562. }
  1563. if (typeof ErrorCodes[codeName] !== 'undefined') {
  1564. throw new Error('Error already defined: ' + codeName + ' as ' + ErrorCodes[codeName]);
  1565. }
  1566. if (typeof ErrorCodeLookup[codeNumber] !== 'undefined') {
  1567. throw new Error('Error code already used: ' + ErrorCodeLookup[codeNumber] + ' as ' + codeNumber);
  1568. }
  1569. ErrorCodes[codeName] = codeNumber;
  1570. ErrorCodeLookup[codeNumber] = codeName;
  1571. ErrorMessagesDefault[codeName] = ErrorMessagesDefault[codeNumber] = defaultMessage;
  1572. for (var langCode in languages) {
  1573. var language = languages[langCode];
  1574. if (language[codeName]) {
  1575. language[codeNumber] = language[codeNumber] || language[codeName];
  1576. }
  1577. }
  1578. },
  1579. reset: function () {
  1580. globalContext.reset();
  1581. this.error = null;
  1582. this.missing = [];
  1583. this.valid = true;
  1584. },
  1585. missing: [],
  1586. error: null,
  1587. valid: true,
  1588. normSchema: normSchema,
  1589. resolveUrl: resolveUrl,
  1590. getDocumentUri: getDocumentUri,
  1591. errorCodes: ErrorCodes
  1592. };
  1593. api.language(language || 'en');
  1594. return api;
  1595. }
  1596. var tv4 = createApi();
  1597. tv4.addLanguage('en-gb', ErrorMessagesDefault);
  1598. //legacy property
  1599. tv4.tv4 = tv4;
  1600. return tv4; // used by _header.js to globalise.
  1601. }));