z-schema 6.0.2 → 7.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +154 -134
  2. package/bin/z-schema +128 -124
  3. package/cjs/ZSchema.d.ts +227 -0
  4. package/cjs/ZSchema.js +13785 -0
  5. package/dist/Errors.js +50 -0
  6. package/dist/FormatValidators.js +136 -0
  7. package/{src → dist}/JsonValidation.js +184 -213
  8. package/dist/Report.js +220 -0
  9. package/{src → dist}/SchemaCache.js +67 -82
  10. package/{src → dist}/SchemaCompilation.js +89 -129
  11. package/dist/SchemaValidation.js +631 -0
  12. package/{src → dist}/Utils.js +96 -104
  13. package/dist/ZSchema.js +365 -0
  14. package/dist/index.js +2 -0
  15. package/dist/schemas/hyper-schema.json +156 -0
  16. package/dist/schemas/schema.json +151 -0
  17. package/dist/types/Errors.d.ts +44 -0
  18. package/dist/types/FormatValidators.d.ts +12 -0
  19. package/dist/types/JsonValidation.d.ts +37 -0
  20. package/dist/types/Report.d.ts +87 -0
  21. package/dist/types/SchemaCache.d.ts +26 -0
  22. package/dist/types/SchemaCompilation.d.ts +1 -0
  23. package/dist/types/SchemaValidation.d.ts +6 -0
  24. package/dist/types/Utils.d.ts +64 -0
  25. package/dist/types/ZSchema.d.ts +97 -0
  26. package/dist/types/index.d.ts +2 -0
  27. package/package.json +59 -45
  28. package/src/Errors.ts +56 -0
  29. package/src/FormatValidators.ts +136 -0
  30. package/src/JsonValidation.ts +624 -0
  31. package/src/Report.ts +337 -0
  32. package/src/SchemaCache.ts +189 -0
  33. package/src/SchemaCompilation.ts +293 -0
  34. package/src/SchemaValidation.ts +629 -0
  35. package/src/Utils.ts +286 -0
  36. package/src/ZSchema.ts +467 -0
  37. package/src/index.ts +3 -0
  38. package/src/schemas/_ +0 -0
  39. package/umd/ZSchema.js +13791 -0
  40. package/umd/ZSchema.min.js +1 -0
  41. package/dist/ZSchema-browser-min.js +0 -2
  42. package/dist/ZSchema-browser-min.js.map +0 -1
  43. package/dist/ZSchema-browser-test.js +0 -32247
  44. package/dist/ZSchema-browser.js +0 -12745
  45. package/index.d.ts +0 -175
  46. package/src/Errors.js +0 -60
  47. package/src/FormatValidators.js +0 -129
  48. package/src/Polyfills.js +0 -16
  49. package/src/Report.js +0 -299
  50. package/src/SchemaValidation.js +0 -619
  51. package/src/ZSchema.js +0 -409
package/index.d.ts DELETED
@@ -1,175 +0,0 @@
1
- // Type definitions for z-schema v3.16.0
2
- // Project: https://github.com/zaggino/z-schema
3
- // Definitions by: pgonzal <https://github.com/pgonzal>
4
- // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
5
-
6
- declare namespace Validator {
7
- export interface Options {
8
- asyncTimeout?: number;
9
- forceAdditional?: boolean;
10
- assumeAdditional?: boolean;
11
- forceItems?: boolean;
12
- forceMinItems?: boolean;
13
- forceMaxItems?: boolean;
14
- forceMinLength?: boolean;
15
- forceMaxLength?: boolean;
16
- forceProperties?: boolean;
17
- ignoreUnresolvableReferences?: boolean;
18
- noExtraKeywords?: boolean;
19
- noTypeless?: boolean;
20
- noEmptyStrings?: boolean;
21
- noEmptyArrays?: boolean;
22
- strictUris?: boolean;
23
- strictMode?: boolean;
24
- reportPathAsArray?: boolean;
25
- breakOnFirstError?: boolean;
26
- pedanticCheck?: boolean;
27
- ignoreUnknownFormats?: boolean;
28
- customValidator?: (report: Report, schema: any, json: any) => void;
29
- }
30
-
31
- export interface SchemaError extends Error {
32
- /**
33
- * Implements the Error.name contract. The value is always "z-schema validation error".
34
- */
35
- name: string;
36
-
37
- /**
38
- * An identifier indicating the type of error.
39
- * Example: "JSON_OBJECT_VALIDATION_FAILED"
40
- */
41
- message: string;
42
-
43
- /**
44
- * Returns details for each error that occurred during validation.
45
- * See Options.breakOnFirstError.
46
- */
47
- details: SchemaErrorDetail[];
48
- }
49
-
50
- export interface SchemaErrorDetail {
51
- /**
52
- * Example: "Expected type string but found type array"
53
- */
54
- message: string;
55
- /**
56
- * An error identifier that can be used to format a custom error message.
57
- * Example: "INVALID_TYPE"
58
- */
59
- code: string;
60
- /**
61
- * Format parameters that can be used to format a custom error message.
62
- * Example: ["string","array"]
63
- */
64
- params: Array<string>;
65
- /**
66
- * A JSON path indicating the location of the error.
67
- * Example: "#/projects/1"
68
- */
69
- path: string;
70
- /**
71
- * The schema rule description, which is included for certain errors where
72
- * this information is useful (e.g. to describe a constraint).
73
- */
74
- description: string;
75
-
76
- /**
77
- * Returns details for sub-schemas that failed to match. For example, if the schema
78
- * uses the "oneOf" constraint to accept several alternative possibilities, each
79
- * alternative will have its own inner detail object explaining why it failed to match.
80
- */
81
- inner: SchemaErrorDetail[];
82
- }
83
-
84
- export const schemaSymbol: unique symbol
85
-
86
- export const jsonSymbol: unique symbol
87
- }
88
-
89
- declare class Validator {
90
- public lastReport: Report | undefined;
91
-
92
- /**
93
- * Register a custom format.
94
- *
95
- * @param name - name of the custom format
96
- * @param validatorFunction - custom format validator function.
97
- * Returns `true` if `value` matches the custom format.
98
- */
99
- public static registerFormat(formatName: string, validatorFunction: (value: any) => boolean): void;
100
-
101
- /**
102
- * Unregister a format.
103
- *
104
- * @param name - name of the custom format
105
- */
106
- public static unregisterFormat(name: string): void;
107
-
108
- /**
109
- * Get the list of all registered formats.
110
- *
111
- * Both the names of the burned-in formats and the custom format names are
112
- * returned by this function.
113
- *
114
- * @returns {string[]} the list of all registered format names.
115
- */
116
- public static getRegisteredFormats(): string[];
117
-
118
- public static getDefaultOptions(): Validator.Options;
119
-
120
- constructor(options: Validator.Options);
121
-
122
- /**
123
- * @param schema - JSON object representing schema
124
- * @returns {boolean} true if schema is valid.
125
- */
126
- validateSchema(schema: any): boolean;
127
-
128
- /**
129
- * @param json - either a JSON string or a parsed JSON object
130
- * @param schema - the JSON object representing the schema
131
- * @returns true if json matches schema
132
- */
133
- validate(json: any, schema: any): boolean;
134
-
135
- /**
136
- * @param json - either a JSON string or a parsed JSON object
137
- * @param schema - the JSON object representing the schema
138
- */
139
- validate(json: any, schema: any, callback: (err: any, valid: boolean) => void): void;
140
-
141
- /**
142
- * Returns an Error object for the most recent failed validation, or null if the validation was successful.
143
- */
144
- getLastError(): Validator.SchemaError;
145
-
146
- /**
147
- * Returns the error details for the most recent validation, or undefined if the validation was successful.
148
- * This is the same list as the SchemaError.details property.
149
- */
150
- getLastErrors(): Validator.SchemaErrorDetail[];
151
- }
152
-
153
- /**
154
- * Basic representation of the Report class -- just enough to support customValidator
155
- */
156
- declare class Report {
157
- errors: Validator.SchemaErrorDetail[];
158
-
159
- /**
160
- * Returns whether the validation did pass
161
- */
162
- isValid(): boolean;
163
-
164
- /**
165
- * @param errorCode - a string representing the code for the custom error, e.g. INVALID_VALUE_SET
166
- * @param errorMessage - string with the message to be returned in the error
167
- * @param params - an array of relevant params for the error, e.g. [fieldName, fieldValue]
168
- * @param subReports - sub-schema involved in the error
169
- * @param schemaDescription - description from the schema used in the validation
170
- * Adds custom error to the errors array in the validation instance and sets valid to false if it is not already set as false
171
- */
172
- addCustomError: (errorCode: string, errorMessage: string, params: string[], subReports: string, schemaDescription: string) => void;
173
- }
174
-
175
- export = Validator;
package/src/Errors.js DELETED
@@ -1,60 +0,0 @@
1
- "use strict";
2
-
3
- module.exports = {
4
-
5
- INVALID_TYPE: "Expected type {0} but found type {1}",
6
- INVALID_FORMAT: "Object didn't pass validation for format {0}: {1}",
7
- ENUM_MISMATCH: "No enum match for: {0}",
8
- ENUM_CASE_MISMATCH: "Enum does not match case for: {0}",
9
- ANY_OF_MISSING: "Data does not match any schemas from 'anyOf'",
10
- ONE_OF_MISSING: "Data does not match any schemas from 'oneOf'",
11
- ONE_OF_MULTIPLE: "Data is valid against more than one schema from 'oneOf'",
12
- NOT_PASSED: "Data matches schema from 'not'",
13
-
14
- // Array errors
15
- ARRAY_LENGTH_SHORT: "Array is too short ({0}), minimum {1}",
16
- ARRAY_LENGTH_LONG: "Array is too long ({0}), maximum {1}",
17
- ARRAY_UNIQUE: "Array items are not unique (indexes {0} and {1})",
18
- ARRAY_ADDITIONAL_ITEMS: "Additional items not allowed",
19
-
20
- // Numeric errors
21
- MULTIPLE_OF: "Value {0} is not a multiple of {1}",
22
- MINIMUM: "Value {0} is less than minimum {1}",
23
- MINIMUM_EXCLUSIVE: "Value {0} is equal or less than exclusive minimum {1}",
24
- MAXIMUM: "Value {0} is greater than maximum {1}",
25
- MAXIMUM_EXCLUSIVE: "Value {0} is equal or greater than exclusive maximum {1}",
26
-
27
- // Object errors
28
- OBJECT_PROPERTIES_MINIMUM: "Too few properties defined ({0}), minimum {1}",
29
- OBJECT_PROPERTIES_MAXIMUM: "Too many properties defined ({0}), maximum {1}",
30
- OBJECT_MISSING_REQUIRED_PROPERTY: "Missing required property: {0}",
31
- OBJECT_ADDITIONAL_PROPERTIES: "Additional properties not allowed: {0}",
32
- OBJECT_DEPENDENCY_KEY: "Dependency failed - key must exist: {0} (due to key: {1})",
33
-
34
- // String errors
35
- MIN_LENGTH: "String is too short ({0} chars), minimum {1}",
36
- MAX_LENGTH: "String is too long ({0} chars), maximum {1}",
37
- PATTERN: "String does not match pattern {0}: {1}",
38
-
39
- // Schema validation errors
40
- KEYWORD_TYPE_EXPECTED: "Keyword '{0}' is expected to be of type '{1}'",
41
- KEYWORD_UNDEFINED_STRICT: "Keyword '{0}' must be defined in strict mode",
42
- KEYWORD_UNEXPECTED: "Keyword '{0}' is not expected to appear in the schema",
43
- KEYWORD_MUST_BE: "Keyword '{0}' must be {1}",
44
- KEYWORD_DEPENDENCY: "Keyword '{0}' requires keyword '{1}'",
45
- KEYWORD_PATTERN: "Keyword '{0}' is not a valid RegExp pattern: {1}",
46
- KEYWORD_VALUE_TYPE: "Each element of keyword '{0}' array must be a '{1}'",
47
- UNKNOWN_FORMAT: "There is no validation function for format '{0}'",
48
- CUSTOM_MODE_FORCE_PROPERTIES: "{0} must define at least one property if present",
49
-
50
- // Remote errors
51
- REF_UNRESOLVED: "Reference has not been resolved during compilation: {0}",
52
- UNRESOLVABLE_REFERENCE: "Reference could not be resolved: {0}",
53
- SCHEMA_NOT_REACHABLE: "Validator was not able to read schema with uri: {0}",
54
- SCHEMA_TYPE_EXPECTED: "Schema is expected to be of type 'object'",
55
- SCHEMA_NOT_AN_OBJECT: "Schema is not an object: {0}",
56
- ASYNC_TIMEOUT: "{0} asynchronous task(s) have timed out after {1} ms",
57
- PARENT_SCHEMA_VALIDATION_FAILED: "Schema failed to validate against its parent schema, see inner errors for details.",
58
- REMOTE_NOT_VALID: "Remote reference didn't compile successfully: {0}"
59
-
60
- };
@@ -1,129 +0,0 @@
1
- /*jshint maxlen: false*/
2
-
3
- var validator = require("validator");
4
-
5
- var FormatValidators = {
6
- "date": function (date) {
7
- if (typeof date !== "string") {
8
- return true;
9
- }
10
- // full-date from http://tools.ietf.org/html/rfc3339#section-5.6
11
- var matches = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/.exec(date);
12
- if (matches === null) {
13
- return false;
14
- }
15
- // var year = matches[1];
16
- // var month = matches[2];
17
- // var day = matches[3];
18
- if (matches[2] < "01" || matches[2] > "12" || matches[3] < "01" || matches[3] > "31") {
19
- return false;
20
- }
21
- return true;
22
- },
23
- "date-time": function (dateTime) {
24
- if (typeof dateTime !== "string") {
25
- return true;
26
- }
27
- // date-time from http://tools.ietf.org/html/rfc3339#section-5.6
28
- var s = dateTime.toLowerCase().split("t");
29
- if (!FormatValidators.date(s[0])) {
30
- return false;
31
- }
32
- var matches = /^([0-9]{2}):([0-9]{2}):([0-9]{2})(.[0-9]+)?(z|([+-][0-9]{2}:[0-9]{2}))$/.exec(s[1]);
33
- if (matches === null) {
34
- return false;
35
- }
36
- // var hour = matches[1];
37
- // var minute = matches[2];
38
- // var second = matches[3];
39
- // var fraction = matches[4];
40
- // var timezone = matches[5];
41
- if (matches[1] > "23" || matches[2] > "59" || matches[3] > "59") {
42
- return false;
43
- }
44
- return true;
45
- },
46
- "email": function (email) {
47
- if (typeof email !== "string") {
48
- return true;
49
- }
50
- return validator.isEmail(email, { "require_tld": true });
51
- },
52
- "hostname": function (hostname) {
53
- if (typeof hostname !== "string") {
54
- return true;
55
- }
56
- /*
57
- http://json-schema.org/latest/json-schema-validation.html#anchor114
58
- A string instance is valid against this attribute if it is a valid
59
- representation for an Internet host name, as defined by RFC 1034, section 3.1 [RFC1034].
60
-
61
- http://tools.ietf.org/html/rfc1034#section-3.5
62
-
63
- <digit> ::= any one of the ten digits 0 through 9
64
- var digit = /[0-9]/;
65
-
66
- <letter> ::= any one of the 52 alphabetic characters A through Z in upper case and a through z in lower case
67
- var letter = /[a-zA-Z]/;
68
-
69
- <let-dig> ::= <letter> | <digit>
70
- var letDig = /[0-9a-zA-Z]/;
71
-
72
- <let-dig-hyp> ::= <let-dig> | "-"
73
- var letDigHyp = /[-0-9a-zA-Z]/;
74
-
75
- <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
76
- var ldhStr = /[-0-9a-zA-Z]+/;
77
-
78
- <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
79
- var label = /[a-zA-Z](([-0-9a-zA-Z]+)?[0-9a-zA-Z])?/;
80
-
81
- <subdomain> ::= <label> | <subdomain> "." <label>
82
- var subdomain = /^[a-zA-Z](([-0-9a-zA-Z]+)?[0-9a-zA-Z])?(\.[a-zA-Z](([-0-9a-zA-Z]+)?[0-9a-zA-Z])?)*$/;
83
-
84
- <domain> ::= <subdomain> | " "
85
- var domain = null;
86
- */
87
- var valid = /^[a-zA-Z](([-0-9a-zA-Z]+)?[0-9a-zA-Z])?(\.[a-zA-Z](([-0-9a-zA-Z]+)?[0-9a-zA-Z])?)*$/.test(hostname);
88
- if (valid) {
89
- // the sum of all label octets and label lengths is limited to 255.
90
- if (hostname.length > 255) { return false; }
91
- // Each node has a label, which is zero to 63 octets in length
92
- var labels = hostname.split(".");
93
- for (var i = 0; i < labels.length; i++) { if (labels[i].length > 63) { return false; } }
94
- }
95
- return valid;
96
- },
97
- "host-name": function (hostname) {
98
- return FormatValidators.hostname.call(this, hostname);
99
- },
100
- "ipv4": function (ipv4) {
101
- if (typeof ipv4 !== "string") { return true; }
102
- return validator.isIP(ipv4, 4);
103
- },
104
- "ipv6": function (ipv6) {
105
- if (typeof ipv6 !== "string") { return true; }
106
- return validator.isIP(ipv6, 6);
107
- },
108
- "regex": function (str) {
109
- try {
110
- RegExp(str);
111
- return true;
112
- } catch (e) {
113
- return false;
114
- }
115
- },
116
- "uri": function (uri) {
117
- if (this.options.strictUris) {
118
- return FormatValidators["strict-uri"].apply(this, arguments);
119
- }
120
- // https://github.com/zaggino/z-schema/issues/18
121
- // RegExp from http://tools.ietf.org/html/rfc3986#appendix-B
122
- return typeof uri !== "string" || RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?").test(uri);
123
- },
124
- "strict-uri": function (uri) {
125
- return typeof uri !== "string" || validator.isURL(uri);
126
- }
127
- };
128
-
129
- module.exports = FormatValidators;
package/src/Polyfills.js DELETED
@@ -1,16 +0,0 @@
1
- // Number.isFinite polyfill
2
- // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isfinite
3
- if (typeof Number.isFinite !== "function") {
4
- Number.isFinite = function isFinite(value) {
5
- // 1. If Type(number) is not Number, return false.
6
- if (typeof value !== "number") {
7
- return false;
8
- }
9
- // 2. If number is NaN, +∞, or −∞, return false.
10
- if (value !== value || value === Infinity || value === -Infinity) {
11
- return false;
12
- }
13
- // 3. Otherwise, return true.
14
- return true;
15
- };
16
- }
package/src/Report.js DELETED
@@ -1,299 +0,0 @@
1
- "use strict";
2
-
3
- var get = require("lodash.get");
4
- var Errors = require("./Errors");
5
- var Utils = require("./Utils");
6
-
7
- /**
8
- * @class
9
- *
10
- * @param {Report|object} parentOrOptions
11
- * @param {object} [reportOptions]
12
- */
13
- function Report(parentOrOptions, reportOptions) {
14
- this.parentReport = parentOrOptions instanceof Report ?
15
- parentOrOptions :
16
- undefined;
17
-
18
- this.options = parentOrOptions instanceof Report ?
19
- parentOrOptions.options :
20
- parentOrOptions || {};
21
-
22
- this.reportOptions = reportOptions || {};
23
-
24
- this.errors = [];
25
- /**
26
- * @type {string[]}
27
- */
28
- this.path = [];
29
- this.asyncTasks = [];
30
-
31
- this.rootSchema = undefined;
32
- this.commonErrorMessage = undefined;
33
- this.json = undefined;
34
- }
35
-
36
- /**
37
- * @returns {boolean}
38
- */
39
- Report.prototype.isValid = function () {
40
- if (this.asyncTasks.length > 0) {
41
- throw new Error("Async tasks pending, can't answer isValid");
42
- }
43
- return this.errors.length === 0;
44
- };
45
-
46
- /**
47
- *
48
- * @param {*} fn
49
- * @param {*} args
50
- * @param {*} asyncTaskResultProcessFn
51
- */
52
- Report.prototype.addAsyncTask = function (fn, args, asyncTaskResultProcessFn) {
53
- this.asyncTasks.push([fn, args, asyncTaskResultProcessFn]);
54
- };
55
-
56
- Report.prototype.getAncestor = function (id) {
57
- if (!this.parentReport) {
58
- return undefined;
59
- }
60
- if (this.parentReport.getSchemaId() === id) {
61
- return this.parentReport;
62
- }
63
- return this.parentReport.getAncestor(id);
64
- };
65
-
66
- /**
67
- *
68
- * @param {*} timeout
69
- * @param {function(*, *)} callback
70
- *
71
- * @returns {void}
72
- */
73
- Report.prototype.processAsyncTasks = function (timeout, callback) {
74
-
75
- var validationTimeout = timeout || 2000,
76
- tasksCount = this.asyncTasks.length,
77
- idx = tasksCount,
78
- timedOut = false,
79
- self = this;
80
-
81
- function finish() {
82
- process.nextTick(function () {
83
- var valid = self.errors.length === 0,
84
- err = valid ? null : self.errors;
85
- callback(err, valid);
86
- });
87
- }
88
-
89
- function respond(asyncTaskResultProcessFn) {
90
- return function (asyncTaskResult) {
91
- if (timedOut) { return; }
92
- asyncTaskResultProcessFn(asyncTaskResult);
93
- if (--tasksCount === 0) {
94
- finish();
95
- }
96
- };
97
- }
98
-
99
- // finish if tasks are completed or there are any errors and breaking on first error was requested
100
- if (tasksCount === 0 || (this.errors.length > 0 && this.options.breakOnFirstError)) {
101
- finish();
102
- return;
103
- }
104
-
105
- while (idx--) {
106
- var task = this.asyncTasks[idx];
107
- task[0].apply(null, task[1].concat(respond(task[2])));
108
- }
109
-
110
- setTimeout(function () {
111
- if (tasksCount > 0) {
112
- timedOut = true;
113
- self.addError("ASYNC_TIMEOUT", [tasksCount, validationTimeout]);
114
- callback(self.errors, false);
115
- }
116
- }, validationTimeout);
117
-
118
- };
119
-
120
- /**
121
- *
122
- * @param {*} returnPathAsString
123
- *
124
- * @return {string[]|string}
125
- */
126
- Report.prototype.getPath = function (returnPathAsString) {
127
- /**
128
- * @type {string[]|string}
129
- */
130
- var path = [];
131
- if (this.parentReport) {
132
- path = path.concat(this.parentReport.path);
133
- }
134
- path = path.concat(this.path);
135
-
136
- if (returnPathAsString !== true) {
137
- // Sanitize the path segments (http://tools.ietf.org/html/rfc6901#section-4)
138
- path = "#/" + path.map(function (segment) {
139
- segment = segment.toString();
140
-
141
- if (Utils.isAbsoluteUri(segment)) {
142
- return "uri(" + segment + ")";
143
- }
144
-
145
- return segment.replace(/\~/g, "~0").replace(/\//g, "~1");
146
- }).join("/");
147
- }
148
- return path;
149
- };
150
-
151
- Report.prototype.getSchemaId = function () {
152
-
153
- if (!this.rootSchema) {
154
- return null;
155
- }
156
-
157
- // get the error path as an array
158
- var path = [];
159
- if (this.parentReport) {
160
- path = path.concat(this.parentReport.path);
161
- }
162
- path = path.concat(this.path);
163
-
164
- // try to find id in the error path
165
- while (path.length > 0) {
166
- var obj = get(this.rootSchema, path);
167
- if (obj && obj.id) { return obj.id; }
168
- path.pop();
169
- }
170
-
171
- // return id of the root
172
- return this.rootSchema.id;
173
- };
174
-
175
- /**
176
- *
177
- * @param {*} errorCode
178
- * @param {*} params
179
- *
180
- * @return {boolean}
181
- */
182
- Report.prototype.hasError = function (errorCode, params) {
183
- var idx = this.errors.length;
184
- while (idx--) {
185
- if (this.errors[idx].code === errorCode) {
186
- // assume match
187
- var match = true;
188
-
189
- // check the params too
190
- var idx2 = this.errors[idx].params.length;
191
- while (idx2--) {
192
- if (this.errors[idx].params[idx2] !== params[idx2]) {
193
- match = false;
194
- }
195
- }
196
-
197
- // if match, return true
198
- if (match) { return match; }
199
- }
200
- }
201
- return false;
202
- };
203
-
204
- /**
205
- *
206
- * @param {*} errorCode
207
- * @param {*} params
208
- * @param {Report[]|Report} [subReports]
209
- * @param {*} [schema]
210
- *
211
- * @return {void}
212
- */
213
- Report.prototype.addError = function (errorCode, params, subReports, schema) {
214
- if (!errorCode) { throw new Error("No errorCode passed into addError()"); }
215
-
216
- this.addCustomError(errorCode, Errors[errorCode], params, subReports, schema);
217
- };
218
-
219
- Report.prototype.getJson = function () {
220
- var self = this;
221
- while (self.json === undefined) {
222
- self = self.parentReport;
223
- if (self === undefined) {
224
- return undefined;
225
- }
226
- }
227
- return self.json;
228
- };
229
-
230
- /**
231
- *
232
- * @param {*} errorCode
233
- * @param {*} errorMessage
234
- * @param {*[]} params
235
- * @param {Report[]|Report} subReports
236
- * @param {*} schema
237
- *
238
- * @returns {void}
239
- */
240
- Report.prototype.addCustomError = function (errorCode, errorMessage, params, subReports, schema) {
241
- if (this.errors.length >= this.reportOptions.maxErrors) {
242
- return;
243
- }
244
-
245
- if (!errorMessage) { throw new Error("No errorMessage known for code " + errorCode); }
246
-
247
- params = params || [];
248
-
249
- var idx = params.length;
250
- while (idx--) {
251
- var whatIs = Utils.whatIs(params[idx]);
252
- var param = (whatIs === "object" || whatIs === "null") ? JSON.stringify(params[idx]) : params[idx];
253
- errorMessage = errorMessage.replace("{" + idx + "}", param);
254
- }
255
-
256
- var err = {
257
- code: errorCode,
258
- params: params,
259
- message: errorMessage,
260
- path: this.getPath(this.options.reportPathAsArray),
261
- schemaId: this.getSchemaId()
262
- };
263
-
264
- err[Utils.schemaSymbol] = schema;
265
- err[Utils.jsonSymbol] = this.getJson();
266
-
267
- if (schema && typeof schema === "string") {
268
- err.description = schema;
269
- } else if (schema && typeof schema === "object") {
270
- if (schema.title) {
271
- err.title = schema.title;
272
- }
273
- if (schema.description) {
274
- err.description = schema.description;
275
- }
276
- }
277
-
278
- if (subReports != null) {
279
- if (!Array.isArray(subReports)) {
280
- subReports = [subReports];
281
- }
282
- err.inner = [];
283
- idx = subReports.length;
284
- while (idx--) {
285
- var subReport = subReports[idx],
286
- idx2 = subReport.errors.length;
287
- while (idx2--) {
288
- err.inner.push(subReport.errors[idx2]);
289
- }
290
- }
291
- if (err.inner.length === 0) {
292
- err.inner = undefined;
293
- }
294
- }
295
-
296
- this.errors.push(err);
297
- };
298
-
299
- module.exports = Report;