z-schema 12.2.0 → 12.4.0

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 (111) hide show
  1. package/README.md +2 -2
  2. package/bin/z-schema +1 -1
  3. package/cjs/{index.js → index.cjs} +838 -707
  4. package/cjs/{index.d.ts → index.d.cts} +47 -26
  5. package/dist/{errors.d.mts → errors.d.ts} +2 -2
  6. package/dist/{errors.mjs → errors.js} +1 -2
  7. package/dist/{format-validators.mjs → format-validators.js} +60 -43
  8. package/dist/{index.d.mts → index.d.ts} +9 -9
  9. package/dist/{index.mjs → index.js} +3 -3
  10. package/dist/{json-schema-versions.d.mts → json-schema-versions.d.ts} +34 -3
  11. package/dist/{json-schema.d.mts → json-schema.d.ts} +7 -7
  12. package/dist/{json-schema.mjs → json-schema.js} +6 -5
  13. package/dist/{json-validation.mjs → json-validation.js} +144 -127
  14. package/dist/{report.d.mts → report.d.ts} +8 -9
  15. package/dist/{report.mjs → report.js} +28 -31
  16. package/dist/{schema-cache.d.mts → schema-cache.d.ts} +5 -5
  17. package/dist/{schema-cache.mjs → schema-cache.js} +10 -11
  18. package/dist/{schema-compiler.d.mts → schema-compiler.d.ts} +4 -4
  19. package/dist/{schema-compiler.mjs → schema-compiler.js} +101 -79
  20. package/dist/{schema-validator.d.mts → schema-validator.d.ts} +5 -5
  21. package/dist/{schema-validator.mjs → schema-validator.js} +138 -166
  22. package/dist/utils/{array.mjs → array.js} +4 -3
  23. package/dist/utils/{base64.mjs → base64.js} +3 -2
  24. package/dist/utils/{clone.mjs → clone.js} +18 -20
  25. package/dist/utils/hostname.js +176 -0
  26. package/dist/utils/{json.mjs → json.js} +13 -8
  27. package/dist/utils/{schema-regex.mjs → schema-regex.js} +5 -5
  28. package/dist/utils/{time.mjs → time.js} +8 -8
  29. package/dist/utils/unicode.js +22 -0
  30. package/dist/utils/{what-is.mjs → what-is.js} +1 -2
  31. package/dist/validation/{array.mjs → array.js} +18 -20
  32. package/dist/validation/{combinators.mjs → combinators.js} +16 -16
  33. package/dist/validation/{numeric.mjs → numeric.js} +11 -11
  34. package/dist/validation/{object.mjs → object.js} +35 -34
  35. package/dist/validation/{ref.mjs → ref.js} +5 -5
  36. package/dist/validation/{shared.mjs → shared.js} +15 -12
  37. package/dist/validation/{string.mjs → string.js} +35 -35
  38. package/dist/validation/type.js +34 -0
  39. package/dist/{z-schema-base.d.mts → z-schema-base.d.ts} +11 -12
  40. package/dist/{z-schema-base.mjs → z-schema-base.js} +45 -40
  41. package/dist/{z-schema-options.d.mts → z-schema-options.d.ts} +3 -3
  42. package/dist/{z-schema-options.mjs → z-schema-options.js} +5 -5
  43. package/dist/{z-schema-reader.d.mts → z-schema-reader.d.ts} +1 -1
  44. package/dist/{z-schema-versions.mjs → z-schema-versions.js} +21 -21
  45. package/dist/{z-schema.d.mts → z-schema.d.ts} +5 -13
  46. package/dist/{z-schema.mjs → z-schema.js} +38 -48
  47. package/package.json +24 -25
  48. package/src/errors.ts +1 -2
  49. package/src/format-validators.ts +173 -67
  50. package/src/json-schema-versions.ts +56 -2
  51. package/src/json-schema.ts +10 -9
  52. package/src/json-validation.ts +189 -146
  53. package/src/report.ts +37 -49
  54. package/src/schema-cache.ts +13 -13
  55. package/src/schema-compiler.ts +170 -117
  56. package/src/schema-validator.ts +239 -238
  57. package/src/utils/array.ts +9 -6
  58. package/src/utils/base64.ts +13 -2
  59. package/src/utils/clone.ts +28 -30
  60. package/src/utils/date.ts +6 -3
  61. package/src/utils/hostname.ts +257 -31
  62. package/src/utils/json.ts +16 -9
  63. package/src/utils/properties.ts +2 -2
  64. package/src/utils/schema-regex.ts +4 -4
  65. package/src/utils/time.ts +8 -7
  66. package/src/utils/unicode.ts +12 -5
  67. package/src/utils/what-is.ts +1 -5
  68. package/src/validation/array.ts +24 -22
  69. package/src/validation/combinators.ts +14 -14
  70. package/src/validation/numeric.ts +14 -28
  71. package/src/validation/object.ts +32 -36
  72. package/src/validation/ref.ts +5 -6
  73. package/src/validation/shared.ts +22 -21
  74. package/src/validation/string.ts +36 -42
  75. package/src/validation/type.ts +17 -17
  76. package/src/z-schema-base.ts +49 -38
  77. package/src/z-schema-options.ts +4 -3
  78. package/src/z-schema.ts +35 -45
  79. package/umd/ZSchema.js +853 -715
  80. package/umd/ZSchema.min.js +2 -2
  81. package/umd/package.json +3 -0
  82. package/dist/utils/hostname.mjs +0 -75
  83. package/dist/utils/unicode.mjs +0 -12
  84. package/dist/validation/type.mjs +0 -32
  85. /package/dist/{format-validators.d.mts → format-validators.d.ts} +0 -0
  86. /package/dist/{json-schema-versions.mjs → json-schema-versions.js} +0 -0
  87. /package/dist/schemas/{draft-04-schema.mjs → draft-04-schema.js} +0 -0
  88. /package/dist/schemas/{draft-06-schema.mjs → draft-06-schema.js} +0 -0
  89. /package/dist/schemas/{draft-07-schema.mjs → draft-07-schema.js} +0 -0
  90. /package/dist/schemas/{draft-2019-09-meta-applicator.mjs → draft-2019-09-meta-applicator.js} +0 -0
  91. /package/dist/schemas/{draft-2019-09-meta-content.mjs → draft-2019-09-meta-content.js} +0 -0
  92. /package/dist/schemas/{draft-2019-09-meta-core.mjs → draft-2019-09-meta-core.js} +0 -0
  93. /package/dist/schemas/{draft-2019-09-meta-format.mjs → draft-2019-09-meta-format.js} +0 -0
  94. /package/dist/schemas/{draft-2019-09-meta-meta-data.mjs → draft-2019-09-meta-meta-data.js} +0 -0
  95. /package/dist/schemas/{draft-2019-09-meta-validation.mjs → draft-2019-09-meta-validation.js} +0 -0
  96. /package/dist/schemas/{draft-2019-09-schema.mjs → draft-2019-09-schema.js} +0 -0
  97. /package/dist/schemas/{draft-2020-12-meta-applicator.mjs → draft-2020-12-meta-applicator.js} +0 -0
  98. /package/dist/schemas/{draft-2020-12-meta-content.mjs → draft-2020-12-meta-content.js} +0 -0
  99. /package/dist/schemas/{draft-2020-12-meta-core.mjs → draft-2020-12-meta-core.js} +0 -0
  100. /package/dist/schemas/{draft-2020-12-meta-format-annotation.mjs → draft-2020-12-meta-format-annotation.js} +0 -0
  101. /package/dist/schemas/{draft-2020-12-meta-format-assertion.mjs → draft-2020-12-meta-format-assertion.js} +0 -0
  102. /package/dist/schemas/{draft-2020-12-meta-meta-data.mjs → draft-2020-12-meta-meta-data.js} +0 -0
  103. /package/dist/schemas/{draft-2020-12-meta-unevaluated.mjs → draft-2020-12-meta-unevaluated.js} +0 -0
  104. /package/dist/schemas/{draft-2020-12-meta-validation.mjs → draft-2020-12-meta-validation.js} +0 -0
  105. /package/dist/schemas/{draft-2020-12-schema.mjs → draft-2020-12-schema.js} +0 -0
  106. /package/dist/utils/{constants.mjs → constants.js} +0 -0
  107. /package/dist/utils/{date.mjs → date.js} +0 -0
  108. /package/dist/utils/{properties.mjs → properties.js} +0 -0
  109. /package/dist/utils/{symbols.mjs → symbols.js} +0 -0
  110. /package/dist/utils/{uri.mjs → uri.js} +0 -0
  111. /package/dist/{z-schema-reader.mjs → z-schema-reader.js} +0 -0
@@ -25,26 +25,15 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
25
25
  }) : target, mod));
26
26
  //#endregion
27
27
  let validator_lib_isEmail_js = require("validator/lib/isEmail.js");
28
- validator_lib_isEmail_js = __toESM(validator_lib_isEmail_js);
28
+ validator_lib_isEmail_js = __toESM(validator_lib_isEmail_js, 1);
29
29
  let validator_lib_isIP_js = require("validator/lib/isIP.js");
30
- validator_lib_isIP_js = __toESM(validator_lib_isIP_js);
30
+ validator_lib_isIP_js = __toESM(validator_lib_isIP_js, 1);
31
31
  let validator_lib_isURL_js = require("validator/lib/isURL.js");
32
- validator_lib_isURL_js = __toESM(validator_lib_isURL_js);
32
+ validator_lib_isURL_js = __toESM(validator_lib_isURL_js, 1);
33
33
  let punycode_punycode_js = require("punycode/punycode.js");
34
- punycode_punycode_js = __toESM(punycode_punycode_js);
34
+ punycode_punycode_js = __toESM(punycode_punycode_js, 1);
35
35
  let safe_regex2 = require("safe-regex2");
36
- safe_regex2 = __toESM(safe_regex2);
37
- //#region src/utils/uri.ts
38
- const getQueryPath = (uri) => {
39
- const io = uri.indexOf("#");
40
- return io === -1 ? void 0 : uri.slice(io + 1);
41
- };
42
- const getRemotePath = (uri) => {
43
- const io = uri.indexOf("#");
44
- return io === -1 ? uri : uri.slice(0, io);
45
- };
46
- const isAbsoluteUri = (uri) => /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(uri);
47
- //#endregion
36
+ safe_regex2 = __toESM(safe_regex2, 1);
48
37
  //#region src/utils/constants.ts
49
38
  /**
50
39
  * Maximum allowed value for {@link ZSchemaOptions.asyncTimeout} in milliseconds.
@@ -60,6 +49,17 @@ const MAX_ASYNC_TIMEOUT = 6e4;
60
49
  */
61
50
  const MAX_SCHEMA_REGEX_LENGTH = 1e4;
62
51
  //#endregion
52
+ //#region src/utils/uri.ts
53
+ const getQueryPath = (uri) => {
54
+ const io = uri.indexOf("#");
55
+ return io === -1 ? void 0 : uri.slice(io + 1);
56
+ };
57
+ const getRemotePath = (uri) => {
58
+ const io = uri.indexOf("#");
59
+ return io === -1 ? uri : uri.slice(0, io);
60
+ };
61
+ const isAbsoluteUri = (uri) => /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(uri);
62
+ //#endregion
63
63
  //#region src/utils/what-is.ts
64
64
  const whatIs = (what) => {
65
65
  if (typeof what === "object") {
@@ -68,8 +68,7 @@ const whatIs = (what) => {
68
68
  return "object";
69
69
  }
70
70
  if (typeof what === "number") {
71
- if (Number.isFinite(what)) if (what % 1 === 0) return "integer";
72
- else return "number";
71
+ if (Number.isFinite(what)) return what % 1 === 0 ? "integer" : "number";
73
72
  if (Number.isNaN(what)) return "not-a-number";
74
73
  return "unknown-number";
75
74
  }
@@ -81,18 +80,12 @@ function isObject(value) {
81
80
  function isInteger(value) {
82
81
  return typeof value === "number" && Number.isFinite(value) && value % 1 === 0;
83
82
  }
84
- //#endregion
85
- //#region src/json-schema.ts
86
- /**
87
- * Keywords whose values are not JSON Schema sub-schemas and must not be
88
- * traversed during schema walking (id collection, reference collection, etc.).
89
- */
90
- const NON_SCHEMA_KEYWORDS = [
83
+ const NON_SCHEMA_KEYWORDS_SET = /* @__PURE__ */ new Set([
91
84
  "enum",
92
85
  "const",
93
86
  "default",
94
87
  "examples"
95
- ];
88
+ ]);
96
89
  /** Returns true if the key is an internal z-schema property (prefixed with `__$`). */
97
90
  const isInternalKey = (key) => key.startsWith("__$");
98
91
  const getId = (schema) => {
@@ -113,7 +106,7 @@ const findId = (schema, id, targetBaseUri, currentBaseUri, maxDepth = 100, _dept
113
106
  } catch {}
114
107
  }
115
108
  if (!targetBaseUri || nextBaseUri === targetBaseUri) {
116
- if (schemaId && (schemaId === id || schemaId[0] === "#" && schemaId.substring(1) === id)) return schema;
109
+ if (schemaId && (schemaId === id || schemaId.startsWith("#") && schemaId.slice(1) === id)) return schema;
117
110
  if (schema.$anchor === id || schema.$dynamicAnchor === id) return schema;
118
111
  }
119
112
  let result;
@@ -125,7 +118,7 @@ const findId = (schema, id, targetBaseUri, currentBaseUri, maxDepth = 100, _dept
125
118
  const keys = Object.keys(schema);
126
119
  for (let i = keys.length - 1; i >= 0; i--) {
127
120
  const k = keys[i];
128
- if (isInternalKey(k) || NON_SCHEMA_KEYWORDS.includes(k)) continue;
121
+ if (isInternalKey(k) || NON_SCHEMA_KEYWORDS_SET.has(k)) continue;
129
122
  result = findId(schema[k], id, targetBaseUri, nextBaseUri, maxDepth, _depth + 1);
130
123
  if (result) return result;
131
124
  }
@@ -186,11 +179,10 @@ const Errors = {
186
179
  MAX_RECURSION_DEPTH_EXCEEDED: "Maximum recursion depth ({0}) exceeded. If your schema or data is deeply nested and valid, increase the maxRecursionDepth option."
187
180
  };
188
181
  var ValidateError = class extends Error {
189
- name;
182
+ name = "ValidateError";
190
183
  details;
191
184
  constructor(message, details) {
192
185
  super(message);
193
- this.name = "z-schema validation error";
194
186
  this.details = details;
195
187
  }
196
188
  };
@@ -211,49 +203,48 @@ function copyProp(from, to, key, fn) {
211
203
  //#region src/utils/clone.ts
212
204
  const shallowClone = (src) => {
213
205
  if (src == null || typeof src !== "object") return src;
214
- let res;
215
206
  if (Array.isArray(src)) {
216
- res = [];
207
+ const res = [];
217
208
  for (let i = 0; i < src.length; i++) res[i] = src[i];
218
- } else {
219
- res = {};
220
- const keys = Object.keys(src).sort();
221
- for (const key of keys) copyProp(src, res, key);
209
+ return res;
222
210
  }
211
+ const res = {};
212
+ const keys = Object.keys(src).sort();
213
+ for (let i = 0; i < keys.length; i++) copyProp(src, res, keys[i]);
223
214
  return res;
224
215
  };
225
216
  const deepClone = (src, maxDepth = 100) => {
226
217
  let vidx = 0;
227
218
  const visited = /* @__PURE__ */ new Map();
228
219
  const cloned = [];
229
- const cloneDeepInner = (src, _depth) => {
230
- if (typeof src !== "object" || src === null) return src;
220
+ const cloneDeepInner = (node, _depth) => {
221
+ if (typeof node !== "object" || node === null) return node;
231
222
  if (_depth >= maxDepth) throw new Error(`Maximum recursion depth (${maxDepth}) exceeded in deepClone. If your schema or data is deeply nested and valid, increase the maxRecursionDepth option.`);
232
- let res;
233
- const cidx = visited.get(src);
223
+ const cidx = visited.get(node);
234
224
  if (cidx !== void 0) return cloned[cidx];
235
- visited.set(src, vidx++);
236
- if (Array.isArray(src)) {
237
- res = [];
238
- cloned.push(res);
239
- for (let i = 0; i < src.length; i++) res[i] = cloneDeepInner(src[i], _depth + 1);
240
- } else {
241
- res = {};
225
+ visited.set(node, vidx++);
226
+ if (Array.isArray(node)) {
227
+ const res = [];
242
228
  cloned.push(res);
243
- const keys = Object.keys(src).sort();
244
- for (const key of keys) copyProp(src, res, key, (v) => cloneDeepInner(v, _depth + 1));
229
+ for (let i = 0; i < node.length; i++) res[i] = cloneDeepInner(node[i], _depth + 1);
230
+ return res;
245
231
  }
232
+ const res = {};
233
+ cloned.push(res);
234
+ const keys = Object.keys(node).sort();
235
+ for (let i = 0; i < keys.length; i++) copyProp(node, res, keys[i], (v) => cloneDeepInner(v, _depth + 1));
246
236
  return res;
247
237
  };
248
238
  return cloneDeepInner(src, 0);
249
239
  };
250
240
  //#endregion
251
241
  //#region src/utils/json.ts
242
+ const sortedKeys = (obj) => Object.keys(obj).sort();
252
243
  const areEqual = (json1, json2, options, _depth = 0) => {
253
244
  const caseInsensitiveComparison = options?.caseInsensitiveComparison || false;
254
245
  const maxDepth = options?.maxDepth ?? 100;
255
246
  if (json1 === json2) return true;
256
- if (caseInsensitiveComparison === true && typeof json1 === "string" && typeof json2 === "string" && json1.toUpperCase() === json2.toUpperCase()) return true;
247
+ if (caseInsensitiveComparison && typeof json1 === "string" && typeof json2 === "string" && json1.toUpperCase() === json2.toUpperCase()) return true;
257
248
  if (_depth >= maxDepth) throw new Error(`Maximum recursion depth (${maxDepth}) exceeded in areEqual. If your data is deeply nested and valid, increase the maxRecursionDepth option.`);
258
249
  let i, len;
259
250
  if (Array.isArray(json1) && Array.isArray(json2)) {
@@ -264,20 +255,24 @@ const areEqual = (json1, json2, options, _depth = 0) => {
264
255
  }
265
256
  if (isObject(json1) && isObject(json2)) {
266
257
  const keys1 = sortedKeys(json1);
267
- if (!areEqual(keys1, sortedKeys(json2), options, _depth + 1)) return false;
258
+ const keys2 = sortedKeys(json2);
259
+ if (!areEqual(keys1, keys2, options, _depth + 1)) return false;
268
260
  len = keys1.length;
269
261
  for (i = 0; i < len; i++) if (!areEqual(json1[keys1[i]], json2[keys1[i]], options, _depth + 1)) return false;
270
262
  return true;
271
263
  }
272
264
  return false;
273
265
  };
274
- const decodeJSONPointer = (str) => {
275
- return decodeURIComponent(str).replace(/~[0-1]/g, (x) => x === "~1" ? "/" : "~");
276
- };
277
- const sortedKeys = (obj) => Object.keys(obj).sort();
266
+ const decodeJSONPointer = (str) => decodeURIComponent(str).replaceAll(/~[0-1]/g, (x) => x === "~1" ? "/" : "~");
278
267
  const get = (obj, path) => {
279
268
  if (typeof path === "string") path = path.split(".");
280
- return path.reduce((acc, key) => acc && acc[key] !== void 0 ? acc[key] : void 0, obj);
269
+ let acc = obj;
270
+ for (let i = 0; i < path.length; i++) {
271
+ const key = path[i];
272
+ if (acc && acc[key] !== void 0) acc = acc[key];
273
+ else return;
274
+ }
275
+ return acc;
281
276
  };
282
277
  //#endregion
283
278
  //#region src/utils/symbols.ts
@@ -307,8 +302,8 @@ var Report = class Report {
307
302
  if (parentOrOptions instanceof Report) {
308
303
  this.reportOptions = reportOptionsOrValidate || {};
309
304
  this.validateOptions = validateOptions || parentOrOptions.validateOptions;
310
- this.__$recursiveAnchorStack = [...parentOrOptions.__$recursiveAnchorStack];
311
- this.__$dynamicScopeStack = [...parentOrOptions.__$dynamicScopeStack];
305
+ this.__$recursiveAnchorStack = parentOrOptions.__$recursiveAnchorStack.slice();
306
+ this.__$dynamicScopeStack = parentOrOptions.__$dynamicScopeStack.slice();
312
307
  this.__validationResultCache = parentOrOptions.__validationResultCache;
313
308
  } else {
314
309
  this.reportOptions = {};
@@ -391,30 +386,24 @@ var Report = class Report {
391
386
  setTimeout(checkTimeout, ASYNC_TIMEOUT_POLL_MS);
392
387
  }
393
388
  getPath(returnPathAsString) {
394
- let path = [];
395
- if (this.parentReport) path = path.concat(this.parentReport.path);
396
- path = path.concat(this.path);
397
- if (returnPathAsString !== true) return "#/" + path.map(function(segment) {
389
+ const path = this.parentReport ? this.parentReport.path.concat(this.path) : this.path.slice();
390
+ if (returnPathAsString !== true) return `#/${path.map((segment) => {
398
391
  segment = segment.toString();
399
- if (isAbsoluteUri(segment)) return "uri(" + segment + ")";
400
- return segment.replace(/~/g, "~0").replace(/\//g, "~1");
401
- }).join("/");
392
+ if (isAbsoluteUri(segment)) return `uri(${segment})`;
393
+ return segment.replaceAll("~", "~0").replaceAll("/", "~1");
394
+ }).join("/")}`;
402
395
  return path;
403
396
  }
404
397
  getSchemaPath() {
405
- let schemaPath = [];
406
- if (this.parentReport) schemaPath = schemaPath.concat(this.parentReport.schemaPath);
407
- schemaPath = schemaPath.concat(this.schemaPath);
408
- return schemaPath;
398
+ if (this.parentReport) return this.parentReport.schemaPath.concat(this.schemaPath);
399
+ return this.schemaPath.slice();
409
400
  }
410
401
  getSchemaId() {
411
402
  if (!this.rootSchema) return;
412
- let path = [];
413
- if (this.parentReport) path = path.concat(this.parentReport.path);
414
- path = path.concat(this.path);
403
+ const path = this.parentReport ? this.parentReport.path.concat(this.path) : this.path.slice();
415
404
  while (path.length > 0) {
416
405
  const obj = get(this.rootSchema, path);
417
- if (obj && obj.id) return obj.id;
406
+ if (isObject(obj) && typeof obj.id === "string") return obj.id;
418
407
  path.pop();
419
408
  }
420
409
  return this.rootSchema.id;
@@ -437,11 +426,11 @@ var Report = class Report {
437
426
  }
438
427
  addCustomError(errorCode, errorMessage, params, subReports, schema, keyword) {
439
428
  if (typeof this.reportOptions.maxErrors === "number" && this.errors.length >= this.reportOptions.maxErrors) return;
440
- if (!errorMessage) throw new Error("No errorMessage known for code " + errorCode);
441
- params = params || [];
429
+ if (!errorMessage) throw new Error(`No errorMessage known for code ${errorCode}`);
430
+ params ||= [];
442
431
  for (let idx = 0; idx < params.length; idx++) {
443
432
  const param = params[idx] === null || isObject(params[idx]) ? JSON.stringify(params[idx]) : params[idx];
444
- errorMessage = errorMessage.replace("{" + idx + "}", param.toString());
433
+ errorMessage = errorMessage.replace(`{${idx}}`, param.toString());
445
434
  }
446
435
  const err = {
447
436
  code: errorCode,
@@ -450,10 +439,10 @@ var Report = class Report {
450
439
  path: this.getPath(this.options.reportPathAsArray),
451
440
  schemaPath: this.getSchemaPath(),
452
441
  schemaId: this.getSchemaId(),
453
- keyword
442
+ keyword,
443
+ [schemaSymbol]: schema,
444
+ [jsonSymbol]: this.getJson()
454
445
  };
455
- err[schemaSymbol] = schema;
456
- err[jsonSymbol] = this.getJson();
457
446
  if (schema && typeof schema === "string") err.description = schema;
458
447
  else if (schema && typeof schema === "object") {
459
448
  if (schema.title) err.title = schema.title;
@@ -462,7 +451,10 @@ var Report = class Report {
462
451
  if (subReports != null) {
463
452
  if (!Array.isArray(subReports)) subReports = [subReports];
464
453
  err.inner = [];
465
- for (const subReport of subReports) for (const error of subReport.errors) err.inner.push(error);
454
+ for (let si = 0; si < subReports.length; si++) {
455
+ const errs = subReports[si].errors;
456
+ for (let ei = 0; ei < errs.length; ei++) err.inner.push(errs[ei]);
457
+ }
466
458
  if (err.inner.length === 0) err.inner = void 0;
467
459
  }
468
460
  if (Array.isArray(this.validateOptions.excludeErrors) && this.validateOptions.excludeErrors.includes(errorCode)) return;
@@ -512,7 +504,7 @@ const normalizeOptions = (options) => {
512
504
  let normalized;
513
505
  if (typeof options === "object") {
514
506
  let keys = Object.keys(options);
515
- for (const key of keys) if (defaultOptions[key] === void 0) throw new Error("Unexpected option passed to constructor: " + key);
507
+ for (const key of keys) if (defaultOptions[key] === void 0) throw new Error(`Unexpected option passed to constructor: ${key}`);
516
508
  keys = Object.keys(defaultOptions);
517
509
  for (const key of keys) if (options[key] === void 0) options[key] = shallowClone(defaultOptions[key]);
518
510
  normalized = options;
@@ -540,7 +532,7 @@ function getSafeRemotePath(uri) {
540
532
  }
541
533
  const getEffectiveId = (schema) => {
542
534
  let id = getId(schema);
543
- if ((!id || !isAbsoluteUri(id)) && typeof schema.id === "string" && isAbsoluteUri(schema.id)) id = schema.id;
535
+ if ((!id || !isAbsoluteUri(id)) && typeof schema.id === "string" && isAbsoluteUri(schema.id)) ({id} = schema);
544
536
  return id;
545
537
  };
546
538
  /**
@@ -549,9 +541,7 @@ const getEffectiveId = (schema) => {
549
541
  * the instance `validator.setRemoteReference()` (instance cache).
550
542
  */
551
543
  function prepareRemoteSchema(schema, uri, validationOptions, maxCloneDepth) {
552
- let _schema;
553
- if (typeof schema === "string") _schema = JSON.parse(schema);
554
- else _schema = deepClone(schema, maxCloneDepth);
544
+ const _schema = typeof schema === "string" ? JSON.parse(schema) : deepClone(schema, maxCloneDepth);
555
545
  if (!_schema.id) _schema.id = uri;
556
546
  if (validationOptions) _schema.__$validationOptions = normalizeOptions(validationOptions);
557
547
  return _schema;
@@ -559,6 +549,7 @@ function prepareRemoteSchema(schema, uri, validationOptions, maxCloneDepth) {
559
549
  var SchemaCache = class SchemaCache {
560
550
  static global_cache = Object.create(null);
561
551
  cache = Object.create(null);
552
+ validator;
562
553
  constructor(validator) {
563
554
  this.validator = validator;
564
555
  }
@@ -635,7 +626,7 @@ var SchemaCache = class SchemaCache {
635
626
  usesAncestorReport = true;
636
627
  } else {
637
628
  remoteReport = new Report(report);
638
- const noCache = result.id && isAbsoluteUri(result.id) ? false : true;
629
+ const noCache = !(result.id && isAbsoluteUri(result.id));
639
630
  if (this.validator.sc.compileSchema(remoteReport, result, { noCache })) {
640
631
  const savedOptions = this.validator.options;
641
632
  try {
@@ -1688,13 +1679,104 @@ const isValidRfc3339Date = (year, month, day) => {
1688
1679
  };
1689
1680
  //#endregion
1690
1681
  //#region src/utils/hostname.ts
1691
- const IDN_SEPARATOR_REGEX = /[\u3002\uff0e\uff61]/g;
1692
- const IDN_SEPARATOR_TEST_REGEX = /[\u3002\uff0e\uff61]/;
1682
+ const IDN_SEPARATOR_REGEX = /[\u3002\uFF0E\uFF61]/g;
1683
+ const IDN_SEPARATOR_TEST_REGEX = /[\u3002\uFF0E\uFF61]/;
1684
+ const XN_LABEL_REGEX = /^xn--/i;
1685
+ const DISALLOWED_CATEGORY_REGEX = /[\p{P}\p{S}\p{Z}\p{C}]/u;
1686
+ const DISALLOWED_CATEGORY_WHITELIST = /* @__PURE__ */ new Set([
1687
+ "-",
1688
+ "·",
1689
+ "͵",
1690
+ "׳",
1691
+ "״",
1692
+ "・",
1693
+ "۽",
1694
+ "۾",
1695
+ "་",
1696
+ "‌",
1697
+ "‍"
1698
+ ]);
1699
+ const isDisallowedCodePoint = (char) => DISALLOWED_CATEGORY_REGEX.test(char) && !DISALLOWED_CATEGORY_WHITELIST.has(char);
1700
+ const TRANSPARENT_MARK_REGEX = /\p{Mn}/u;
1701
+ const ARABIC_SCRIPT_REGEX = /\p{Script=Arabic}/u;
1702
+ const ARABIC_INDIC_DIGITS_REGEX = /[\u0660-\u0669\u06F0-\u06F9]/;
1703
+ const isArabicJoiningLetter = (char) => char !== void 0 && ARABIC_SCRIPT_REGEX.test(char) && !ARABIC_INDIC_DIGITS_REGEX.test(char);
1704
+ const hasZwnjJoiningContext = (label, idx) => {
1705
+ let before = idx - 1;
1706
+ while (before >= 0 && TRANSPARENT_MARK_REGEX.test(label[before])) before--;
1707
+ let after = idx + 1;
1708
+ while (after < label.length && TRANSPARENT_MARK_REGEX.test(label[after])) after++;
1709
+ return isArabicJoiningLetter(label[before]) && isArabicJoiningLetter(label[after]);
1710
+ };
1711
+ const BIDI_NSM_REGEX = /[\p{Mn}\p{Me}]/u;
1712
+ const BIDI_ARABIC_INDIC_DIGIT_REGEX = /[\u0660-\u0669]/;
1713
+ const BIDI_EXTENDED_ARABIC_INDIC_DIGIT_REGEX = /[\u06F0-\u06F9]/;
1714
+ const BIDI_HEBREW_SCRIPT_REGEX = /\p{Script=Hebrew}/u;
1715
+ const BIDI_AL_SCRIPT_REGEX = /[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}]/u;
1716
+ const BIDI_ASCII_DIGIT_REGEX = /[0-9]/;
1717
+ const BIDI_LETTER_REGEX = /\p{L}/u;
1718
+ const classifyBidi = (char) => {
1719
+ if (BIDI_NSM_REGEX.test(char)) return "NSM";
1720
+ if (BIDI_ARABIC_INDIC_DIGIT_REGEX.test(char)) return "AN";
1721
+ if (BIDI_EXTENDED_ARABIC_INDIC_DIGIT_REGEX.test(char)) return "EN";
1722
+ if (BIDI_HEBREW_SCRIPT_REGEX.test(char)) return "R";
1723
+ if (BIDI_AL_SCRIPT_REGEX.test(char)) return "AL";
1724
+ if (BIDI_ASCII_DIGIT_REGEX.test(char)) return "EN";
1725
+ if (BIDI_LETTER_REGEX.test(char)) return "L";
1726
+ return "ON";
1727
+ };
1728
+ const isLabelBidiTriggering = (label) => {
1729
+ for (const char of label) {
1730
+ const bidiClass = classifyBidi(char);
1731
+ if (bidiClass === "R" || bidiClass === "AL" || bidiClass === "AN") return true;
1732
+ }
1733
+ return false;
1734
+ };
1735
+ const isLabelBidiRuleValid = (label) => {
1736
+ const classes = [];
1737
+ for (const char of label) classes.push(classifyBidi(char));
1738
+ if (classes.length === 0) return false;
1739
+ const first = classes[0];
1740
+ if (first !== "L" && first !== "R" && first !== "AL") return false;
1741
+ let lastIdx = classes.length - 1;
1742
+ while (lastIdx > 0 && classes[lastIdx] === "NSM") lastIdx--;
1743
+ const last = classes[lastIdx];
1744
+ if (first === "R" || first === "AL") {
1745
+ let hasEN = false;
1746
+ let hasAN = false;
1747
+ for (let i = 0; i < classes.length; i++) {
1748
+ const c = classes[i];
1749
+ if (c !== "R" && c !== "AL" && c !== "AN" && c !== "EN" && c !== "NSM" && c !== "ON") return false;
1750
+ if (c === "EN") hasEN = true;
1751
+ else if (c === "AN") hasAN = true;
1752
+ }
1753
+ if (hasEN && hasAN) return false;
1754
+ return last === "R" || last === "AL" || last === "EN" || last === "AN";
1755
+ }
1756
+ for (let i = 0; i < classes.length; i++) {
1757
+ const c = classes[i];
1758
+ if (c !== "L" && c !== "EN" && c !== "NSM" && c !== "ON") return false;
1759
+ }
1760
+ return last === "L" || last === "EN";
1761
+ };
1762
+ const isDomainBidiValid = (unicodeLabels) => {
1763
+ let isBidiDomain = false;
1764
+ for (let i = 0; i < unicodeLabels.length; i++) if (isLabelBidiTriggering(unicodeLabels[i])) {
1765
+ isBidiDomain = true;
1766
+ break;
1767
+ }
1768
+ if (!isBidiDomain) return true;
1769
+ for (let i = 0; i < unicodeLabels.length; i++) if (!isLabelBidiRuleValid(unicodeLabels[i])) return false;
1770
+ return true;
1771
+ };
1693
1772
  const splitHostnameLabels = (hostname) => {
1694
1773
  if (hostname.length === 0 || hostname.length > 255) return null;
1695
1774
  if (hostname.startsWith(".") || hostname.endsWith(".")) return null;
1696
1775
  const labels = hostname.split(".");
1697
- if (labels.some((label) => label.length === 0 || label.length > 63)) return null;
1776
+ for (let i = 0; i < labels.length; i++) {
1777
+ const len = labels[i].length;
1778
+ if (len === 0 || len > 63) return null;
1779
+ }
1698
1780
  return labels;
1699
1781
  };
1700
1782
  const isAsciiHostnameLabel = (label) => /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(label);
@@ -1702,47 +1784,42 @@ const isGreek = (char) => /\p{Script=Greek}/u.test(char);
1702
1784
  const isHebrew = (char) => /\p{Script=Hebrew}/u.test(char);
1703
1785
  const hasCjkKanaOrHan = (input) => /[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u.test(input);
1704
1786
  const toUnicodeLabel = (label) => {
1705
- if (!/^xn--/i.test(label)) return label;
1787
+ if (!XN_LABEL_REGEX.test(label)) return label;
1706
1788
  try {
1707
1789
  return punycode_punycode_js.default.toUnicode(label.toLowerCase());
1708
- } catch (_e) {
1790
+ } catch {
1709
1791
  return null;
1710
1792
  }
1711
1793
  };
1712
1794
  const isValidIdnUnicodeLabel = (label) => {
1713
1795
  if (label.startsWith("-") || label.endsWith("-")) return false;
1714
- if (label.length >= 4 && label[2] === "-" && label[3] === "-" && !/^xn--/i.test(label)) return false;
1796
+ if (label.length >= 4 && label[2] === "-" && label[3] === "-" && !XN_LABEL_REGEX.test(label)) return false;
1715
1797
  if (/^\p{M}/u.test(label)) return false;
1716
- if (/[\u302e\u302f\u0640\u07fa]/u.test(label)) return false;
1798
+ if (/[\u302E\u302F\u0640\u07FA]/u.test(label)) return false;
1717
1799
  for (let idx = 0; idx < label.length; idx++) {
1718
1800
  const char = label[idx];
1719
- if (char === "·") {
1720
- if (idx === 0 || idx === label.length - 1 || label[idx - 1] !== "l" || label[idx + 1] !== "l") return false;
1721
- }
1722
- if (char === "͵") {
1723
- if (idx === label.length - 1 || !isGreek(label[idx + 1])) return false;
1724
- }
1725
- if (char === "׳" || char === "״") {
1726
- if (idx === 0 || !isHebrew(label[idx - 1])) return false;
1727
- }
1728
- if (char === "‍") {
1729
- if (idx === 0 || label[idx - 1] !== "्") return false;
1730
- }
1731
- }
1732
- if (label.includes("・") && !hasCjkKanaOrHan(label.replace(/\u30fb/g, ""))) return false;
1801
+ if (char === "·" && (idx === 0 || idx === label.length - 1 || label[idx - 1] !== "l" || label[idx + 1] !== "l")) return false;
1802
+ if (char === "͵" && (idx === label.length - 1 || !isGreek(label[idx + 1]))) return false;
1803
+ if ((char === "׳" || char === "״") && (idx === 0 || !isHebrew(label[idx - 1]))) return false;
1804
+ if (char === "" && (idx === 0 || label[idx - 1] !== "्")) return false;
1805
+ if (char === "‌" && (idx === 0 || label[idx - 1] !== "्" && !hasZwnjJoiningContext(label, idx))) return false;
1806
+ }
1807
+ for (const char of label) if (isDisallowedCodePoint(char)) return false;
1808
+ if (label.includes("・") && !hasCjkKanaOrHan(label.replaceAll("・", ""))) return false;
1733
1809
  const hasArabicIndic = /[\u0660-\u0669]/.test(label);
1734
- const hasExtendedArabicIndic = /[\u06f0-\u06f9]/.test(label);
1810
+ const hasExtendedArabicIndic = /[\u06F0-\u06F9]/.test(label);
1735
1811
  if (hasArabicIndic && hasExtendedArabicIndic) return false;
1736
1812
  return true;
1737
1813
  };
1738
1814
  const isValidHostname = (hostname) => {
1739
- if (IDN_SEPARATOR_TEST_REGEX.test(hostname) || /[^\x00-\x7F]/.test(hostname)) return false;
1815
+ if (IDN_SEPARATOR_TEST_REGEX.test(hostname) || /[^\u0000-\u007F]/.test(hostname)) return false;
1740
1816
  if (validator_lib_isIP_js.default.default(hostname, 4)) return false;
1741
1817
  const labels = splitHostnameLabels(hostname);
1742
1818
  if (labels === null) return false;
1743
- for (const label of labels) {
1819
+ for (let i = 0; i < labels.length; i++) {
1820
+ const label = labels[i];
1744
1821
  if (!isAsciiHostnameLabel(label)) return false;
1745
- if (/^xn--/i.test(label)) {
1822
+ if (XN_LABEL_REGEX.test(label)) {
1746
1823
  const unicodeLabel = toUnicodeLabel(label);
1747
1824
  if (unicodeLabel === null || !isValidIdnUnicodeLabel(unicodeLabel)) return false;
1748
1825
  }
@@ -1750,13 +1827,28 @@ const isValidHostname = (hostname) => {
1750
1827
  return true;
1751
1828
  };
1752
1829
  const isValidIdnHostname = (hostname) => {
1753
- const labels = splitHostnameLabels(hostname.replace(IDN_SEPARATOR_REGEX, "."));
1830
+ const normalizedHostname = hostname.replace(IDN_SEPARATOR_REGEX, ".");
1831
+ const labels = splitHostnameLabels(normalizedHostname);
1754
1832
  if (labels === null) return false;
1755
- for (const label of labels) {
1833
+ const unicodeLabels = [];
1834
+ let totalLength = labels.length - 1;
1835
+ for (let i = 0; i < labels.length; i++) {
1836
+ const label = labels[i];
1756
1837
  const unicodeLabel = toUnicodeLabel(label);
1757
1838
  if (unicodeLabel === null || !isValidIdnUnicodeLabel(unicodeLabel)) return false;
1839
+ let aLabel;
1840
+ try {
1841
+ aLabel = punycode_punycode_js.default.toASCII(unicodeLabel);
1842
+ } catch {
1843
+ return false;
1844
+ }
1845
+ if (XN_LABEL_REGEX.test(label) && aLabel.toLowerCase() !== label.toLowerCase()) return false;
1846
+ if (aLabel.length > 63) return false;
1847
+ totalLength += aLabel.length;
1848
+ unicodeLabels.push(unicodeLabel);
1758
1849
  }
1759
- return true;
1850
+ if (totalLength > 253) return false;
1851
+ return isDomainBidiValid(unicodeLabels);
1760
1852
  };
1761
1853
  //#endregion
1762
1854
  //#region src/utils/time.ts
@@ -1769,22 +1861,22 @@ const toUtcTime = (hour, minute, offsetSign, offsetHour, offsetMinute) => {
1769
1861
  minute: normalizedUtcTotalMinutes % 60
1770
1862
  };
1771
1863
  };
1772
- const RFC3339_TIME_REGEX = /^([0-9]{2}):([0-9]{2}):([0-9]{2})(\.[0-9]+)?(z|([+-][0-9]{2}:[0-9]{2}))$/i;
1864
+ const RFC3339_TIME_REGEX = /^(?<hour>[0-9]{2}):(?<minute>[0-9]{2}):(?<second>[0-9]{2})(?<fraction>\.[0-9]+)?(?<offset>z|(?<offsetValue>[+-][0-9]{2}:[0-9]{2}))$/i;
1773
1865
  const parseRfc3339Time = (time) => {
1774
1866
  const matches = RFC3339_TIME_REGEX.exec(time);
1775
1867
  if (matches === null) return null;
1776
- const hour = parseInt(matches[1], 10);
1777
- const minute = parseInt(matches[2], 10);
1778
- const second = parseInt(matches[3], 10);
1868
+ const hour = Number.parseInt(matches[1], 10);
1869
+ const minute = Number.parseInt(matches[2], 10);
1870
+ const second = Number.parseInt(matches[3], 10);
1779
1871
  if (hour > 23 || minute > 59 || second > 60) return null;
1780
1872
  let utcHour = hour;
1781
1873
  let utcMinute = minute;
1782
1874
  if (matches[5].toLowerCase() !== "z") {
1783
- const offsetMatches = /^([+-])([0-9]{2}):([0-9]{2})$/.exec(matches[5]);
1875
+ const offsetMatches = /^(?<sign>[+-])(?<hour>[0-9]{2}):(?<minute>[0-9]{2})$/.exec(matches[5]);
1784
1876
  if (offsetMatches === null) return null;
1785
1877
  const offsetSign = offsetMatches[1];
1786
- const offsetHour = parseInt(offsetMatches[2], 10);
1787
- const offsetMinute = parseInt(offsetMatches[3], 10);
1878
+ const offsetHour = Number.parseInt(offsetMatches[2], 10);
1879
+ const offsetMinute = Number.parseInt(offsetMatches[3], 10);
1788
1880
  if (offsetHour > 23 || offsetMinute > 59) return null;
1789
1881
  const utc = toUtcTime(hour, minute, offsetSign, offsetHour, offsetMinute);
1790
1882
  utcHour = utc.hour;
@@ -1803,19 +1895,20 @@ const parseRfc3339Time = (time) => {
1803
1895
  //#region src/format-validators.ts
1804
1896
  const dateValidator = (date) => {
1805
1897
  if (typeof date !== "string") return true;
1806
- const matches = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/.exec(date);
1898
+ const matches = /^(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})$/.exec(date);
1807
1899
  if (matches === null) return false;
1808
- return isValidRfc3339Date(parseInt(matches[1], 10), parseInt(matches[2], 10), parseInt(matches[3], 10));
1900
+ return isValidRfc3339Date(Number.parseInt(matches[1], 10), Number.parseInt(matches[2], 10), Number.parseInt(matches[3], 10));
1809
1901
  };
1810
1902
  const dateTimeValidator = (dateTime) => {
1811
1903
  if (typeof dateTime !== "string") return true;
1812
- const s = dateTime.toLowerCase().split("t");
1813
- if (s.length !== 2) return false;
1814
- const datePart = s[0];
1815
- const timePart = s[1];
1816
- const dateMatches = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/.exec(datePart);
1904
+ let tIdx = dateTime.indexOf("T");
1905
+ if (tIdx === -1) tIdx = dateTime.indexOf("t");
1906
+ if (tIdx === -1) return false;
1907
+ const datePart = dateTime.slice(0, tIdx);
1908
+ const timePart = dateTime.slice(tIdx + 1);
1909
+ const dateMatches = /^(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})$/.exec(datePart);
1817
1910
  if (dateMatches === null) return false;
1818
- if (!isValidRfc3339Date(parseInt(dateMatches[1], 10), parseInt(dateMatches[2], 10), parseInt(dateMatches[3], 10))) return false;
1911
+ if (!isValidRfc3339Date(Number.parseInt(dateMatches[1], 10), Number.parseInt(dateMatches[2], 10), Number.parseInt(dateMatches[3], 10))) return false;
1819
1912
  return parseRfc3339Time(timePart) !== null;
1820
1913
  };
1821
1914
  const emailValidator = (email) => {
@@ -1824,7 +1917,7 @@ const emailValidator = (email) => {
1824
1917
  require_tld: true,
1825
1918
  allow_ip_domain: true
1826
1919
  })) return true;
1827
- const ipv6Literal = /^(.+)@\[IPv6:([^\]]+)\]$/i.exec(email);
1920
+ const ipv6Literal = /^(?<localPart>.+)@\[IPv6:(?<address>[^\]]+)\]$/i.exec(email);
1828
1921
  if (!ipv6Literal) return false;
1829
1922
  const localPart = ipv6Literal[1];
1830
1923
  const addressPart = ipv6Literal[2];
@@ -1844,26 +1937,26 @@ const ipv6Validator = (ipv6) => {
1844
1937
  if (ipv6.includes("%")) return false;
1845
1938
  return validator_lib_isIP_js.default.default(ipv6, 6);
1846
1939
  };
1940
+ const INVALID_REGEX_ESCAPES = /* @__PURE__ */ new Set(["a"]);
1847
1941
  const regexValidator = (input) => {
1848
1942
  if (typeof input !== "string") return true;
1849
- const invalidEscapes = new Set(["a"]);
1850
1943
  for (let idx = 0; idx < input.length; idx++) {
1851
1944
  if (input[idx] !== "\\") continue;
1852
1945
  idx++;
1853
1946
  if (idx >= input.length) return false;
1854
1947
  const escaped = input[idx];
1855
- if (invalidEscapes.has(escaped)) return false;
1948
+ if (INVALID_REGEX_ESCAPES.has(escaped)) return false;
1856
1949
  }
1857
1950
  try {
1858
- RegExp(input);
1951
+ new RegExp(input);
1859
1952
  return true;
1860
- } catch (_e) {
1953
+ } catch {
1861
1954
  return false;
1862
1955
  }
1863
1956
  };
1864
1957
  const durationValidator = (input) => {
1865
1958
  if (typeof input !== "string") return true;
1866
- if (!/^P[\x00-\x7F]*$/.test(input)) return false;
1959
+ if (!/^P[\u0000-\u007F]*$/.test(input)) return false;
1867
1960
  if (!input.startsWith("P")) return false;
1868
1961
  const body = input.slice(1);
1869
1962
  if (body.length === 0) return false;
@@ -1873,7 +1966,7 @@ const durationValidator = (input) => {
1873
1966
  const datePart = parts[0];
1874
1967
  const timePart = parts.length === 2 ? parts[1] : void 0;
1875
1968
  if (datePart.length > 0 && !/^(?:\d+Y(?:\d+M(?:\d+D)?)?|\d+M(?:\d+D)?|\d+D)$/.test(datePart)) return false;
1876
- const hasDateComponent = /\d+[YMD]/.test(datePart);
1969
+ const hasDateComponent = datePart.length > 0;
1877
1970
  let hasTimeComponent = false;
1878
1971
  if (timePart !== void 0) {
1879
1972
  if (timePart.length === 0) return false;
@@ -1888,32 +1981,31 @@ const uuidValidator = (input) => {
1888
1981
  return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(input);
1889
1982
  };
1890
1983
  const strictUriValidator = (uri) => typeof uri !== "string" || validator_lib_isURL_js.default.default(uri);
1984
+ const isHexChar = (c) => c >= 48 && c <= 57 || c >= 65 && c <= 70 || c >= 97 && c <= 102;
1891
1985
  const hasValidPercentEncoding = (str) => {
1892
- for (let i = 0; i < str.length; i++) if (str[i] === "%") {
1893
- if (i + 2 >= str.length || !/[0-9a-fA-F]/.test(str[i + 1]) || !/[0-9a-fA-F]/.test(str[i + 2])) return false;
1894
- }
1986
+ for (let i = 0; i < str.length; i++) if (str[i] === "%" && (i + 2 >= str.length || !isHexChar(str.charCodeAt(i + 1)) || !isHexChar(str.charCodeAt(i + 2)))) return false;
1895
1987
  return true;
1896
1988
  };
1897
- const uriValidator = function(uri) {
1989
+ const uriValidator = (uri) => {
1898
1990
  if (typeof uri !== "string") return true;
1899
- if (/[^\x00-\x7F]/.test(uri)) return false;
1991
+ if (/[^\u0000-\u007F]/.test(uri)) return false;
1900
1992
  if (!hasValidPercentEncoding(uri)) return false;
1901
- const match = uri.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):\/\/([^/?#]*)/);
1993
+ const match = /^(?<scheme>[a-zA-Z][a-zA-Z0-9+.-]*):\/\/(?<authority>[^/?#]*)/.exec(uri);
1902
1994
  if (match) {
1903
1995
  const authority = match[2];
1904
1996
  const atIndex = authority.indexOf("@");
1905
1997
  if (atIndex > 0) {
1906
- const userinfo = authority.substring(0, atIndex);
1998
+ const userinfo = authority.slice(0, atIndex);
1907
1999
  if (userinfo.includes("[") || userinfo.includes("]")) return false;
1908
2000
  }
1909
- let hostPort = atIndex >= 0 ? authority.substring(atIndex + 1) : authority;
2001
+ let hostPort = atIndex === -1 ? authority : authority.slice(atIndex + 1);
1910
2002
  if (hostPort.startsWith("[")) {
1911
2003
  const bracketEnd = hostPort.indexOf("]");
1912
- if (bracketEnd >= 0) hostPort = hostPort.substring(bracketEnd + 1);
2004
+ if (bracketEnd !== -1) hostPort = hostPort.slice(bracketEnd + 1);
1913
2005
  }
1914
2006
  const colonIndex = hostPort.lastIndexOf(":");
1915
- if (colonIndex >= 0) {
1916
- const port = hostPort.substring(colonIndex + 1);
2007
+ if (colonIndex !== -1) {
2008
+ const port = hostPort.slice(colonIndex + 1);
1917
2009
  if (port.length > 0 && !/^\d+$/.test(port)) return false;
1918
2010
  }
1919
2011
  }
@@ -1921,12 +2013,12 @@ const uriValidator = function(uri) {
1921
2013
  };
1922
2014
  const uriReferenceValidator = (uri) => {
1923
2015
  if (typeof uri !== "string") return true;
1924
- if (/[^\x00-\x7F]/.test(uri)) return false;
1925
- return /^([a-zA-Z][a-zA-Z0-9+.-]*:)?[^"\\<>^{}^`| ]*$/.test(uri);
2016
+ if (/[^\u0000-\u007F]/.test(uri)) return false;
2017
+ return /^(?:[a-zA-Z][a-zA-Z0-9+.-]*:)?[^"\\<>^{}^`| ]*$/.test(uri);
1926
2018
  };
1927
2019
  const uriTemplateValidator = (uri) => {
1928
2020
  if (typeof uri !== "string") return true;
1929
- if (!/^([a-zA-Z][a-zA-Z0-9+.-]*:)?[^"\\<>^`| ]*$/.test(uri)) return false;
2021
+ if (!/^(?:[a-zA-Z][a-zA-Z0-9+.-]*:)?[^"\\<>^`| ]*$/.test(uri)) return false;
1930
2022
  let inExpression = false;
1931
2023
  for (let idx = 0; idx < uri.length; idx++) {
1932
2024
  const ch = uri[idx];
@@ -1952,29 +2044,39 @@ const jsonPointerValidator = (pointer) => {
1952
2044
  if (typeof pointer !== "string") return true;
1953
2045
  if (pointer === "") return true;
1954
2046
  if (!/^(?:\/[^/]*)+$/.test(pointer)) return false;
1955
- const tokens = pointer.split("/").slice(1);
1956
- for (const token of tokens) if (!hasValidTildeEscapes(token)) return false;
2047
+ const tokens = pointer.split("/");
2048
+ for (let i = 1; i < tokens.length; i++) if (!hasValidTildeEscapes(tokens[i])) return false;
1957
2049
  return true;
1958
2050
  };
1959
2051
  const relativeJsonPointerValidator = (pointer) => {
1960
2052
  if (typeof pointer !== "string") return true;
1961
- const match = pointer.match(/^(0|[1-9]\d*)(.*)$/);
2053
+ const match = /^(?<int>0|[1-9]\d*)(?<suffix>.*)$/.exec(pointer);
1962
2054
  if (!match) return false;
1963
2055
  const suffix = match[2];
1964
2056
  if (suffix === "" || suffix === "#") return true;
1965
2057
  if (!suffix.startsWith("/")) return false;
1966
2058
  if (!/^(?:\/[^/]*)+$/.test(suffix)) return false;
1967
- const tokens = suffix.split("/").slice(1);
1968
- for (const token of tokens) if (!hasValidTildeEscapes(token)) return false;
2059
+ const tokens = suffix.split("/");
2060
+ for (let i = 1; i < tokens.length; i++) if (!hasValidTildeEscapes(tokens[i])) return false;
1969
2061
  return true;
1970
2062
  };
1971
2063
  const timeValidator = (time) => {
1972
2064
  if (typeof time !== "string") return true;
1973
2065
  return parseRfc3339Time(time) !== null;
1974
2066
  };
2067
+ const LONE_SURROGATE_REGEX = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]/;
2068
+ const QUOTED_LOCAL_PART_REGEX = /^"(?:[^"\\]|\\.)*"$/u;
2069
+ const UNQUOTED_LOCAL_PART_REGEX = /^[^\s@]+$/u;
2070
+ const isValidIdnEmailLocalPart = (localPart) => {
2071
+ if (localPart.length === 0 || LONE_SURROGATE_REGEX.test(localPart)) return false;
2072
+ if (localPart.length >= 2 && localPart.startsWith("\"") && localPart.endsWith("\"")) return QUOTED_LOCAL_PART_REGEX.test(localPart);
2073
+ return UNQUOTED_LOCAL_PART_REGEX.test(localPart);
2074
+ };
1975
2075
  const idnEmailValidator = (email) => {
1976
2076
  if (typeof email !== "string") return true;
1977
- return /^[^\s@]+@[^\s@]+$/.test(email);
2077
+ const atIdx = email.lastIndexOf("@");
2078
+ if (atIdx <= 0 || atIdx === email.length - 1) return false;
2079
+ return isValidIdnEmailLocalPart(email.slice(0, atIdx)) && isValidIdnHostname(email.slice(atIdx + 1));
1978
2080
  };
1979
2081
  const idnHostnameValidator = (hostname) => {
1980
2082
  if (typeof hostname !== "string") return true;
@@ -1986,13 +2088,13 @@ const iriValidator = (iri) => {
1986
2088
  try {
1987
2089
  new URL(iri);
1988
2090
  return true;
1989
- } catch (_e) {
2091
+ } catch {
1990
2092
  return false;
1991
2093
  }
1992
2094
  };
1993
2095
  const iriReferenceValidator = (iriReference) => {
1994
2096
  if (typeof iriReference !== "string") return true;
1995
- return /^([a-zA-Z][a-zA-Z0-9+.-]*:)?[^"\\<>^{}^`| ]*$/u.test(iriReference);
2097
+ return /^(?:[a-zA-Z][a-zA-Z0-9+.-]*:)?[^"\\<>^{}^`| ]*$/u.test(iriReference);
1996
2098
  };
1997
2099
  const inbuiltValidators = {
1998
2100
  date: dateValidator,
@@ -2023,9 +2125,16 @@ function getFormatValidators(options) {
2023
2125
  ...inbuiltValidators,
2024
2126
  ...options?.strictUris ? { uri: strictUriValidator } : {},
2025
2127
  ...customValidators,
2026
- ...options?.customFormats || {}
2128
+ ...options?.customFormats
2027
2129
  };
2028
2130
  }
2131
+ function resolveFormatValidator(name, options) {
2132
+ const custom = options?.customFormats;
2133
+ if (custom && Object.hasOwn(custom, name)) return custom[name];
2134
+ if (Object.hasOwn(customValidators, name)) return customValidators[name];
2135
+ if (options?.strictUris && name === "uri") return strictUriValidator;
2136
+ return inbuiltValidators[name];
2137
+ }
2029
2138
  function registerFormat(name, validatorFunction) {
2030
2139
  customValidators[name] = validatorFunction;
2031
2140
  }
@@ -2074,12 +2183,12 @@ function compileSchemaRegex(pattern) {
2074
2183
  ok: true,
2075
2184
  value: new RegExp(pattern, "u")
2076
2185
  };
2077
- } catch (e) {
2186
+ } catch (error) {
2078
2187
  return {
2079
2188
  ok: false,
2080
2189
  error: {
2081
2190
  pattern,
2082
- message: e && e.message ? e.message : "Invalid regular expression"
2191
+ message: error instanceof Error ? error.message : "Invalid regular expression"
2083
2192
  }
2084
2193
  };
2085
2194
  }
@@ -2088,12 +2197,12 @@ function compileSchemaRegex(pattern) {
2088
2197
  ok: true,
2089
2198
  value: new RegExp(pattern)
2090
2199
  };
2091
- } catch (e) {
2200
+ } catch (error) {
2092
2201
  return {
2093
2202
  ok: false,
2094
2203
  error: {
2095
2204
  pattern,
2096
- message: e && e.message ? e.message : "Invalid regular expression"
2205
+ message: error instanceof Error ? error.message : "Invalid regular expression"
2097
2206
  }
2098
2207
  };
2099
2208
  }
@@ -2122,7 +2231,7 @@ const isUniqueArray = (arr, indexes, maxDepth) => {
2122
2231
  const seen = /* @__PURE__ */ new Set();
2123
2232
  for (let i = 0; i < l; i++) {
2124
2233
  const v = arr[i];
2125
- const key = typeof v + ":" + String(v);
2234
+ const key = `${typeof v}:${String(v)}`;
2126
2235
  if (seen.has(key)) {
2127
2236
  if (indexes) for (let j = 0; j < i; j++) {
2128
2237
  const prev = arr[j];
@@ -2137,7 +2246,8 @@ const isUniqueArray = (arr, indexes, maxDepth) => {
2137
2246
  }
2138
2247
  return true;
2139
2248
  }
2140
- for (let i = 0; i < l; i++) for (let j = i + 1; j < l; j++) if (areEqual(arr[i], arr[j], { maxDepth })) {
2249
+ const eqOpts = { maxDepth };
2250
+ for (let i = 0; i < l; i++) for (let j = i + 1; j < l; j++) if (areEqual(arr[i], arr[j], eqOpts)) {
2141
2251
  if (indexes) indexes.push(i, j);
2142
2252
  return false;
2143
2253
  }
@@ -2152,11 +2262,7 @@ const difference = (bigSet, subSet) => {
2152
2262
  };
2153
2263
  //#endregion
2154
2264
  //#region src/validation/shared.ts
2155
- const shouldSkipValidate = function(options, errors) {
2156
- return options && Array.isArray(options.includeErrors) && options.includeErrors.length > 0 && !errors.some(function(err) {
2157
- return options.includeErrors.includes(err);
2158
- });
2159
- };
2265
+ const shouldSkipValidate = (options, errors) => options && Array.isArray(options.includeErrors) && options.includeErrors.length > 0 && !errors.some((err) => options.includeErrors.includes(err));
2160
2266
  const supportsDependentKeywords = (schema, version) => {
2161
2267
  if (typeof schema.$schema === "string") return !/draft-04|draft-06|draft-07/.test(schema.$schema);
2162
2268
  return !(version === "draft-04" || version === "draft-06" || version === "draft-07");
@@ -2165,7 +2271,7 @@ const VOCAB_VALIDATION_2019_09 = "https://json-schema.org/draft/2019-09/vocab/va
2165
2271
  const VOCAB_VALIDATION_2020_12 = "https://json-schema.org/draft/2020-12/vocab/validation";
2166
2272
  const VOCAB_FORMAT_2019_09 = "https://json-schema.org/draft/2019-09/vocab/format";
2167
2273
  const VOCAB_FORMAT_ASSERTION_2020_12 = "https://json-schema.org/draft/2020-12/vocab/format-assertion";
2168
- const VALIDATION_VOCAB_KEYWORDS = new Set([
2274
+ const VALIDATION_VOCAB_KEYWORDS = /* @__PURE__ */ new Set([
2169
2275
  "type",
2170
2276
  "multipleOf",
2171
2277
  "maximum",
@@ -2196,7 +2302,9 @@ const isValidationVocabularyEnabled = (schema, report, version) => {
2196
2302
  const metaSchema = currentSchemaMeta || rootSchemaMeta;
2197
2303
  if (!metaSchema || typeof metaSchema !== "object" || !isObject(metaSchema.$vocabulary)) return true;
2198
2304
  const vocabulary = metaSchema.$vocabulary;
2199
- if (Object.hasOwn(vocabulary, VOCAB_VALIDATION_2019_09) || Object.hasOwn(vocabulary, VOCAB_VALIDATION_2020_12)) return vocabulary[VOCAB_VALIDATION_2019_09] === true || vocabulary[VOCAB_VALIDATION_2020_12] === true;
2305
+ const has2019 = Object.hasOwn(vocabulary, VOCAB_VALIDATION_2019_09);
2306
+ const has2020 = Object.hasOwn(vocabulary, VOCAB_VALIDATION_2020_12);
2307
+ if (has2019 || has2020) return vocabulary[VOCAB_VALIDATION_2019_09] || vocabulary[VOCAB_VALIDATION_2020_12];
2200
2308
  return false;
2201
2309
  };
2202
2310
  /**
@@ -2212,8 +2320,8 @@ const isFormatAssertionVocabEnabled = (schema, report, version) => {
2212
2320
  const metaSchema = currentSchemaMeta || rootSchemaMeta;
2213
2321
  if (!metaSchema || typeof metaSchema !== "object" || !isObject(metaSchema.$vocabulary)) return false;
2214
2322
  const vocabulary = metaSchema.$vocabulary;
2215
- if (Object.hasOwn(vocabulary, VOCAB_FORMAT_ASSERTION_2020_12)) return vocabulary[VOCAB_FORMAT_ASSERTION_2020_12] === true;
2216
- if (Object.hasOwn(vocabulary, VOCAB_FORMAT_2019_09)) return vocabulary[VOCAB_FORMAT_2019_09] === true;
2323
+ if (Object.hasOwn(vocabulary, VOCAB_FORMAT_ASSERTION_2020_12)) return vocabulary[VOCAB_FORMAT_ASSERTION_2020_12];
2324
+ if (Object.hasOwn(vocabulary, VOCAB_FORMAT_2019_09)) return vocabulary[VOCAB_FORMAT_2019_09];
2217
2325
  return false;
2218
2326
  };
2219
2327
  function cacheValidationResult(report, schema, json, passed) {
@@ -2237,9 +2345,14 @@ function getCachedValidationResult(report, schema, json) {
2237
2345
  */
2238
2346
  function deferOrRunSync(report, subReports, decisionFn) {
2239
2347
  const asyncTasksBefore = report.asyncTasks.length;
2240
- for (const subReport of subReports) report.asyncTasks.push(...subReport.asyncTasks);
2348
+ for (let i = 0; i < subReports.length; i++) {
2349
+ const tasks = subReports[i].asyncTasks;
2350
+ for (let j = 0; j < tasks.length; j++) report.asyncTasks.push(tasks[j]);
2351
+ }
2241
2352
  if (report.asyncTasks.length > asyncTasksBefore) report.addAsyncTaskWithPath((callback) => {
2242
- setTimeout(() => callback(null), 0);
2353
+ setTimeout(() => {
2354
+ callback(null);
2355
+ }, 0);
2243
2356
  }, [], () => {
2244
2357
  decisionFn();
2245
2358
  });
@@ -2247,35 +2360,33 @@ function deferOrRunSync(report, subReports, decisionFn) {
2247
2360
  }
2248
2361
  //#endregion
2249
2362
  //#region src/validation/array.ts
2250
- function additionalItemsValidator(report, schema, json) {
2251
- if (shouldSkipValidate(this.validateOptions, ["ARRAY_ADDITIONAL_ITEMS"])) return;
2363
+ function additionalItemsValidator(ctx, report, schema, json) {
2364
+ if (shouldSkipValidate(ctx.validateOptions, ["ARRAY_ADDITIONAL_ITEMS"])) return;
2252
2365
  if (!Array.isArray(json)) return;
2253
- if (schema.additionalItems === false && Array.isArray(schema.items)) {
2254
- if (json.length > schema.items.length) report.addError("ARRAY_ADDITIONAL_ITEMS", void 0, void 0, schema, "additionalItems");
2255
- }
2366
+ if (schema.additionalItems === false && Array.isArray(schema.items) && json.length > schema.items.length) report.addError("ARRAY_ADDITIONAL_ITEMS", void 0, void 0, schema, "additionalItems");
2256
2367
  }
2257
2368
  function itemsValidator() {}
2258
2369
  function prefixItemsValidator() {}
2259
- function maxItemsValidator(report, schema, json) {
2260
- if (shouldSkipValidate(this.validateOptions, ["ARRAY_LENGTH_LONG"])) return;
2370
+ function maxItemsValidator(ctx, report, schema, json) {
2371
+ if (shouldSkipValidate(ctx.validateOptions, ["ARRAY_LENGTH_LONG"])) return;
2261
2372
  if (!Array.isArray(json)) return;
2262
2373
  if (json.length > schema.maxItems) report.addError("ARRAY_LENGTH_LONG", [json.length, schema.maxItems], void 0, schema, "maxItems");
2263
2374
  }
2264
- function minItemsValidator(report, schema, json) {
2265
- if (shouldSkipValidate(this.validateOptions, ["ARRAY_LENGTH_SHORT"])) return;
2375
+ function minItemsValidator(ctx, report, schema, json) {
2376
+ if (shouldSkipValidate(ctx.validateOptions, ["ARRAY_LENGTH_SHORT"])) return;
2266
2377
  if (!Array.isArray(json)) return;
2267
2378
  if (json.length < schema.minItems) report.addError("ARRAY_LENGTH_SHORT", [json.length, schema.minItems], void 0, schema, "minItems");
2268
2379
  }
2269
- function uniqueItemsValidator(report, schema, json) {
2270
- if (shouldSkipValidate(this.validateOptions, ["ARRAY_UNIQUE"])) return;
2380
+ function uniqueItemsValidator(ctx, report, schema, json) {
2381
+ if (shouldSkipValidate(ctx.validateOptions, ["ARRAY_UNIQUE"])) return;
2271
2382
  if (!Array.isArray(json)) return;
2272
2383
  if (schema.uniqueItems === true) {
2273
2384
  const matches = [];
2274
- if (isUniqueArray(json, matches, this.options.maxRecursionDepth) === false) report.addError("ARRAY_UNIQUE", matches, void 0, schema, "uniqueItems");
2385
+ if (!isUniqueArray(json, matches, ctx.options.maxRecursionDepth)) report.addError("ARRAY_UNIQUE", matches, void 0, schema, "uniqueItems");
2275
2386
  }
2276
2387
  }
2277
- function containsValidator(report, schema, json) {
2278
- if (shouldSkipValidate(this.validateOptions, ["CONTAINS"])) return;
2388
+ function containsValidator(ctx, report, schema, json) {
2389
+ if (shouldSkipValidate(ctx.validateOptions, ["CONTAINS"])) return;
2279
2390
  if (!Array.isArray(json)) return;
2280
2391
  const containsSchema = schema.contains;
2281
2392
  if (containsSchema === void 0) return;
@@ -2284,16 +2395,16 @@ function containsValidator(report, schema, json) {
2284
2395
  for (let idx = 0; idx < json.length; idx++) {
2285
2396
  const subReport = new Report_(report);
2286
2397
  subReports.push(subReport);
2287
- this._jsonValidate(subReport, containsSchema, json[idx]);
2398
+ ctx._jsonValidate(subReport, containsSchema, json[idx]);
2288
2399
  cacheValidationResult(report, containsSchema, json[idx], subReport.errors.length === 0);
2289
2400
  }
2290
2401
  const addContainsErrorIfNeeded = () => {
2291
2402
  let matchingItems = 0;
2292
- for (const subReport of subReports) if (subReport.errors.length === 0) matchingItems += 1;
2293
- const supportsContainsBounds = this.options.version === "draft2019-09" || this.options.version === "draft2020-12";
2403
+ for (let i = 0; i < subReports.length; i++) if (subReports[i].errors.length === 0) matchingItems += 1;
2404
+ const supportsContainsBounds = ctx.options.version === "draft2019-09" || ctx.options.version === "draft2020-12";
2294
2405
  const minContains = supportsContainsBounds && typeof schema.minContains === "number" ? schema.minContains ?? 1 : 1;
2295
2406
  const maxContains = supportsContainsBounds && typeof schema.maxContains === "number" ? schema.maxContains : void 0;
2296
- if (!(matchingItems >= minContains) || !(maxContains === void 0 || matchingItems <= maxContains)) report.addError("CONTAINS", void 0, subReports, schema, void 0);
2407
+ if (!(matchingItems >= minContains) || !(maxContains === void 0 || matchingItems <= maxContains)) report.addError("CONTAINS", void 0, subReports, schema);
2297
2408
  };
2298
2409
  deferOrRunSync(report, subReports, addContainsErrorIfNeeded);
2299
2410
  }
@@ -2301,18 +2412,18 @@ function maxContainsValidator() {}
2301
2412
  function minContainsValidator() {}
2302
2413
  //#endregion
2303
2414
  //#region src/validation/combinators.ts
2304
- function allOfValidator(report, schema, json) {
2415
+ function allOfValidator(ctx, report, schema, json) {
2305
2416
  for (let i = 0; i < schema.allOf.length; i++) {
2306
- const validateResult = this._jsonValidate(report, schema.allOf[i], json);
2307
- if (this.options.breakOnFirstError && validateResult === false) break;
2417
+ const validateResult = ctx._jsonValidate(report, schema.allOf[i], json);
2418
+ if (ctx.options.breakOnFirstError && !validateResult) break;
2308
2419
  }
2309
2420
  }
2310
- function anyOfValidator(report, schema, json) {
2421
+ function anyOfValidator(ctx, report, schema, json) {
2311
2422
  const subReports = [];
2312
2423
  for (let i = 0; i < schema.anyOf.length; i++) {
2313
2424
  const subReport = new Report(report);
2314
2425
  subReports.push(subReport);
2315
- this._jsonValidate(subReport, schema.anyOf[i], json);
2426
+ ctx._jsonValidate(subReport, schema.anyOf[i], json);
2316
2427
  cacheValidationResult(report, schema.anyOf[i], json, subReport.errors.length === 0);
2317
2428
  }
2318
2429
  deferOrRunSync(report, subReports, () => {
@@ -2321,15 +2432,15 @@ function anyOfValidator(report, schema, json) {
2321
2432
  passed = true;
2322
2433
  break;
2323
2434
  }
2324
- if (passed === false) report.addError("ANY_OF_MISSING", void 0, subReports, schema, "anyOf");
2435
+ if (!passed) report.addError("ANY_OF_MISSING", void 0, subReports, schema, "anyOf");
2325
2436
  });
2326
2437
  }
2327
- function oneOfValidator(report, schema, json) {
2438
+ function oneOfValidator(ctx, report, schema, json) {
2328
2439
  const subReports = [];
2329
2440
  for (let i = 0; i < schema.oneOf.length; i++) {
2330
2441
  const subReport = new Report(report);
2331
2442
  subReports.push(subReport);
2332
- this._jsonValidate(subReport, schema.oneOf[i], json);
2443
+ ctx._jsonValidate(subReport, schema.oneOf[i], json);
2333
2444
  cacheValidationResult(report, schema.oneOf[i], json, subReport.errors.length === 0);
2334
2445
  }
2335
2446
  deferOrRunSync(report, subReports, () => {
@@ -2339,77 +2450,77 @@ function oneOfValidator(report, schema, json) {
2339
2450
  else if (passes > 1) report.addError("ONE_OF_MULTIPLE", void 0, void 0, schema, "oneOf");
2340
2451
  });
2341
2452
  }
2342
- function notValidator(report, schema, json) {
2453
+ function notValidator(ctx, report, schema, json) {
2343
2454
  const subReport = new Report(report);
2344
- if (this._jsonValidate(subReport, schema.not, json) === true) report.addError("NOT_PASSED", void 0, void 0, schema, "not");
2455
+ if (ctx._jsonValidate(subReport, schema.not, json)) report.addError("NOT_PASSED", void 0, void 0, schema, "not");
2345
2456
  }
2346
- function ifValidator(report, schema, json) {
2347
- if (this.options.version === "draft-04" || this.options.version === "draft-06") return;
2457
+ function ifValidator(ctx, report, schema, json) {
2458
+ if (ctx.options.version === "draft-04" || ctx.options.version === "draft-06") return;
2348
2459
  const conditionSchema = schema.if;
2349
2460
  const thenSchema = schema.then;
2350
2461
  const elseSchema = schema.else;
2351
2462
  if (conditionSchema === void 0 || thenSchema === void 0 && elseSchema === void 0) return;
2352
2463
  const conditionReport = new Report(report);
2353
- this._jsonValidate(conditionReport, conditionSchema, json);
2464
+ ctx._jsonValidate(conditionReport, conditionSchema, json);
2354
2465
  cacheValidationResult(report, conditionSchema, json, conditionReport.errors.length === 0);
2355
2466
  const branchSchema = conditionReport.errors.length === 0 ? thenSchema : elseSchema;
2356
2467
  if (branchSchema === void 0) return;
2357
- this._jsonValidate(report, branchSchema, json);
2468
+ ctx._jsonValidate(report, branchSchema, json);
2358
2469
  }
2359
2470
  function thenValidator() {}
2360
2471
  function elseValidator() {}
2361
2472
  //#endregion
2362
2473
  //#region src/validation/numeric.ts
2363
- function multipleOfValidator(report, schema, json) {
2364
- if (shouldSkipValidate(this.validateOptions, ["MULTIPLE_OF"])) return;
2474
+ function multipleOfValidator(ctx, report, schema, json) {
2475
+ if (shouldSkipValidate(ctx.validateOptions, ["MULTIPLE_OF"])) return;
2365
2476
  if (typeof json !== "number") return;
2366
2477
  const result = json / schema.multipleOf;
2367
2478
  if (!Number.isFinite(result) || Math.abs(result - Math.round(result)) >= 1e-10) report.addError("MULTIPLE_OF", [json, schema.multipleOf], void 0, schema, "multipleOf");
2368
2479
  }
2369
- function maximumValidator(report, schema, json) {
2370
- if (shouldSkipValidate(this.validateOptions, ["MAXIMUM", "MAXIMUM_EXCLUSIVE"])) return;
2480
+ function maximumValidator(ctx, report, schema, json) {
2481
+ if (shouldSkipValidate(ctx.validateOptions, ["MAXIMUM", "MAXIMUM_EXCLUSIVE"])) return;
2371
2482
  if (typeof json !== "number") return;
2372
2483
  if (schema.exclusiveMaximum !== true) {
2373
2484
  if (json > schema.maximum) report.addError("MAXIMUM", [json, schema.maximum], void 0, schema, "maximum");
2374
2485
  } else if (json >= schema.maximum) report.addError("MAXIMUM_EXCLUSIVE", [json, schema.maximum], void 0, schema, "maximum");
2375
2486
  }
2376
- function exclusiveMaximumValidator(report, schema, json) {
2487
+ function exclusiveMaximumValidator(ctx, report, schema, json) {
2377
2488
  if (typeof schema.exclusiveMaximum === "number") {
2378
- if (shouldSkipValidate(this.validateOptions, ["MAXIMUM_EXCLUSIVE"])) return;
2489
+ if (shouldSkipValidate(ctx.validateOptions, ["MAXIMUM_EXCLUSIVE"])) return;
2379
2490
  if (typeof json !== "number") return;
2380
2491
  if (json >= schema.exclusiveMaximum) report.addError("MAXIMUM_EXCLUSIVE", [json, schema.exclusiveMaximum], void 0, schema, "exclusiveMaximum");
2381
2492
  }
2382
2493
  }
2383
- function minimumValidator(report, schema, json) {
2384
- if (shouldSkipValidate(this.validateOptions, ["MINIMUM", "MINIMUM_EXCLUSIVE"])) return;
2494
+ function minimumValidator(ctx, report, schema, json) {
2495
+ if (shouldSkipValidate(ctx.validateOptions, ["MINIMUM", "MINIMUM_EXCLUSIVE"])) return;
2385
2496
  if (typeof json !== "number") return;
2386
2497
  if (schema.exclusiveMinimum !== true) {
2387
2498
  if (json < schema.minimum) report.addError("MINIMUM", [json, schema.minimum], void 0, schema, "minimum");
2388
2499
  } else if (json <= schema.minimum) report.addError("MINIMUM_EXCLUSIVE", [json, schema.minimum], void 0, schema, "minimum");
2389
2500
  }
2390
- function exclusiveMinimumValidator(report, schema, json) {
2501
+ function exclusiveMinimumValidator(ctx, report, schema, json) {
2391
2502
  if (typeof schema.exclusiveMinimum === "number") {
2392
- if (shouldSkipValidate(this.validateOptions, ["MINIMUM_EXCLUSIVE"])) return;
2503
+ if (shouldSkipValidate(ctx.validateOptions, ["MINIMUM_EXCLUSIVE"])) return;
2393
2504
  if (typeof json !== "number") return;
2394
2505
  if (json <= schema.exclusiveMinimum) report.addError("MINIMUM_EXCLUSIVE", [json, schema.exclusiveMinimum], void 0, schema, "exclusiveMinimum");
2395
2506
  }
2396
2507
  }
2397
2508
  //#endregion
2398
2509
  //#region src/validation/object.ts
2399
- function maxPropertiesValidator(report, schema, json) {
2400
- if (shouldSkipValidate(this.validateOptions, ["OBJECT_PROPERTIES_MAXIMUM"])) return;
2510
+ function maxPropertiesValidator(ctx, report, schema, json) {
2511
+ if (shouldSkipValidate(ctx.validateOptions, ["OBJECT_PROPERTIES_MAXIMUM"])) return;
2401
2512
  if (!isObject(json)) return;
2402
2513
  const keysCount = Object.keys(json).length;
2403
2514
  if (keysCount > schema.maxProperties) report.addError("OBJECT_PROPERTIES_MAXIMUM", [keysCount, schema.maxProperties], void 0, schema, "maxProperties");
2404
2515
  }
2405
- function minPropertiesValidator(report, schema, json) {
2406
- if (shouldSkipValidate(this.validateOptions, ["OBJECT_PROPERTIES_MINIMUM"])) return;
2516
+ function minPropertiesValidator(ctx, report, schema, json) {
2517
+ if (shouldSkipValidate(ctx.validateOptions, ["OBJECT_PROPERTIES_MINIMUM"])) return;
2407
2518
  if (!isObject(json)) return;
2408
2519
  const keysCount = Object.keys(json).length;
2409
2520
  if (keysCount < schema.minProperties) report.addError("OBJECT_PROPERTIES_MINIMUM", [keysCount, schema.minProperties], void 0, schema, "minProperties");
2410
2521
  }
2411
- function requiredValidator(report, schema, json) {
2412
- if (shouldSkipValidate(this.validateOptions, ["OBJECT_MISSING_REQUIRED_PROPERTY"])) return;
2522
+ function requiredValidator(ctx, report, schema, json) {
2523
+ if (shouldSkipValidate(ctx.validateOptions, ["OBJECT_MISSING_REQUIRED_PROPERTY"])) return;
2413
2524
  if (!isObject(json)) return;
2414
2525
  const idx = schema.required.length;
2415
2526
  for (let i = 0; i < idx; i++) {
@@ -2417,30 +2528,31 @@ function requiredValidator(report, schema, json) {
2417
2528
  if (!Object.hasOwn(json, requiredPropertyName)) report.addError("OBJECT_MISSING_REQUIRED_PROPERTY", [requiredPropertyName], void 0, schema, "required");
2418
2529
  }
2419
2530
  }
2420
- function additionalPropertiesValidator(report, schema, json) {
2421
- if (schema.properties === void 0 && schema.patternProperties === void 0) return propertiesValidator.call(this, report, schema, json);
2531
+ function additionalPropertiesValidator(ctx, report, schema, json) {
2532
+ if (schema.properties === void 0 && schema.patternProperties === void 0) propertiesValidator(ctx, report, schema, json);
2422
2533
  }
2423
- function patternPropertiesValidator(report, schema, json) {
2424
- if (schema.properties === void 0) return propertiesValidator.call(this, report, schema, json);
2534
+ function patternPropertiesValidator(ctx, report, schema, json) {
2535
+ if (schema.properties === void 0) propertiesValidator(ctx, report, schema, json);
2425
2536
  }
2426
- function propertiesValidator(report, schema, json) {
2427
- if (shouldSkipValidate(this.validateOptions, ["OBJECT_ADDITIONAL_PROPERTIES"])) return;
2537
+ function propertiesValidator(ctx, report, schema, json) {
2538
+ if (shouldSkipValidate(ctx.validateOptions, ["OBJECT_ADDITIONAL_PROPERTIES"])) return;
2428
2539
  if (!isObject(json)) return;
2429
- const properties = schema.properties !== void 0 ? schema.properties : {};
2430
- const patternProperties = schema.patternProperties !== void 0 ? schema.patternProperties : {};
2540
+ const properties = schema.properties === void 0 ? {} : schema.properties;
2541
+ const patternProperties = schema.patternProperties === void 0 ? {} : schema.patternProperties;
2431
2542
  if (schema.additionalProperties === false) {
2432
2543
  let s = Object.keys(json);
2433
2544
  const p = Object.keys(properties);
2434
2545
  const pp = Object.keys(patternProperties);
2435
2546
  s = difference(s, p);
2436
- for (const ppKey of pp) {
2547
+ for (let i = 0; i < pp.length; i++) {
2548
+ const ppKey = pp[i];
2437
2549
  const result = compileSchemaRegex(ppKey);
2438
2550
  if (!result.ok) continue;
2439
2551
  const regExp = result.value;
2440
- for (let idx2 = s.length - 1; idx2 >= 0; idx2--) if (regExp.test(s[idx2]) === true) s.splice(idx2, 1);
2552
+ for (let idx2 = s.length - 1; idx2 >= 0; idx2--) if (regExp.test(s[idx2])) s.splice(idx2, 1);
2441
2553
  }
2442
2554
  if (s.length > 0) {
2443
- if (Array.isArray(this.options.assumeAdditional)) for (const allowed of this.options.assumeAdditional) {
2555
+ if (Array.isArray(ctx.options.assumeAdditional)) for (const allowed of ctx.options.assumeAdditional) {
2444
2556
  const io = s.indexOf(allowed);
2445
2557
  if (io !== -1) s.splice(io, 1);
2446
2558
  }
@@ -2448,29 +2560,29 @@ function propertiesValidator(report, schema, json) {
2448
2560
  }
2449
2561
  }
2450
2562
  }
2451
- function dependenciesValidator(report, schema, json) {
2452
- if (shouldSkipValidate(this.validateOptions, ["OBJECT_DEPENDENCY_KEY"])) return;
2563
+ function dependenciesValidator(ctx, report, schema, json) {
2564
+ if (shouldSkipValidate(ctx.validateOptions, ["OBJECT_DEPENDENCY_KEY"])) return;
2453
2565
  if (!isObject(json)) return;
2454
2566
  const keys = Object.keys(schema.dependencies);
2455
2567
  for (const dependencyName of keys) if (Object.hasOwn(json, dependencyName)) {
2456
2568
  const dependencyDefinition = schema.dependencies[dependencyName];
2457
2569
  if (Array.isArray(dependencyDefinition)) {
2458
2570
  for (const requiredPropertyName of dependencyDefinition) if (!Object.hasOwn(json, requiredPropertyName)) report.addError("OBJECT_DEPENDENCY_KEY", [requiredPropertyName, dependencyName], void 0, schema, "dependencies");
2459
- } else this._jsonValidate(report, dependencyDefinition, json);
2571
+ } else ctx._jsonValidate(report, dependencyDefinition, json);
2460
2572
  }
2461
2573
  }
2462
- function dependentSchemasValidator(report, schema, json) {
2463
- if (!supportsDependentKeywords(schema, this.options.version)) return;
2574
+ function dependentSchemasValidator(ctx, report, schema, json) {
2575
+ if (!supportsDependentKeywords(schema, ctx.options.version)) return;
2464
2576
  if (!isObject(json) || !isObject(schema.dependentSchemas)) return;
2465
2577
  const keys = Object.keys(schema.dependentSchemas);
2466
2578
  for (const dependencyName of keys) if (Object.hasOwn(json, dependencyName)) {
2467
2579
  const dependencySchema = schema.dependentSchemas[dependencyName];
2468
- this._jsonValidate(report, dependencySchema, json);
2580
+ ctx._jsonValidate(report, dependencySchema, json);
2469
2581
  }
2470
2582
  }
2471
- function dependentRequiredValidator(report, schema, json) {
2472
- if (!supportsDependentKeywords(schema, this.options.version)) return;
2473
- if (shouldSkipValidate(this.validateOptions, ["OBJECT_DEPENDENCY_KEY"])) return;
2583
+ function dependentRequiredValidator(ctx, report, schema, json) {
2584
+ if (!supportsDependentKeywords(schema, ctx.options.version)) return;
2585
+ if (shouldSkipValidate(ctx.validateOptions, ["OBJECT_DEPENDENCY_KEY"])) return;
2474
2586
  if (!isObject(json) || !isObject(schema.dependentRequired)) return;
2475
2587
  const keys = Object.keys(schema.dependentRequired);
2476
2588
  for (const dependencyName of keys) {
@@ -2480,8 +2592,8 @@ function dependentRequiredValidator(report, schema, json) {
2480
2592
  for (const requiredPropertyName of requiredProperties) if (!Object.hasOwn(json, requiredPropertyName)) report.addError("OBJECT_DEPENDENCY_KEY", [requiredPropertyName, dependencyName], void 0, schema, "dependentRequired");
2481
2593
  }
2482
2594
  }
2483
- function propertyNamesValidator(report, schema, json) {
2484
- if (shouldSkipValidate(this.validateOptions, ["PROPERTY_NAMES"])) return;
2595
+ function propertyNamesValidator(ctx, report, schema, json) {
2596
+ if (shouldSkipValidate(ctx.validateOptions, ["PROPERTY_NAMES"])) return;
2485
2597
  if (!isObject(json)) return;
2486
2598
  const propertyNamesSchema = schema.propertyNames;
2487
2599
  if (propertyNamesSchema === void 0) return;
@@ -2491,10 +2603,10 @@ function propertyNamesValidator(report, schema, json) {
2491
2603
  for (const key of keys) {
2492
2604
  const subReport = new Report_(report);
2493
2605
  subReports.push(subReport);
2494
- this._jsonValidate(subReport, propertyNamesSchema, key);
2606
+ ctx._jsonValidate(subReport, propertyNamesSchema, key);
2495
2607
  }
2496
2608
  const addPropertyNameErrors = () => {
2497
- for (let idx = 0; idx < keys.length; idx++) if (subReports[idx].errors.length > 0) report.addError("PROPERTY_NAMES", [keys[idx]], subReports[idx], schema, void 0);
2609
+ for (let idx = 0; idx < keys.length; idx++) if (subReports[idx].errors.length > 0) report.addError("PROPERTY_NAMES", [keys[idx]], subReports[idx], schema);
2498
2610
  };
2499
2611
  deferOrRunSync(report, subReports, addPropertyNameErrors);
2500
2612
  }
@@ -2504,7 +2616,7 @@ const getDynamicRefAnchorName = (dynamicRef) => {
2504
2616
  const hashIdx = dynamicRef.indexOf("#");
2505
2617
  if (hashIdx === -1) return;
2506
2618
  const fragment = dynamicRef.slice(hashIdx + 1);
2507
- if (!fragment || fragment[0] === "/") return;
2619
+ if (!fragment || fragment.startsWith("/")) return;
2508
2620
  return fragment;
2509
2621
  };
2510
2622
  const findDynamicAnchorInScope = (scopeSchema, anchorName) => {
@@ -2531,7 +2643,7 @@ const resolveRecursiveRef = (schema, recursiveAnchorStack) => {
2531
2643
  */
2532
2644
  const resolveDynamicRef = (schema, dynamicScopeStack) => {
2533
2645
  const resolved = schema.__$dynamicRefResolved;
2534
- if (typeof resolved === "undefined" || !schema.$dynamicRef) return resolved;
2646
+ if (resolved === void 0 || !schema.$dynamicRef) return resolved;
2535
2647
  let target = resolved;
2536
2648
  const anchorName = getDynamicRefAnchorName(schema.$dynamicRef);
2537
2649
  if (anchorName && typeof target === "object" && target.$dynamicAnchor === anchorName) for (let scopeIdx = 0; scopeIdx < dynamicScopeStack.length; scopeIdx++) {
@@ -2558,8 +2670,9 @@ const decodeBase64 = (value) => {
2558
2670
  } catch {
2559
2671
  return;
2560
2672
  }
2561
- if (typeof Buffer !== "undefined") try {
2562
- return Buffer.from(value, "base64").toString("utf8");
2673
+ const bufferCtor = globalThis.Buffer;
2674
+ if (bufferCtor !== void 0) try {
2675
+ return bufferCtor.from(value, "base64").toString("utf-8");
2563
2676
  } catch {
2564
2677
  return;
2565
2678
  }
@@ -2568,27 +2681,37 @@ const decodeBase64 = (value) => {
2568
2681
  //#region src/utils/unicode.ts
2569
2682
  /**
2570
2683
  * Returns the number of Unicode code points in the string.
2571
- * Uses the built-in string iterator which correctly handles surrogate pairs.
2684
+ * Uses a surrogate-aware charCodeAt scan (equivalent to the string iterator)
2685
+ * that counts a surrogate pair as one code point and lone surrogates as one each.
2572
2686
  */
2573
2687
  function unicodeLength(str) {
2574
- let count = 0;
2575
- for (const _cp of str) count++;
2688
+ let count = str.length;
2689
+ for (let i = 0; i < str.length - 1; i++) {
2690
+ const hi = str.charCodeAt(i);
2691
+ if (hi >= 55296 && hi <= 56319) {
2692
+ const lo = str.charCodeAt(i + 1);
2693
+ if (lo >= 56320 && lo <= 57343) {
2694
+ count--;
2695
+ i++;
2696
+ }
2697
+ }
2698
+ }
2576
2699
  return count;
2577
2700
  }
2578
2701
  //#endregion
2579
2702
  //#region src/validation/string.ts
2580
- function minLengthValidator(report, schema, json) {
2581
- if (shouldSkipValidate(this.validateOptions, ["MIN_LENGTH"])) return;
2703
+ function minLengthValidator(ctx, report, schema, json) {
2704
+ if (shouldSkipValidate(ctx.validateOptions, ["MIN_LENGTH"])) return;
2582
2705
  if (typeof json !== "string") return;
2583
2706
  if (unicodeLength(json) < schema.minLength) report.addError("MIN_LENGTH", [json.length, schema.minLength], void 0, schema, "minLength");
2584
2707
  }
2585
- function maxLengthValidator(report, schema, json) {
2586
- if (shouldSkipValidate(this.validateOptions, ["MAX_LENGTH"])) return;
2708
+ function maxLengthValidator(ctx, report, schema, json) {
2709
+ if (shouldSkipValidate(ctx.validateOptions, ["MAX_LENGTH"])) return;
2587
2710
  if (typeof json !== "string") return;
2588
2711
  if (unicodeLength(json) > schema.maxLength) report.addError("MAX_LENGTH", [json.length, schema.maxLength], void 0, schema, "maxLength");
2589
2712
  }
2590
- function patternValidator(report, schema, json) {
2591
- if (shouldSkipValidate(this.validateOptions, ["PATTERN"])) return;
2713
+ function patternValidator(ctx, report, schema, json) {
2714
+ if (shouldSkipValidate(ctx.validateOptions, ["PATTERN"])) return;
2592
2715
  if (typeof json !== "string") return;
2593
2716
  const result = compileSchemaRegex(schema.pattern);
2594
2717
  if (!result.ok) {
@@ -2601,46 +2724,46 @@ function patternValidator(report, schema, json) {
2601
2724
  }
2602
2725
  if (!result.value.test(json)) report.addError("PATTERN", [schema.pattern, json], void 0, schema, "pattern");
2603
2726
  }
2604
- function formatValidator(report, schema, json) {
2605
- if (this.options.formatAssertions === false) return;
2606
- if (this.options.formatAssertions === true) {
2607
- if (!isFormatAssertionVocabEnabled(schema, report, this.options.version)) return;
2608
- }
2609
- const isModernDraft = this.options.version === "draft2019-09" || this.options.version === "draft2020-12";
2610
- const formatValidatorFn = getFormatValidators(this.options)[schema.format];
2727
+ function formatValidator(ctx, report, schema, json) {
2728
+ if (ctx.options.formatAssertions === false) return;
2729
+ if (ctx.options.formatAssertions === true && !isFormatAssertionVocabEnabled(schema, report, ctx.options.version)) return;
2730
+ const isModernDraft = ctx.options.version === "draft2019-09" || ctx.options.version === "draft2020-12";
2731
+ const formatValidatorFn = resolveFormatValidator(schema.format, ctx.options);
2611
2732
  if (typeof formatValidatorFn === "function") {
2612
- if (shouldSkipValidate(this.validateOptions, ["INVALID_FORMAT"])) return;
2733
+ if (shouldSkipValidate(ctx.validateOptions, ["INVALID_FORMAT"])) return;
2613
2734
  if (report.hasError("INVALID_TYPE", [schema.type, whatIs(json)])) return;
2614
- if (formatValidatorFn.length === 2) report.addAsyncTaskWithPath(formatValidatorFn, [json], function(result) {
2735
+ if (formatValidatorFn.length === 2) report.addAsyncTaskWithPath(formatValidatorFn, [json], (result) => {
2615
2736
  if (result !== true) report.addError("INVALID_FORMAT", [schema.format, JSON.stringify(json)], void 0, schema, "format");
2616
2737
  });
2617
2738
  else {
2618
- const result = formatValidatorFn.call(this, json);
2739
+ const result = formatValidatorFn.call(ctx, json);
2619
2740
  if (result instanceof Promise) {
2620
2741
  const promiseResult = result;
2621
2742
  report.addAsyncTaskWithPath(async (callback) => {
2743
+ let resolved = false;
2622
2744
  try {
2623
- callback(await promiseResult);
2624
- } catch (_error) {
2625
- callback(false);
2626
- }
2627
- }, [], function(resolvedResult) {
2745
+ resolved = await promiseResult;
2746
+ } catch {}
2747
+ callback(resolved);
2748
+ }, [], (resolvedResult) => {
2628
2749
  if (resolvedResult !== true) report.addError("INVALID_FORMAT", [schema.format, JSON.stringify(json)], void 0, schema, "format");
2629
2750
  });
2630
- } else if (result !== true) report.addError("INVALID_FORMAT", [schema.format, JSON.stringify(json)], void 0, schema, "format");
2751
+ } else if (!result) report.addError("INVALID_FORMAT", [schema.format, JSON.stringify(json)], void 0, schema, "format");
2631
2752
  }
2632
- } else if (this.options.ignoreUnknownFormats !== true && !isModernDraft) report.addError("UNKNOWN_FORMAT", [schema.format], void 0, schema, "format");
2753
+ } else if (ctx.options.ignoreUnknownFormats !== true && !isModernDraft) report.addError("UNKNOWN_FORMAT", [schema.format], void 0, schema, "format");
2633
2754
  }
2634
- function contentEncodingValidator(report, schema, json) {
2635
- if (this.options.version !== "draft-07") return;
2755
+ function contentEncodingValidator(ctx, report, schema, json) {
2756
+ if (ctx.options.version !== "draft-07") return;
2636
2757
  if (typeof json !== "string") return;
2637
- if (schema.contentEncoding !== "base64") return;
2758
+ const { contentEncoding } = schema;
2759
+ if (contentEncoding !== "base64") return;
2638
2760
  if (!isValidBase64(json)) report.addError("INVALID_FORMAT", ["contentEncoding:base64", JSON.stringify(json)], void 0, schema, "contentEncoding");
2639
2761
  }
2640
- function contentMediaTypeValidator(report, schema, json) {
2641
- if (this.options.version !== "draft-07") return;
2762
+ function contentMediaTypeValidator(ctx, report, schema, json) {
2763
+ if (ctx.options.version !== "draft-07") return;
2642
2764
  if (typeof json !== "string") return;
2643
- if (schema.contentMediaType !== "application/json") return;
2765
+ const { contentMediaType } = schema;
2766
+ if (contentMediaType !== "application/json") return;
2644
2767
  let payload = json;
2645
2768
  if (schema.contentEncoding === "base64") {
2646
2769
  const decoded = decodeBase64(json);
@@ -2658,38 +2781,40 @@ function contentMediaTypeValidator(report, schema, json) {
2658
2781
  }
2659
2782
  //#endregion
2660
2783
  //#region src/validation/type.ts
2661
- function typeValidator(report, schema, json) {
2662
- if (shouldSkipValidate(this.validateOptions, ["INVALID_TYPE"])) return;
2784
+ function typeValidator(ctx, report, schema, json) {
2785
+ if (shouldSkipValidate(ctx.validateOptions, ["INVALID_TYPE"])) return;
2663
2786
  const jsonType = whatIs(json);
2664
2787
  if (typeof schema.type === "string") {
2665
2788
  if (jsonType !== schema.type && (jsonType !== "integer" || schema.type !== "number")) report.addError("INVALID_TYPE", [schema.type, jsonType], void 0, schema, "type");
2666
2789
  } else if (!schema.type.includes(jsonType) && (jsonType !== "integer" || !schema.type.includes("number"))) report.addError("INVALID_TYPE", [JSON.stringify(schema.type), jsonType], void 0, schema, "type");
2667
2790
  }
2668
- function enumValidator(report, schema, json) {
2669
- if (shouldSkipValidate(this.validateOptions, ["ENUM_CASE_MISMATCH", "ENUM_MISMATCH"])) return;
2670
- let match = false, caseInsensitiveMatch = false;
2671
- for (const enumVal of schema.enum) if (areEqual(json, enumVal, { maxDepth: this.options.maxRecursionDepth })) {
2791
+ function enumValidator(ctx, report, schema, json) {
2792
+ if (shouldSkipValidate(ctx.validateOptions, ["ENUM_CASE_MISMATCH", "ENUM_MISMATCH"])) return;
2793
+ const eqOpts = { maxDepth: ctx.options.maxRecursionDepth };
2794
+ const eqOptsCI = {
2795
+ caseInsensitiveComparison: true,
2796
+ maxDepth: ctx.options.maxRecursionDepth
2797
+ };
2798
+ let caseInsensitiveMatch = false, match = false;
2799
+ for (const enumVal of schema.enum) if (areEqual(json, enumVal, eqOpts)) {
2672
2800
  match = true;
2673
2801
  break;
2674
- } else if (areEqual(json, enumVal, {
2675
- caseInsensitiveComparison: true,
2676
- maxDepth: this.options.maxRecursionDepth
2677
- })) caseInsensitiveMatch = true;
2678
- if (match === false) {
2679
- const error = caseInsensitiveMatch && this.options.enumCaseInsensitiveComparison ? "ENUM_CASE_MISMATCH" : "ENUM_MISMATCH";
2802
+ } else if (areEqual(json, enumVal, eqOptsCI)) caseInsensitiveMatch = true;
2803
+ if (!match) {
2804
+ const error = caseInsensitiveMatch && ctx.options.enumCaseInsensitiveComparison ? "ENUM_CASE_MISMATCH" : "ENUM_MISMATCH";
2680
2805
  report.addError(error, [JSON.stringify(json)], void 0, schema, "enum");
2681
2806
  }
2682
2807
  }
2683
- function constValidator(report, schema, json) {
2808
+ function constValidator(ctx, report, schema, json) {
2684
2809
  const constValue = schema.const;
2685
- if (areEqual(json, constValue, { maxDepth: this.options.maxRecursionDepth }) === false) report.addError("CONST", [JSON.stringify(constValue)], void 0, schema, void 0);
2810
+ if (!areEqual(json, constValue, { maxDepth: ctx.options.maxRecursionDepth })) report.addError("CONST", [JSON.stringify(constValue)], void 0, schema);
2686
2811
  }
2687
2812
  //#endregion
2688
2813
  //#region src/json-validation.ts
2689
- function collectEvaluated(args) {
2814
+ function collectEvaluated(ctx, args) {
2690
2815
  const { report, currentSchema, json, mode, depth } = args;
2691
2816
  if (!currentSchema || typeof currentSchema === "boolean") return /* @__PURE__ */ new Set();
2692
- if (depth > (this.options.maxRecursionDepth ?? 100)) {
2817
+ if (depth > (ctx.options.maxRecursionDepth ?? 100)) {
2693
2818
  report.addError("COLLECT_EVALUATED_DEPTH_EXCEEDED", [depth]);
2694
2819
  return /* @__PURE__ */ new Set();
2695
2820
  }
@@ -2700,7 +2825,7 @@ function collectEvaluated(args) {
2700
2825
  return false;
2701
2826
  };
2702
2827
  const recurse = (subSchema) => {
2703
- if (mode === "items") return collectEvaluated.call(this, {
2828
+ if (mode === "items") return collectEvaluated(ctx, {
2704
2829
  report,
2705
2830
  currentSchema: subSchema,
2706
2831
  json,
@@ -2708,7 +2833,7 @@ function collectEvaluated(args) {
2708
2833
  jsonArr: args.jsonArr,
2709
2834
  depth: depth + 1
2710
2835
  });
2711
- return collectEvaluated.call(this, {
2836
+ return collectEvaluated(ctx, {
2712
2837
  report,
2713
2838
  currentSchema: subSchema,
2714
2839
  json,
@@ -2718,7 +2843,7 @@ function collectEvaluated(args) {
2718
2843
  });
2719
2844
  };
2720
2845
  if (mode === "items") {
2721
- const jsonArr = args.jsonArr;
2846
+ const { jsonArr } = args;
2722
2847
  if (Array.isArray(currentSchema.prefixItems)) {
2723
2848
  const len = Math.min(currentSchema.prefixItems.length, jsonArr.length);
2724
2849
  for (let i = 0; i < len; i++) evaluated.add(i);
@@ -2734,104 +2859,102 @@ function collectEvaluated(args) {
2734
2859
  let passed = getCachedValidationResult(report, currentSchema.contains, jsonArr[i]);
2735
2860
  if (passed === void 0) {
2736
2861
  const subReport = new Report(report);
2737
- validate.call(this, subReport, currentSchema.contains, jsonArr[i]);
2862
+ validate(ctx, subReport, currentSchema.contains, jsonArr[i]);
2738
2863
  passed = subReport.errors.length === 0;
2739
2864
  }
2740
2865
  if (passed) evaluated.add(i);
2741
2866
  }
2742
2867
  if (currentSchema.unevaluatedItems === true) return "all";
2743
2868
  } else {
2744
- const jsonData = args.jsonData;
2869
+ const { jsonData } = args;
2745
2870
  if (isObject(currentSchema.properties)) {
2746
- for (const key of Object.keys(currentSchema.properties)) if (Object.hasOwn(jsonData, key)) evaluated.add(key);
2871
+ const propKeysCE = Object.keys(currentSchema.properties);
2872
+ for (let i = 0; i < propKeysCE.length; i++) {
2873
+ const key = propKeysCE[i];
2874
+ if (Object.hasOwn(jsonData, key)) evaluated.add(key);
2875
+ }
2747
2876
  }
2748
2877
  if (isObject(currentSchema.patternProperties)) for (const pattern of Object.keys(currentSchema.patternProperties)) {
2749
2878
  const result = compileSchemaRegex(pattern);
2750
2879
  if (result.ok) {
2751
- for (const key of Object.keys(jsonData)) if (result.value.test(key)) evaluated.add(key);
2880
+ const jdKeys = Object.keys(jsonData);
2881
+ for (let i = 0; i < jdKeys.length; i++) if (result.value.test(jdKeys[i])) evaluated.add(jdKeys[i]);
2752
2882
  }
2753
2883
  }
2754
2884
  if (currentSchema.additionalProperties !== void 0) {
2755
- const propKeys = isObject(currentSchema.properties) ? Object.keys(currentSchema.properties) : [];
2885
+ const propKeySet = new Set(isObject(currentSchema.properties) ? Object.keys(currentSchema.properties) : []);
2756
2886
  const patternRegexes = [];
2757
2887
  if (isObject(currentSchema.patternProperties)) for (const pattern of Object.keys(currentSchema.patternProperties)) {
2758
2888
  const result = compileSchemaRegex(pattern);
2759
2889
  if (result.ok) patternRegexes.push(result.value);
2760
2890
  }
2761
- for (const key of Object.keys(jsonData)) {
2762
- if (propKeys.includes(key)) continue;
2763
- if (patternRegexes.some((re) => re.test(key))) continue;
2891
+ const apKeys = Object.keys(jsonData);
2892
+ for (let i = 0; i < apKeys.length; i++) {
2893
+ const key = apKeys[i];
2894
+ if (propKeySet.has(key)) continue;
2895
+ let matchedPattern = false;
2896
+ for (let pi = 0; pi < patternRegexes.length; pi++) if (patternRegexes[pi].test(key)) {
2897
+ matchedPattern = true;
2898
+ break;
2899
+ }
2900
+ if (matchedPattern) continue;
2764
2901
  evaluated.add(key);
2765
2902
  }
2766
2903
  }
2767
2904
  if (isObject(currentSchema.dependentSchemas)) {
2768
- for (const [depKey, depSchema] of Object.entries(currentSchema.dependentSchemas)) if (Object.hasOwn(jsonData, depKey)) {
2769
- if (merge(recurse(depSchema))) return "all";
2770
- }
2905
+ for (const [depKey, depSchema] of Object.entries(currentSchema.dependentSchemas)) if (Object.hasOwn(jsonData, depKey) && merge(recurse(depSchema))) return "all";
2771
2906
  }
2772
2907
  if (currentSchema.unevaluatedProperties === true) return "all";
2773
2908
  }
2774
2909
  if (Array.isArray(currentSchema.allOf)) {
2775
- for (const subSchema of currentSchema.allOf) if (merge(recurse(subSchema))) return "all";
2910
+ for (let i = 0; i < currentSchema.allOf.length; i++) if (merge(recurse(currentSchema.allOf[i]))) return "all";
2776
2911
  }
2777
- if (Array.isArray(currentSchema.anyOf)) for (const subSchema of currentSchema.anyOf) {
2912
+ if (Array.isArray(currentSchema.anyOf)) for (let i = 0; i < currentSchema.anyOf.length; i++) {
2913
+ const subSchema = currentSchema.anyOf[i];
2778
2914
  let passed = getCachedValidationResult(report, subSchema, json);
2779
2915
  if (passed === void 0) {
2780
2916
  const subReport = new Report(report);
2781
- validate.call(this, subReport, subSchema, json);
2917
+ validate(ctx, subReport, subSchema, json);
2782
2918
  passed = subReport.errors.length === 0;
2783
2919
  }
2784
- if (passed) {
2785
- if (merge(recurse(subSchema))) return "all";
2786
- }
2920
+ if (passed && merge(recurse(subSchema))) return "all";
2787
2921
  }
2788
- if (Array.isArray(currentSchema.oneOf)) for (const subSchema of currentSchema.oneOf) {
2922
+ if (Array.isArray(currentSchema.oneOf)) for (let i = 0; i < currentSchema.oneOf.length; i++) {
2923
+ const subSchema = currentSchema.oneOf[i];
2789
2924
  let passed = getCachedValidationResult(report, subSchema, json);
2790
2925
  if (passed === void 0) {
2791
2926
  const subReport = new Report(report);
2792
- validate.call(this, subReport, subSchema, json);
2927
+ validate(ctx, subReport, subSchema, json);
2793
2928
  passed = subReport.errors.length === 0;
2794
2929
  }
2795
- if (passed) {
2796
- if (merge(recurse(subSchema))) return "all";
2797
- }
2930
+ if (passed && merge(recurse(subSchema))) return "all";
2798
2931
  }
2799
2932
  if (currentSchema.if !== void 0) {
2800
2933
  let condPassed = getCachedValidationResult(report, currentSchema.if, json);
2801
2934
  if (condPassed === void 0) {
2802
2935
  const condReport = new Report(report);
2803
- validate.call(this, condReport, currentSchema.if, json);
2936
+ validate(ctx, condReport, currentSchema.if, json);
2804
2937
  condPassed = condReport.errors.length === 0;
2805
2938
  }
2806
2939
  if (condPassed) {
2807
2940
  if (merge(recurse(currentSchema.if))) return "all";
2808
- if (currentSchema.then !== void 0) {
2809
- if (merge(recurse(currentSchema.then))) return "all";
2810
- }
2811
- } else if (currentSchema.else !== void 0) {
2812
- if (merge(recurse(currentSchema.else))) return "all";
2813
- }
2814
- }
2815
- if (currentSchema.__$refResolved && currentSchema.__$refResolved !== currentSchema) {
2816
- if (merge(recurse(currentSchema.__$refResolved))) return "all";
2941
+ if (currentSchema.then !== void 0 && merge(recurse(currentSchema.then))) return "all";
2942
+ } else if (currentSchema.else !== void 0 && merge(recurse(currentSchema.else))) return "all";
2817
2943
  }
2944
+ if (currentSchema.__$refResolved && currentSchema.__$refResolved !== currentSchema && merge(recurse(currentSchema.__$refResolved))) return "all";
2818
2945
  const recursiveTarget = resolveRecursiveRef(currentSchema, report.__$recursiveAnchorStack);
2819
- if (recursiveTarget && recursiveTarget !== currentSchema) {
2820
- if (merge(recurse(recursiveTarget))) return "all";
2821
- }
2946
+ if (recursiveTarget && recursiveTarget !== currentSchema && merge(recurse(recursiveTarget))) return "all";
2822
2947
  const dynamicTarget = resolveDynamicRef(currentSchema, report.__$dynamicScopeStack);
2823
- if (dynamicTarget && dynamicTarget !== currentSchema) {
2824
- if (merge(recurse(dynamicTarget))) return "all";
2825
- }
2948
+ if (dynamicTarget && dynamicTarget !== currentSchema && merge(recurse(dynamicTarget))) return "all";
2826
2949
  return evaluated;
2827
2950
  }
2828
- function unevaluatedItemsValidator(report, schema, json) {
2951
+ function unevaluatedItemsValidator(ctx, report, schema, json) {
2829
2952
  if (!Array.isArray(json)) return;
2830
2953
  if (schema.unevaluatedItems === true) return;
2831
2954
  const unevalSchema = schema.unevaluatedItems;
2832
2955
  if (unevalSchema === void 0) return;
2833
2956
  if (json.length === 0) return;
2834
- const evaluatedItems = collectEvaluated.call(this, {
2957
+ const evaluatedItems = collectEvaluated(ctx, {
2835
2958
  report,
2836
2959
  currentSchema: schema,
2837
2960
  json,
@@ -2844,23 +2967,24 @@ function unevaluatedItemsValidator(report, schema, json) {
2844
2967
  for (let i = 0; i < json.length; i++) if (!evaluatedItems.has(i)) unevaluatedIndices.push(i);
2845
2968
  if (unevaluatedIndices.length === 0) return;
2846
2969
  if (unevalSchema === false) report.addError("ARRAY_UNEVALUATED_ITEMS", void 0, void 0, schema, "unevaluatedItems");
2847
- else for (const idx of unevaluatedIndices) {
2970
+ else for (let i = 0; i < unevaluatedIndices.length; i++) {
2971
+ const idx = unevaluatedIndices[i];
2848
2972
  const subReport = new Report(report);
2849
- validate.call(this, subReport, unevalSchema, json[idx]);
2973
+ validate(ctx, subReport, unevalSchema, json[idx]);
2850
2974
  if (subReport.errors.length > 0) {
2851
2975
  report.addError("ARRAY_UNEVALUATED_ITEMS", void 0, void 0, schema, "unevaluatedItems");
2852
2976
  break;
2853
2977
  }
2854
2978
  }
2855
2979
  }
2856
- function unevaluatedPropertiesValidator(report, schema, json) {
2980
+ function unevaluatedPropertiesValidator(ctx, report, schema, json) {
2857
2981
  if (!isObject(json)) return;
2858
2982
  if (schema.unevaluatedProperties === true) return;
2859
2983
  const unevalSchema = schema.unevaluatedProperties;
2860
2984
  if (unevalSchema === void 0) return;
2861
2985
  const allKeys = Object.keys(json);
2862
2986
  if (allKeys.length === 0) return;
2863
- const evaluatedProperties = collectEvaluated.call(this, {
2987
+ const evaluatedProperties = collectEvaluated(ctx, {
2864
2988
  report,
2865
2989
  currentSchema: schema,
2866
2990
  json,
@@ -2869,32 +2993,35 @@ function unevaluatedPropertiesValidator(report, schema, json) {
2869
2993
  depth: 0
2870
2994
  });
2871
2995
  if (evaluatedProperties === "all") return;
2872
- const unevaluatedKeys = allKeys.filter((key) => !evaluatedProperties.has(key));
2996
+ const unevaluatedKeys = [];
2997
+ for (let i = 0; i < allKeys.length; i++) if (!evaluatedProperties.has(allKeys[i])) unevaluatedKeys.push(allKeys[i]);
2873
2998
  if (unevaluatedKeys.length === 0) return;
2874
2999
  if (unevalSchema === false) report.addError("OBJECT_UNEVALUATED_PROPERTIES", [unevaluatedKeys.join(", ")], void 0, schema, "unevaluatedProperties");
2875
- else for (const key of unevaluatedKeys) {
3000
+ else for (let i = 0; i < unevaluatedKeys.length; i++) {
3001
+ const key = unevaluatedKeys[i];
2876
3002
  const subReport = new Report(report);
2877
- validate.call(this, subReport, unevalSchema, json[key]);
3003
+ validate(ctx, subReport, unevalSchema, json[key]);
2878
3004
  if (subReport.errors.length > 0) report.addError("OBJECT_UNEVALUATED_PROPERTIES", [key], void 0, schema, "unevaluatedProperties");
2879
3005
  }
2880
3006
  }
2881
3007
  function definitionsValidator() {}
3008
+ const noopValidator = () => {};
2882
3009
  const JsonValidators = {
2883
- id: () => {},
2884
- $id: () => {},
2885
- $ref: () => {},
2886
- $schema: () => {},
2887
- $dynamicAnchor: () => {},
2888
- $dynamicRef: () => {},
2889
- $anchor: () => {},
2890
- $defs: () => {},
2891
- $vocabulary: () => {},
2892
- $recursiveAnchor: () => {},
2893
- $recursiveRef: () => {},
2894
- examples: () => {},
2895
- title: () => {},
2896
- description: () => {},
2897
- default: () => {},
3010
+ id: noopValidator,
3011
+ $id: noopValidator,
3012
+ $ref: noopValidator,
3013
+ $schema: noopValidator,
3014
+ $dynamicAnchor: noopValidator,
3015
+ $dynamicRef: noopValidator,
3016
+ $anchor: noopValidator,
3017
+ $defs: noopValidator,
3018
+ $vocabulary: noopValidator,
3019
+ $recursiveAnchor: noopValidator,
3020
+ $recursiveRef: noopValidator,
3021
+ examples: noopValidator,
3022
+ title: noopValidator,
3023
+ description: noopValidator,
3024
+ default: noopValidator,
2898
3025
  type: typeValidator,
2899
3026
  enum: enumValidator,
2900
3027
  const: constValidator,
@@ -2939,18 +3066,18 @@ const JsonValidators = {
2939
3066
  else: elseValidator,
2940
3067
  definitions: definitionsValidator
2941
3068
  };
2942
- const recurseArray = function(report, schema, json) {
3069
+ function recurseArray(ctx, report, schema, json) {
2943
3070
  const schemaUri = typeof schema.$schema === "string" ? schema.$schema : void 0;
2944
- const prefixItems = (schemaUri === "https://json-schema.org/draft/2020-12/schema" || !schemaUri && this.options.version === "draft2020-12") && Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0;
3071
+ const prefixItems = (schemaUri === "https://json-schema.org/draft/2020-12/schema" || !schemaUri && ctx.options.version === "draft2020-12") && Array.isArray(schema.prefixItems) ? schema.prefixItems : void 0;
2945
3072
  if (prefixItems) {
2946
3073
  for (let idx = 0; idx < json.length; idx++) if (idx < prefixItems.length) {
2947
3074
  report.path.push(idx);
2948
- validate.call(this, report, prefixItems[idx], json[idx]);
3075
+ validate(ctx, report, prefixItems[idx], json[idx]);
2949
3076
  report.path.pop();
2950
3077
  } else if (schema.items !== void 0 && !Array.isArray(schema.items)) {
2951
3078
  report.path.push(idx);
2952
3079
  report.schemaPath.push("items");
2953
- validate.call(this, report, schema.items, json[idx]);
3080
+ validate(ctx, report, schema.items, json[idx]);
2954
3081
  report.schemaPath.pop();
2955
3082
  report.path.pop();
2956
3083
  }
@@ -2959,50 +3086,56 @@ const recurseArray = function(report, schema, json) {
2959
3086
  if (Array.isArray(schema.items)) {
2960
3087
  for (let idx = 0; idx < json.length; idx++) if (idx < schema.items.length) {
2961
3088
  report.path.push(idx);
2962
- validate.call(this, report, schema.items[idx], json[idx]);
3089
+ validate(ctx, report, schema.items[idx], json[idx]);
2963
3090
  report.path.pop();
2964
3091
  } else if (typeof schema.additionalItems === "object") {
2965
3092
  report.path.push(idx);
2966
- validate.call(this, report, schema.additionalItems, json[idx]);
3093
+ validate(ctx, report, schema.additionalItems, json[idx]);
2967
3094
  report.path.pop();
2968
3095
  }
2969
3096
  } else if (typeof schema.items === "object" || typeof schema.items === "boolean") for (let idx = 0; idx < json.length; idx++) {
2970
3097
  report.path.push(idx);
2971
3098
  report.schemaPath.push("items");
2972
- validate.call(this, report, schema.items, json[idx]);
3099
+ validate(ctx, report, schema.items, json[idx]);
2973
3100
  report.schemaPath.pop();
2974
3101
  report.path.pop();
2975
3102
  }
2976
- };
2977
- const recurseObject = function(report, schema, json) {
2978
- let additionalProperties = schema.additionalProperties;
3103
+ }
3104
+ function recurseObject(ctx, report, schema, json) {
3105
+ let { additionalProperties } = schema;
2979
3106
  if (additionalProperties === true || additionalProperties === void 0) additionalProperties = {};
2980
3107
  const p = schema.properties ? Object.keys(schema.properties) : [];
2981
3108
  const pp = schema.patternProperties ? Object.keys(schema.patternProperties) : [];
2982
3109
  const keys = Object.keys(json);
3110
+ const ppCompiled = [];
3111
+ for (let i = 0; i < pp.length; i++) {
3112
+ const r = compileSchemaRegex(pp[i]);
3113
+ if (r.ok) ppCompiled.push({
3114
+ key: pp[i],
3115
+ re: r.value
3116
+ });
3117
+ }
2983
3118
  for (const m of keys) {
2984
3119
  const propertyValue = json[m];
3120
+ const isProp = p.includes(m);
2985
3121
  const s = [];
2986
- if (p.includes(m)) s.push(schema.properties[m]);
2987
- for (const regexString of pp) {
2988
- const result = compileSchemaRegex(regexString);
2989
- if (result.ok && result.value.test(m) === true) s.push(schema.patternProperties[regexString]);
2990
- }
3122
+ if (isProp) s.push(schema.properties[m]);
3123
+ for (let i = 0; i < ppCompiled.length; i++) if (ppCompiled[i].re.test(m)) s.push(schema.patternProperties[ppCompiled[i].key]);
2991
3124
  if (s.length === 0 && additionalProperties !== false) s.push(additionalProperties);
2992
3125
  for (const schema_s of s) {
2993
3126
  report.path.push(m);
2994
- if (p.includes(m)) {
3127
+ if (isProp) {
2995
3128
  report.schemaPath.push("properties");
2996
3129
  report.schemaPath.push(m);
2997
3130
  } else report.schemaPath.push("additionalProperties");
2998
- validate.call(this, report, schema_s, propertyValue);
3131
+ validate(ctx, report, schema_s, propertyValue);
2999
3132
  report.path.pop();
3000
3133
  report.schemaPath.pop();
3001
- if (p.includes(m)) report.schemaPath.pop();
3134
+ if (isProp) report.schemaPath.pop();
3002
3135
  }
3003
3136
  }
3004
- };
3005
- function validate(report, schema, json) {
3137
+ }
3138
+ function validate(ctx, report, schema, json) {
3006
3139
  report.commonErrorMessage = "JSON_OBJECT_VALIDATION_FAILED";
3007
3140
  if (schema === true) return true;
3008
3141
  if (schema === false) {
@@ -3026,7 +3159,7 @@ function validate(report, schema, json) {
3026
3159
  let pushedDynamicScope = false;
3027
3160
  const schemaId = getId(schema);
3028
3161
  const dynamicScopeEntry = schema.__$resourceRoot || (isRoot || typeof schemaId === "string" ? schema : void 0);
3029
- if (dynamicScopeEntry && dynamicScopeStack[dynamicScopeStack.length - 1] !== dynamicScopeEntry) {
3162
+ if (dynamicScopeEntry && dynamicScopeStack.at(-1) !== dynamicScopeEntry) {
3030
3163
  dynamicScopeStack.push(dynamicScopeEntry);
3031
3164
  pushedDynamicScope = true;
3032
3165
  }
@@ -3034,10 +3167,11 @@ function validate(report, schema, json) {
3034
3167
  recursiveAnchorStack.push(schema);
3035
3168
  pushedRecursiveAnchor = true;
3036
3169
  }
3037
- if (schema.$ref !== void 0) if (this.options.version === "draft2019-09" || this.options.version === "draft2020-12") {
3038
- if (!schema.__$refResolved) report.addError("REF_UNRESOLVED", [schema.$ref], void 0, schema);
3039
- else validate.call(this, report, schema.__$refResolved, json);
3040
- keys = keys.filter((key) => key !== "$ref");
3170
+ if (schema.$ref !== void 0) if (ctx.options.version === "draft2019-09" || ctx.options.version === "draft2020-12") {
3171
+ if (schema.__$refResolved) validate(ctx, report, schema.__$refResolved, json);
3172
+ else report.addError("REF_UNRESOLVED", [schema.$ref], void 0, schema);
3173
+ const refIdx = keys.indexOf("$ref");
3174
+ if (refIdx !== -1) keys.splice(refIdx, 1);
3041
3175
  } else {
3042
3176
  let maxRefs = 99;
3043
3177
  while (schema.$ref && maxRefs > 0) {
@@ -3055,58 +3189,66 @@ function validate(report, schema, json) {
3055
3189
  report.schemaPath = [];
3056
3190
  }
3057
3191
  if (schema.$recursiveRef !== void 0) {
3058
- if (this.options.version === "draft2019-09" || this.options.version === "draft2020-12") {
3192
+ if (ctx.options.version === "draft2019-09" || ctx.options.version === "draft2020-12") {
3059
3193
  const recursiveRefTarget = resolveRecursiveRef(schema, recursiveAnchorStack);
3060
- if (!recursiveRefTarget) report.addError("REF_UNRESOLVED", [schema.$recursiveRef], void 0, schema);
3061
- else validate.call(this, report, recursiveRefTarget, json);
3062
- keys = keys.filter((key) => key !== "$recursiveRef");
3194
+ if (recursiveRefTarget) validate(ctx, report, recursiveRefTarget, json);
3195
+ else report.addError("REF_UNRESOLVED", [schema.$recursiveRef], void 0, schema);
3196
+ const recursiveRefIdx = keys.indexOf("$recursiveRef");
3197
+ if (recursiveRefIdx !== -1) keys.splice(recursiveRefIdx, 1);
3063
3198
  }
3064
3199
  }
3065
3200
  if (schema.$dynamicRef !== void 0) {
3066
- if (this.options.version === "draft2020-12") {
3201
+ if (ctx.options.version === "draft2020-12") {
3067
3202
  const dynamicRefTarget = resolveDynamicRef(schema, dynamicScopeStack);
3068
- if (typeof dynamicRefTarget === "undefined") report.addError("REF_UNRESOLVED", [schema.$dynamicRef], void 0, schema);
3069
- else validate.call(this, report, dynamicRefTarget, json);
3070
- keys = keys.filter((key) => key !== "$dynamicRef");
3203
+ if (dynamicRefTarget === void 0) report.addError("REF_UNRESOLVED", [schema.$dynamicRef], void 0, schema);
3204
+ else validate(ctx, report, dynamicRefTarget, json);
3205
+ const dynamicRefIdx = keys.indexOf("$dynamicRef");
3206
+ if (dynamicRefIdx !== -1) keys.splice(dynamicRefIdx, 1);
3071
3207
  }
3072
3208
  }
3073
- const validationVocabularyEnabled = isValidationVocabularyEnabled(schema, report, this.options.version);
3074
- if (!validationVocabularyEnabled) keys = keys.filter((key) => !VALIDATION_VOCAB_KEYWORDS.has(key));
3209
+ const validationVocabularyEnabled = isValidationVocabularyEnabled(schema, report, ctx.options.version);
3210
+ if (!validationVocabularyEnabled) {
3211
+ let wi = 0;
3212
+ for (let ri = 0; ri < keys.length; ri++) if (!VALIDATION_VOCAB_KEYWORDS.has(keys[ri])) keys[wi++] = keys[ri];
3213
+ keys.length = wi;
3214
+ }
3075
3215
  if (validationVocabularyEnabled && schema.type) {
3076
3216
  keys.splice(keys.indexOf("type"), 1);
3077
3217
  report.schemaPath.push("type");
3078
- JsonValidators.type.call(this, report, schema, json);
3218
+ JsonValidators.type(ctx, report, schema, json);
3079
3219
  report.schemaPath.pop();
3080
- if (report.errors.length && this.options.breakOnFirstError) {
3220
+ if (report.errors.length && ctx.options.breakOnFirstError) {
3081
3221
  if (pushedRecursiveAnchor) recursiveAnchorStack.pop();
3082
3222
  if (pushedDynamicScope) dynamicScopeStack.pop();
3083
3223
  return false;
3084
3224
  }
3085
3225
  }
3086
3226
  const deferredUnevaluatedKeys = [];
3087
- for (const key of keys) {
3227
+ for (let i = 0; i < keys.length; i++) {
3228
+ const key = keys[i];
3088
3229
  if (key === "unevaluatedItems" || key === "unevaluatedProperties") {
3089
3230
  deferredUnevaluatedKeys.push(key);
3090
3231
  continue;
3091
3232
  }
3092
3233
  const validator = JsonValidators[key];
3093
3234
  if (validator) {
3094
- validator.call(this, report, schema, json);
3095
- if (report.errors.length && this.options.breakOnFirstError) break;
3235
+ validator(ctx, report, schema, json);
3236
+ if (report.errors.length && ctx.options.breakOnFirstError) break;
3096
3237
  }
3097
3238
  }
3098
- if (deferredUnevaluatedKeys.length > 0 && !(report.errors.length > 0 && this.options.breakOnFirstError)) for (const key of deferredUnevaluatedKeys) {
3239
+ if (deferredUnevaluatedKeys.length > 0 && !(report.errors.length > 0 && ctx.options.breakOnFirstError)) for (let i = 0; i < deferredUnevaluatedKeys.length; i++) {
3240
+ const key = deferredUnevaluatedKeys[i];
3099
3241
  const validator = JsonValidators[key];
3100
3242
  if (validator) {
3101
- validator.call(this, report, schema, json);
3102
- if (report.errors.length && this.options.breakOnFirstError) break;
3243
+ validator(ctx, report, schema, json);
3244
+ if (report.errors.length && ctx.options.breakOnFirstError) break;
3103
3245
  }
3104
3246
  }
3105
- if (report.errors.length === 0 || this.options.breakOnFirstError === false) {
3106
- if (Array.isArray(json)) recurseArray.call(this, report, schema, json);
3107
- else if (isObject(json)) recurseObject.call(this, report, schema, json);
3247
+ if (report.errors.length === 0 || ctx.options.breakOnFirstError === false) {
3248
+ if (Array.isArray(json)) recurseArray(ctx, report, schema, json);
3249
+ else if (isObject(json)) recurseObject(ctx, report, schema, json);
3108
3250
  }
3109
- if (typeof this.options.customValidator === "function") this.options.customValidator.call(this, report, schema, json);
3251
+ if (typeof ctx.options.customValidator === "function") ctx.options.customValidator.call(ctx, report, schema, json);
3110
3252
  if (pushedRecursiveAnchor) recursiveAnchorStack.pop();
3111
3253
  if (pushedDynamicScope) dynamicScopeStack.pop();
3112
3254
  if (isRoot) report.rootSchema = void 0;
@@ -3123,14 +3265,14 @@ function setSchemaReader(schemaReader) {
3123
3265
  }
3124
3266
  //#endregion
3125
3267
  //#region src/schema-compiler.ts
3126
- const UNSAFE_TARGETS = [
3268
+ const UNSAFE_TARGETS = /* @__PURE__ */ new Set([
3127
3269
  Object.prototype,
3128
3270
  Function.prototype,
3129
3271
  Array.prototype
3130
- ];
3272
+ ]);
3131
3273
  /** Returns true if `obj` is a built-in prototype that must not be mutated. */
3132
3274
  function isUnsafeTarget(obj) {
3133
- return UNSAFE_TARGETS.includes(obj);
3275
+ return UNSAFE_TARGETS.has(obj);
3134
3276
  }
3135
3277
  /** Safely assign a property on `obj`, refusing prototype-polluting keys. */
3136
3278
  function safeSetProperty(obj, key, value) {
@@ -3143,35 +3285,81 @@ function safeDeleteProperty(obj, key) {
3143
3285
  if (isUnsafeTarget(obj)) return;
3144
3286
  if (key !== "__proto__" && key !== "constructor" && key !== "prototype") delete obj[key];
3145
3287
  }
3288
+ const resolveReference = (base, ref) => {
3289
+ if (isAbsoluteUri(ref)) return ref;
3290
+ const baseStr = base ?? "";
3291
+ if (ref.startsWith("#")) {
3292
+ const hashIndex = baseStr.indexOf("#");
3293
+ return (hashIndex === -1 ? baseStr : baseStr.slice(0, hashIndex)) + ref;
3294
+ }
3295
+ if (!baseStr) return ref;
3296
+ const hashIndex = baseStr.indexOf("#");
3297
+ const baseNoFrag = hashIndex === -1 ? baseStr : baseStr.slice(0, hashIndex);
3298
+ if (isAbsoluteUri(baseNoFrag)) try {
3299
+ return new URL(ref, baseNoFrag).toString();
3300
+ } catch {}
3301
+ let baseDir = baseNoFrag;
3302
+ if (!baseDir.endsWith("/")) {
3303
+ const lastSlash = baseDir.lastIndexOf("/");
3304
+ baseDir = lastSlash === -1 ? "" : baseDir.slice(0, lastSlash + 1);
3305
+ }
3306
+ return baseDir + ref;
3307
+ };
3308
+ const isSimpleIdentifier = (id) => !id.startsWith("#") && !id.includes("/") && !id.includes(".") && !id.includes("#");
3309
+ const resolveIdScope = (base, id) => {
3310
+ if (isAbsoluteUri(id)) return id;
3311
+ const baseStr = base ?? "";
3312
+ if (isSimpleIdentifier(id)) {
3313
+ const hashIndex = baseStr.indexOf("#");
3314
+ return `${hashIndex === -1 ? baseStr : baseStr.slice(0, hashIndex)}#${id}`;
3315
+ }
3316
+ return resolveReference(base, id);
3317
+ };
3318
+ const resolveSchemaScopeId = (base, schema, id) => {
3319
+ if (typeof schema.$id === "string") return resolveReference(base, id);
3320
+ return resolveIdScope(base, id);
3321
+ };
3146
3322
  const collectIds = (obj, maxDepth = 100) => {
3147
3323
  const ids = [];
3148
3324
  function walk(node, scope, _depth = 0) {
3149
3325
  if (typeof node !== "object" || node == null) return;
3326
+ const schemaNode = node;
3150
3327
  if (_depth >= maxDepth) throw new Error(`Maximum recursion depth (${maxDepth}) exceeded in collectIds. If your schema is deeply nested and valid, increase the maxRecursionDepth option.`);
3151
3328
  let addedScope = false;
3152
- const nodeId = getId(node);
3329
+ const nodeId = getId(schemaNode);
3153
3330
  if (typeof nodeId === "string") {
3154
3331
  let type = isAbsoluteUri(nodeId) ? "absolute" : "relative";
3155
3332
  if (scope.length === 0) type = "root";
3156
3333
  const id = {
3157
3334
  id: nodeId,
3158
3335
  type,
3159
- obj: node
3336
+ obj: schemaNode
3160
3337
  };
3161
3338
  if (type === "absolute" || type === "root" && isAbsoluteUri(nodeId)) id.absoluteUri = nodeId;
3162
- else if (type === "root" && typeof node.id === "string" && isAbsoluteUri(node.id) && node.id !== nodeId) id.absoluteUri = resolveSchemaScopeId(node.id, node, nodeId);
3339
+ else if (type === "root" && typeof schemaNode.id === "string" && isAbsoluteUri(schemaNode.id) && schemaNode.id !== nodeId) id.absoluteUri = resolveSchemaScopeId(schemaNode.id, schemaNode, nodeId);
3163
3340
  else if (type === "relative") {
3164
- id.absoluteParent = scope.filter((x) => x.type === "absolute" || x.type === "root" && x.absoluteUri).slice(-1)[0];
3165
- if (id.absoluteParent) id.absoluteUri = resolveSchemaScopeId(id.absoluteParent.absoluteUri || id.absoluteParent.id, node, id.id);
3341
+ let absoluteParent;
3342
+ for (let i = scope.length - 1; i >= 0; i--) {
3343
+ const sc = scope[i];
3344
+ if (sc.type === "absolute" || sc.type === "root" && sc.absoluteUri) {
3345
+ absoluteParent = sc;
3346
+ break;
3347
+ }
3348
+ }
3349
+ id.absoluteParent = absoluteParent;
3350
+ if (id.absoluteParent) {
3351
+ const parentUri = id.absoluteParent.absoluteUri || id.absoluteParent.id;
3352
+ id.absoluteUri = resolveSchemaScopeId(parentUri, schemaNode, id.id);
3353
+ }
3166
3354
  }
3167
3355
  ids.push(id);
3168
3356
  scope.push(id);
3169
3357
  addedScope = true;
3170
3358
  }
3171
3359
  if (Array.isArray(node)) for (const item of node) walk(item, scope, _depth + 1);
3172
- else for (const key of Object.keys(node)) {
3173
- if (isInternalKey(key) || NON_SCHEMA_KEYWORDS.includes(key)) continue;
3174
- walk(node[key], scope, _depth + 1);
3360
+ else for (const key of Object.keys(schemaNode)) {
3361
+ if (isInternalKey(key) || NON_SCHEMA_KEYWORDS_SET.has(key)) continue;
3362
+ walk(schemaNode[key], scope, _depth + 1);
3175
3363
  }
3176
3364
  if (addedScope) scope.pop();
3177
3365
  }
@@ -3179,42 +3367,42 @@ const collectIds = (obj, maxDepth = 100) => {
3179
3367
  return ids;
3180
3368
  };
3181
3369
  const collectReferences = (obj, results, scope, path, options, maxDepth = 100, _depth = 0) => {
3182
- results = results || [];
3183
- scope = scope || [];
3184
- path = path || [];
3185
- options = options || {};
3370
+ results ||= [];
3371
+ scope ||= [];
3372
+ path ||= [];
3373
+ options ||= {};
3186
3374
  if (typeof obj !== "object" || obj === null) return results;
3187
3375
  if (_depth >= maxDepth) throw new Error(`Maximum recursion depth (${maxDepth}) exceeded in collectReferences. If your schema is deeply nested and valid, increase the maxRecursionDepth option.`);
3188
- const hasRef = typeof obj.$ref === "string" && typeof obj.__$refResolved === "undefined";
3376
+ const hasRef = typeof obj.$ref === "string" && obj.__$refResolved === void 0;
3189
3377
  let addedScope = false;
3190
3378
  const isRootScope = scope.length === 0;
3191
3379
  let scopeId = getId(obj);
3192
3380
  if (typeof obj.id === "string" && isAbsoluteUri(obj.id) && (!scopeId || !isAbsoluteUri(scopeId))) scopeId = obj.id;
3193
3381
  if (typeof scopeId === "string" && (isRootScope || !hasRef || options.useRefObjectScope === true)) {
3194
- const base = scope.length > 0 ? scope[scope.length - 1] : void 0;
3382
+ const base = scope.length > 0 ? scope.at(-1) : void 0;
3195
3383
  scope.push(resolveSchemaScopeId(base, obj, scopeId));
3196
3384
  addedScope = true;
3197
3385
  }
3198
3386
  if (hasRef) results.push({
3199
- ref: resolveReference(scope[scope.length - 1], obj.$ref),
3387
+ ref: resolveReference(scope.at(-1), obj.$ref),
3200
3388
  key: "$ref",
3201
3389
  obj,
3202
3390
  path: path.slice(0)
3203
3391
  });
3204
- if (typeof obj.$recursiveRef === "string" && typeof obj.__$recursiveRefResolved === "undefined") results.push({
3205
- ref: resolveReference(scope[scope.length - 1], obj.$recursiveRef),
3392
+ if (typeof obj.$recursiveRef === "string" && obj.__$recursiveRefResolved === void 0) results.push({
3393
+ ref: resolveReference(scope.at(-1), obj.$recursiveRef),
3206
3394
  key: "$recursiveRef",
3207
3395
  obj,
3208
3396
  path: path.slice(0)
3209
3397
  });
3210
- if (typeof obj.$dynamicRef === "string" && typeof obj.__$dynamicRefResolved === "undefined") results.push({
3211
- ref: resolveReference(scope[scope.length - 1], obj.$dynamicRef),
3398
+ if (typeof obj.$dynamicRef === "string" && obj.__$dynamicRefResolved === void 0) results.push({
3399
+ ref: resolveReference(scope.at(-1), obj.$dynamicRef),
3212
3400
  key: "$dynamicRef",
3213
3401
  obj,
3214
3402
  path: path.slice(0)
3215
3403
  });
3216
- if (typeof obj.$schema === "string" && typeof obj.__$schemaResolved === "undefined") results.push({
3217
- ref: resolveReference(scope[scope.length - 1], obj.$schema),
3404
+ if (typeof obj.$schema === "string" && obj.__$schemaResolved === void 0) results.push({
3405
+ ref: resolveReference(scope.at(-1), obj.$schema),
3218
3406
  key: "$schema",
3219
3407
  obj,
3220
3408
  path: path.slice(0)
@@ -3227,7 +3415,7 @@ const collectReferences = (obj, results, scope, path, options, maxDepth = 100, _
3227
3415
  else {
3228
3416
  const keys = Object.keys(obj);
3229
3417
  for (const key of keys) {
3230
- if (isInternalKey(key) || NON_SCHEMA_KEYWORDS.includes(key)) continue;
3418
+ if (isInternalKey(key) || NON_SCHEMA_KEYWORDS_SET.has(key)) continue;
3231
3419
  path.push(key);
3232
3420
  collectReferences(obj[key], results, scope, path, options, maxDepth, _depth + 1);
3233
3421
  path.pop();
@@ -3236,41 +3424,8 @@ const collectReferences = (obj, results, scope, path, options, maxDepth = 100, _
3236
3424
  if (addedScope) scope.pop();
3237
3425
  return results;
3238
3426
  };
3239
- const resolveReference = (base, ref) => {
3240
- if (isAbsoluteUri(ref)) return ref;
3241
- const baseStr = base ?? "";
3242
- if (ref[0] === "#") {
3243
- const hashIndex = baseStr.indexOf("#");
3244
- return (hashIndex === -1 ? baseStr : baseStr.slice(0, hashIndex)) + ref;
3245
- }
3246
- if (!baseStr) return ref;
3247
- const hashIndex = baseStr.indexOf("#");
3248
- const baseNoFrag = hashIndex === -1 ? baseStr : baseStr.slice(0, hashIndex);
3249
- if (isAbsoluteUri(baseNoFrag)) try {
3250
- return new URL(ref, baseNoFrag).toString();
3251
- } catch {}
3252
- let baseDir = baseNoFrag;
3253
- if (!baseDir.endsWith("/")) {
3254
- const lastSlash = baseDir.lastIndexOf("/");
3255
- baseDir = lastSlash === -1 ? "" : baseDir.slice(0, lastSlash + 1);
3256
- }
3257
- return baseDir + ref;
3258
- };
3259
- const isSimpleIdentifier = (id) => id[0] !== "#" && !id.includes("/") && !id.includes(".") && !id.includes("#");
3260
- const resolveIdScope = (base, id) => {
3261
- if (isAbsoluteUri(id)) return id;
3262
- const baseStr = base ?? "";
3263
- if (isSimpleIdentifier(id)) {
3264
- const hashIndex = baseStr.indexOf("#");
3265
- return (hashIndex === -1 ? baseStr : baseStr.slice(0, hashIndex)) + "#" + id;
3266
- }
3267
- return resolveReference(base, id);
3268
- };
3269
- const resolveSchemaScopeId = (base, schema, id) => {
3270
- if (typeof schema.$id === "string") return resolveReference(base, id);
3271
- return resolveIdScope(base, id);
3272
- };
3273
3427
  var SchemaCompiler = class {
3428
+ validator;
3274
3429
  constructor(validator) {
3275
3430
  this.validator = validator;
3276
3431
  }
@@ -3279,7 +3434,8 @@ var SchemaCompiler = class {
3279
3434
  for (const item of ids) if (item.absoluteUri) {
3280
3435
  this.validator.scache.cacheSchemaByUri(item.absoluteUri, item.obj);
3281
3436
  if (item.type === "relative" && item.absoluteParent && isSimpleIdentifier(item.id)) {
3282
- const altAbsoluteUri = resolveReference(item.absoluteParent.absoluteUri || item.absoluteParent.id, item.id);
3437
+ const parentUri = item.absoluteParent.absoluteUri || item.absoluteParent.id;
3438
+ const altAbsoluteUri = resolveReference(parentUri, item.id);
3283
3439
  this.validator.scache.cacheSchemaByUri(altAbsoluteUri, item.obj);
3284
3440
  }
3285
3441
  } else if (item.type === "root") this.validator.scache.cacheSchemaByUri(item.id, item.obj);
@@ -3288,19 +3444,19 @@ var SchemaCompiler = class {
3288
3444
  report.commonErrorMessage = "SCHEMA_COMPILATION_FAILED";
3289
3445
  if (typeof schema === "string") {
3290
3446
  const loadedSchema = this.validator.scache.getSchemaByUri(report, schema);
3291
- if (typeof loadedSchema === "undefined") {
3447
+ if (loadedSchema === void 0) {
3292
3448
  report.addError("SCHEMA_NOT_REACHABLE", [schema]);
3293
3449
  return false;
3294
3450
  }
3295
3451
  schema = loadedSchema;
3296
3452
  }
3297
3453
  if (Array.isArray(schema)) {
3298
- if (!options?.noCache) schema.forEach((s) => this.collectAndCacheIds(s));
3454
+ if (!options?.noCache) for (let i = 0; i < schema.length; i++) this.collectAndCacheIds(schema[i]);
3299
3455
  return this.compileArrayOfSchemas(report, schema);
3300
3456
  } else if (typeof schema === "boolean") return true;
3301
- else if (!options?.noCache) this.collectAndCacheIds(schema);
3457
+ if (!options?.noCache) this.collectAndCacheIds(schema);
3302
3458
  const canMutateSchemaObject = schema !== Object.prototype && schema !== Function.prototype && schema !== Array.prototype;
3303
- if (canMutateSchemaObject && schema.__$compiled && schema.id && this.validator.scache.checkCacheForUri(schema.id) === false) schema.__$compiled = void 0;
3459
+ if (canMutateSchemaObject && schema.__$compiled && schema.id && !this.validator.scache.checkCacheForUri(schema.id)) schema.__$compiled = void 0;
3304
3460
  if (schema.__$compiled) return true;
3305
3461
  if (canMutateSchemaObject && !schema.$schema && this.validator.options.version !== "none") schema.$schema = this.validator.getDefaultSchemaId();
3306
3462
  if (schema.id && typeof schema.id === "string" && !options?.noCache) this.validator.scache.cacheSchemaByUri(schema.id, schema);
@@ -3315,7 +3471,7 @@ var SchemaCompiler = class {
3315
3471
  const refs = collectReferences(schema, void 0, void 0, void 0, { useRefObjectScope }, this.validator.options.maxRecursionDepth);
3316
3472
  for (const refObj of refs) {
3317
3473
  let response = this.validator.scache.getSchemaByUri(report, refObj.ref, schema);
3318
- if (typeof response === "undefined") {
3474
+ if (response === void 0) {
3319
3475
  const schemaReader = getSchemaReader();
3320
3476
  if (schemaReader) {
3321
3477
  const remotePath = getRemotePath(refObj.ref);
@@ -3323,23 +3479,24 @@ var SchemaCompiler = class {
3323
3479
  if (s) {
3324
3480
  s.id = remotePath;
3325
3481
  const subreport = new Report(report);
3326
- if (!this.compileSchema(subreport, s)) report.errors = report.errors.concat(subreport.errors);
3327
- else response = this.validator.scache.getSchemaByUri(report, refObj.ref, schema);
3482
+ if (this.compileSchema(subreport, s)) response = this.validator.scache.getSchemaByUri(report, refObj.ref, schema);
3483
+ else for (let i = 0; i < subreport.errors.length; i++) report.errors.push(subreport.errors[i]);
3328
3484
  }
3329
3485
  }
3330
3486
  }
3331
- if (typeof response === "undefined") {
3487
+ if (response === void 0) {
3332
3488
  const hasNotValid = report.hasError("REMOTE_NOT_VALID", [refObj.ref]);
3333
3489
  const isAbsolute = isAbsoluteUri(refObj.ref);
3334
3490
  let isDownloaded = false;
3335
3491
  const ignoreUnresolvableRemotes = this.validator.options.ignoreUnresolvableReferences === true;
3336
3492
  if (isAbsolute) isDownloaded = this.validator.scache.checkCacheForUri(refObj.ref);
3337
3493
  if (hasNotValid) {} else if (ignoreUnresolvableRemotes && isAbsolute) {} else if (isDownloaded) {} else {
3338
- report.path.push(...refObj.path);
3494
+ const pathLen = refObj.path.length;
3495
+ for (let i = 0; i < pathLen; i++) report.path.push(refObj.path[i]);
3339
3496
  report.addError("UNRESOLVABLE_REFERENCE", [refObj.ref]);
3340
- report.path = report.path.slice(0, -refObj.path.length);
3497
+ report.path.length -= pathLen;
3341
3498
  if (isValidExceptReferences && canMutateSchemaObject && !isUnsafeTarget(schema)) {
3342
- schema.__$missingReferences = schema.__$missingReferences || [];
3499
+ schema.__$missingReferences ||= [];
3343
3500
  schema.__$missingReferences.push(refObj);
3344
3501
  }
3345
3502
  }
@@ -3354,13 +3511,20 @@ var SchemaCompiler = class {
3354
3511
  compileArrayOfSchemas(report, arr) {
3355
3512
  let compiled = 0, lastLoopCompiled;
3356
3513
  do {
3357
- report.errors = report.errors.filter((e) => e.code !== "UNRESOLVABLE_REFERENCE");
3514
+ let wi = 0;
3515
+ for (let ri = 0; ri < report.errors.length; ri++) if (report.errors[ri].code !== "UNRESOLVABLE_REFERENCE") report.errors[wi++] = report.errors[ri];
3516
+ report.errors.length = wi;
3358
3517
  lastLoopCompiled = compiled;
3359
3518
  compiled = this.compileArrayOfSchemasLoop(report, arr);
3519
+ const idMap = /* @__PURE__ */ new Map();
3520
+ for (let i = 0; i < arr.length; i++) {
3521
+ const schemaId = arr[i].id;
3522
+ if (schemaId && !idMap.has(schemaId)) idMap.set(schemaId, arr[i]);
3523
+ }
3360
3524
  for (const sch of arr) if (sch.__$missingReferences) {
3361
3525
  for (let idx2 = sch.__$missingReferences.length - 1; idx2 >= 0; idx2--) {
3362
3526
  const refObj = sch.__$missingReferences[idx2];
3363
- const response = arr.find((x) => x.id === refObj.ref);
3527
+ const response = idMap.get(refObj.ref);
3364
3528
  if (response) {
3365
3529
  safeSetProperty(refObj.obj, `__${refObj.key}Resolved`, response);
3366
3530
  sch.__$missingReferences.splice(idx2, 1);
@@ -3376,62 +3540,74 @@ var SchemaCompiler = class {
3376
3540
  for (const schema of arr) {
3377
3541
  const report = new Report(mainReport);
3378
3542
  if (this.compileSchema(report, schema)) compiledCount++;
3379
- mainReport.errors = mainReport.errors.concat(report.errors);
3543
+ for (let i = 0; i < report.errors.length; i++) mainReport.errors.push(report.errors[i]);
3380
3544
  }
3381
3545
  return compiledCount;
3382
3546
  }
3383
3547
  };
3384
3548
  //#endregion
3385
3549
  //#region src/schema-validator.ts
3550
+ const PRIMITIVE_TYPES = [
3551
+ "array",
3552
+ "boolean",
3553
+ "integer",
3554
+ "number",
3555
+ "null",
3556
+ "object",
3557
+ "string"
3558
+ ];
3559
+ const PRIMITIVE_TYPE_STR = PRIMITIVE_TYPES.join(",");
3560
+ const PRIMITIVE_TYPES_SET = new Set(PRIMITIVE_TYPES);
3386
3561
  const SchemaValidators = {
3387
- $ref: function(report, schema) {
3562
+ $ref(report, schema) {
3388
3563
  if (typeof schema.$ref !== "string") report.addError("KEYWORD_TYPE_EXPECTED", ["$ref", "string"], void 0, schema, "$ref");
3389
3564
  },
3390
- $schema: function(report, schema) {
3565
+ $schema(report, schema) {
3391
3566
  if (typeof schema.$schema !== "string") report.addError("KEYWORD_TYPE_EXPECTED", ["$schema", "string"], void 0, schema, "$schema");
3392
3567
  },
3393
- multipleOf: function(report, schema) {
3568
+ multipleOf(report, schema) {
3394
3569
  if (typeof schema.multipleOf !== "number") report.addError("KEYWORD_TYPE_EXPECTED", ["multipleOf", "number"], void 0, schema, "multipleOf");
3395
3570
  else if (schema.multipleOf <= 0) report.addError("KEYWORD_MUST_BE", ["multipleOf", "strictly greater than 0"], void 0, schema, "multipleOf");
3396
3571
  },
3397
- maximum: function(report, schema) {
3572
+ maximum(report, schema) {
3398
3573
  if (typeof schema.maximum !== "number") report.addError("KEYWORD_TYPE_EXPECTED", ["maximum", "number"], void 0, schema, "maximum");
3399
3574
  },
3400
- exclusiveMaximum: function(report, schema) {
3575
+ exclusiveMaximum(report, schema) {
3401
3576
  if (report.options.version === "draft-04") {
3402
3577
  if (typeof schema.exclusiveMaximum !== "boolean") report.addError("KEYWORD_TYPE_EXPECTED", ["exclusiveMaximum", "boolean"], void 0, schema, "exclusiveMaximum");
3403
3578
  else if (schema.maximum === void 0) report.addError("KEYWORD_DEPENDENCY", ["exclusiveMaximum", "maximum"], void 0, schema, "exclusiveMaximum");
3404
3579
  } else if (typeof schema.exclusiveMaximum !== "boolean" && typeof schema.exclusiveMaximum !== "number") report.addError("KEYWORD_TYPE_EXPECTED", ["exclusiveMaximum", ["boolean", "number"]], void 0, schema, "exclusiveMaximum");
3405
3580
  },
3406
- minimum: function(report, schema) {
3581
+ minimum(report, schema) {
3407
3582
  if (typeof schema.minimum !== "number") report.addError("KEYWORD_TYPE_EXPECTED", ["minimum", "number"], void 0, schema, "minimum");
3408
3583
  },
3409
- exclusiveMinimum: function(report, schema) {
3584
+ exclusiveMinimum(report, schema) {
3410
3585
  if (report.options.version === "draft-04") {
3411
3586
  if (typeof schema.exclusiveMinimum !== "boolean") report.addError("KEYWORD_TYPE_EXPECTED", ["exclusiveMinimum", "boolean"], void 0, schema, "exclusiveMinimum");
3412
3587
  else if (schema.minimum === void 0) report.addError("KEYWORD_DEPENDENCY", ["exclusiveMinimum", "minimum"], void 0, schema, "exclusiveMinimum");
3413
3588
  } else if (typeof schema.exclusiveMinimum !== "boolean" && typeof schema.exclusiveMinimum !== "number") report.addError("KEYWORD_TYPE_EXPECTED", ["exclusiveMinimum", ["boolean", "number"]], void 0, schema, "exclusiveMinimum");
3414
3589
  },
3415
- maxLength: function(report, schema) {
3590
+ maxLength(report, schema) {
3416
3591
  if (!isInteger(schema.maxLength)) report.addError("KEYWORD_TYPE_EXPECTED", ["maxLength", "integer"], void 0, schema, "maxLength");
3417
3592
  else if (schema.maxLength < 0) report.addError("KEYWORD_MUST_BE", ["maxLength", "greater than, or equal to 0"], void 0, schema, "maxLength");
3418
3593
  },
3419
- minLength: function(report, schema) {
3594
+ minLength(report, schema) {
3420
3595
  if (!isInteger(schema.minLength)) report.addError("KEYWORD_TYPE_EXPECTED", ["minLength", "integer"], void 0, schema, "minLength");
3421
3596
  else if (schema.minLength < 0) report.addError("KEYWORD_MUST_BE", ["minLength", "greater than, or equal to 0"], void 0, schema, "minLength");
3422
3597
  },
3423
- pattern: function(report, schema) {
3424
- if (typeof schema.pattern !== "string") report.addError("KEYWORD_TYPE_EXPECTED", ["pattern", "string"], void 0, schema, "pattern");
3425
- else {
3426
- const result = compileSchemaRegex(schema.pattern);
3427
- if (!result.ok) report.addError("KEYWORD_PATTERN", [
3428
- "pattern",
3429
- schema.pattern,
3430
- result.error.message
3431
- ], void 0, schema, "pattern");
3598
+ pattern(report, schema) {
3599
+ if (typeof schema.pattern !== "string") {
3600
+ report.addError("KEYWORD_TYPE_EXPECTED", ["pattern", "string"], void 0, schema, "pattern");
3601
+ return;
3432
3602
  }
3603
+ const result = compileSchemaRegex(schema.pattern);
3604
+ if (!result.ok) report.addError("KEYWORD_PATTERN", [
3605
+ "pattern",
3606
+ schema.pattern,
3607
+ result.error.message
3608
+ ], void 0, schema, "pattern");
3433
3609
  },
3434
- additionalItems: function(report, schema) {
3610
+ additionalItems(report, schema) {
3435
3611
  if (typeof schema.additionalItems !== "boolean" && !isObject(schema.additionalItems)) report.addError("KEYWORD_TYPE_EXPECTED", ["additionalItems", ["boolean", "object"]], void 0, schema, "additionalItems");
3436
3612
  else if (isObject(schema.additionalItems)) {
3437
3613
  report.path.push("additionalItems");
@@ -3439,7 +3615,7 @@ const SchemaValidators = {
3439
3615
  report.path.pop();
3440
3616
  }
3441
3617
  },
3442
- items: function(report, schema) {
3618
+ items(report, schema) {
3443
3619
  if (Array.isArray(schema.items)) for (let idx = 0; idx < schema.items.length; idx++) {
3444
3620
  report.path.push("items");
3445
3621
  report.path.push(idx);
@@ -3459,34 +3635,34 @@ const SchemaValidators = {
3459
3635
  if (this.options.forceAdditional === true && schema.additionalItems === void 0 && Array.isArray(schema.items)) report.addError("KEYWORD_UNDEFINED_STRICT", ["additionalItems"], void 0, schema, "additionalItems");
3460
3636
  if (this.options.assumeAdditional && schema.additionalItems === void 0 && Array.isArray(schema.items)) schema.additionalItems = false;
3461
3637
  },
3462
- maxItems: function(report, schema) {
3638
+ maxItems(report, schema) {
3463
3639
  if (typeof schema.maxItems !== "number") report.addError("KEYWORD_TYPE_EXPECTED", ["maxItems", "integer"], void 0, schema, "maxItems");
3464
3640
  else if (schema.maxItems < 0) report.addError("KEYWORD_MUST_BE", ["maxItems", "greater than, or equal to 0"], void 0, schema, "maxItems");
3465
3641
  },
3466
- minItems: function(report, schema) {
3642
+ minItems(report, schema) {
3467
3643
  if (!isInteger(schema.minItems)) report.addError("KEYWORD_TYPE_EXPECTED", ["minItems", "integer"], void 0, schema, "minItems");
3468
3644
  else if (schema.minItems < 0) report.addError("KEYWORD_MUST_BE", ["minItems", "greater than, or equal to 0"], void 0, schema, "minItems");
3469
3645
  },
3470
- uniqueItems: function(report, schema) {
3646
+ uniqueItems(report, schema) {
3471
3647
  if (typeof schema.uniqueItems !== "boolean") report.addError("KEYWORD_TYPE_EXPECTED", ["uniqueItems", "boolean"], void 0, schema, "uniqueItems");
3472
3648
  },
3473
- maxProperties: function(report, schema) {
3649
+ maxProperties(report, schema) {
3474
3650
  if (!isInteger(schema.maxProperties)) report.addError("KEYWORD_TYPE_EXPECTED", ["maxProperties", "integer"], void 0, schema, "maxProperties");
3475
3651
  else if (schema.maxProperties < 0) report.addError("KEYWORD_MUST_BE", ["maxProperties", "greater than, or equal to 0"], void 0, schema, "maxProperties");
3476
3652
  },
3477
- minProperties: function(report, schema) {
3653
+ minProperties(report, schema) {
3478
3654
  if (!isInteger(schema.minProperties)) report.addError("KEYWORD_TYPE_EXPECTED", ["minProperties", "integer"], void 0, schema, "minProperties");
3479
3655
  else if (schema.minProperties < 0) report.addError("KEYWORD_MUST_BE", ["minProperties", "greater than, or equal to 0"], void 0, schema, "minProperties");
3480
3656
  },
3481
- required: function(report, schema) {
3657
+ required(report, schema) {
3482
3658
  if (!Array.isArray(schema.required)) report.addError("KEYWORD_TYPE_EXPECTED", ["required", "array"], void 0, schema, "required");
3483
3659
  else if (report.options.version === "draft-04" && schema.required.length === 0) report.addError("KEYWORD_MUST_BE", ["required", "an array with at least one element"], void 0, schema, "required");
3484
3660
  else {
3485
3661
  for (const item of schema.required) if (typeof item !== "string") report.addError("KEYWORD_VALUE_TYPE", ["required", "string"], void 0, schema, "required");
3486
- if (isUniqueArray(schema.required) === false) report.addError("KEYWORD_MUST_BE", ["required", "an array with unique items"], void 0, schema, "required");
3662
+ if (!isUniqueArray(schema.required)) report.addError("KEYWORD_MUST_BE", ["required", "an array with unique items"], void 0, schema, "required");
3487
3663
  }
3488
3664
  },
3489
- additionalProperties: function(report, schema) {
3665
+ additionalProperties(report, schema) {
3490
3666
  if (typeof schema.additionalProperties !== "boolean" && !isObject(schema.additionalProperties)) report.addError("KEYWORD_TYPE_EXPECTED", ["additionalProperties", ["boolean", "object"]], void 0, schema, "additionalProperties");
3491
3667
  else if (isObject(schema.additionalProperties)) {
3492
3668
  report.path.push("additionalProperties");
@@ -3494,7 +3670,7 @@ const SchemaValidators = {
3494
3670
  report.path.pop();
3495
3671
  }
3496
3672
  },
3497
- properties: function(report, schema) {
3673
+ properties(report, schema) {
3498
3674
  if (!isObject(schema.properties)) {
3499
3675
  report.addError("KEYWORD_TYPE_EXPECTED", ["properties", "object"], void 0, schema, "properties");
3500
3676
  return;
@@ -3512,7 +3688,7 @@ const SchemaValidators = {
3512
3688
  if (this.options.assumeAdditional && schema.additionalProperties === void 0) schema.additionalProperties = false;
3513
3689
  if (this.options.forceProperties === true && keys.length === 0) report.addError("CUSTOM_MODE_FORCE_PROPERTIES", ["properties"], void 0, schema, "properties");
3514
3690
  },
3515
- patternProperties: function(report, schema) {
3691
+ patternProperties(report, schema) {
3516
3692
  if (!isObject(schema.patternProperties)) {
3517
3693
  report.addError("KEYWORD_TYPE_EXPECTED", ["patternProperties", "object"], void 0, schema, "patternProperties");
3518
3694
  return;
@@ -3534,93 +3710,52 @@ const SchemaValidators = {
3534
3710
  }
3535
3711
  if (this.options.forceProperties === true && keys.length === 0) report.addError("CUSTOM_MODE_FORCE_PROPERTIES", ["patternProperties"], void 0, schema, "patternProperties");
3536
3712
  },
3537
- dependencies: function(report, schema) {
3538
- if (!isObject(schema.dependencies)) report.addError("KEYWORD_TYPE_EXPECTED", ["dependencies", "object"], void 0, schema, "dependencies");
3539
- else {
3540
- const keys = Object.keys(schema.dependencies);
3541
- for (const schemaKey of keys) {
3542
- const schemaDependency = schema.dependencies[schemaKey];
3543
- if (isObject(schemaDependency) || report.options.version !== "draft-04" && typeof schemaDependency === "boolean") {
3544
- report.path.push("dependencies");
3545
- report.path.push(schemaKey);
3546
- this.validateSchema(report, schemaDependency);
3547
- report.path.pop();
3548
- report.path.pop();
3549
- } else if (Array.isArray(schemaDependency)) {
3550
- const depArray = schemaDependency;
3551
- if (report.options.version === "draft-04" && depArray.length === 0) report.addError("KEYWORD_MUST_BE", ["dependencies", "not empty array"], void 0, schema, "dependencies");
3552
- for (const dep of depArray) if (typeof dep !== "string") report.addError("KEYWORD_VALUE_TYPE", ["dependencies", "string"], void 0, schema, "dependencies");
3553
- if (isUniqueArray(depArray) === false) report.addError("KEYWORD_MUST_BE", ["dependencies", "an array with unique items"], void 0, schema, "dependencies");
3554
- } else report.addError("KEYWORD_VALUE_TYPE", ["dependencies", report.options.version === "draft-04" ? "object or array" : "boolean, object or array"], void 0, schema, "dependencies");
3555
- }
3713
+ dependencies(report, schema) {
3714
+ if (!isObject(schema.dependencies)) {
3715
+ report.addError("KEYWORD_TYPE_EXPECTED", ["dependencies", "object"], void 0, schema, "dependencies");
3716
+ return;
3717
+ }
3718
+ const keys = Object.keys(schema.dependencies);
3719
+ for (const schemaKey of keys) {
3720
+ const schemaDependency = schema.dependencies[schemaKey];
3721
+ if (isObject(schemaDependency) || report.options.version !== "draft-04" && typeof schemaDependency === "boolean") {
3722
+ report.path.push("dependencies");
3723
+ report.path.push(schemaKey);
3724
+ this.validateSchema(report, schemaDependency);
3725
+ report.path.pop();
3726
+ report.path.pop();
3727
+ } else if (Array.isArray(schemaDependency)) {
3728
+ const depArray = schemaDependency;
3729
+ if (report.options.version === "draft-04" && depArray.length === 0) report.addError("KEYWORD_MUST_BE", ["dependencies", "not empty array"], void 0, schema, "dependencies");
3730
+ for (const dep of depArray) if (typeof dep !== "string") report.addError("KEYWORD_VALUE_TYPE", ["dependencies", "string"], void 0, schema, "dependencies");
3731
+ if (!isUniqueArray(depArray)) report.addError("KEYWORD_MUST_BE", ["dependencies", "an array with unique items"], void 0, schema, "dependencies");
3732
+ } else report.addError("KEYWORD_VALUE_TYPE", ["dependencies", report.options.version === "draft-04" ? "object or array" : "boolean, object or array"], void 0, schema, "dependencies");
3556
3733
  }
3557
3734
  },
3558
- enum: function(report, schema) {
3559
- if (Array.isArray(schema.enum) === false) report.addError("KEYWORD_TYPE_EXPECTED", ["enum", "array"], void 0, schema, "enum");
3735
+ enum(report, schema) {
3736
+ if (!Array.isArray(schema.enum)) report.addError("KEYWORD_TYPE_EXPECTED", ["enum", "array"], void 0, schema, "enum");
3560
3737
  else if (schema.enum.length === 0) report.addError("KEYWORD_MUST_BE", ["enum", "an array with at least one element"], void 0, schema, "enum");
3561
- else if (isUniqueArray(schema.enum) === false) report.addError("KEYWORD_MUST_BE", ["enum", "an array with unique elements"], void 0, schema, "enum");
3738
+ else if (!isUniqueArray(schema.enum)) report.addError("KEYWORD_MUST_BE", ["enum", "an array with unique elements"], void 0, schema, "enum");
3562
3739
  },
3563
- type: function(report, schema) {
3564
- const primitiveTypes = [
3565
- "array",
3566
- "boolean",
3567
- "integer",
3568
- "number",
3569
- "null",
3570
- "object",
3571
- "string"
3572
- ];
3573
- const primitiveTypeStr = primitiveTypes.join(",");
3740
+ type(report, schema) {
3574
3741
  const isArray = Array.isArray(schema.type);
3575
3742
  if (Array.isArray(schema.type)) {
3576
- for (const typeItem of schema.type) if (!primitiveTypes.includes(typeItem)) report.addError("KEYWORD_TYPE_EXPECTED", ["type", primitiveTypeStr], void 0, schema, "type");
3577
- if (isUniqueArray(schema.type) === false) report.addError("KEYWORD_MUST_BE", ["type", "an object with unique properties"], void 0, schema, "type");
3743
+ for (const typeItem of schema.type) if (!PRIMITIVE_TYPES_SET.has(typeItem)) report.addError("KEYWORD_TYPE_EXPECTED", ["type", PRIMITIVE_TYPE_STR], void 0, schema, "type");
3744
+ if (!isUniqueArray(schema.type)) report.addError("KEYWORD_MUST_BE", ["type", "an object with unique properties"], void 0, schema, "type");
3578
3745
  } else if (typeof schema.type === "string") {
3579
- if (!primitiveTypes.includes(schema.type)) report.addError("KEYWORD_TYPE_EXPECTED", ["type", primitiveTypeStr], void 0, schema, "type");
3746
+ if (!PRIMITIVE_TYPES_SET.has(schema.type)) report.addError("KEYWORD_TYPE_EXPECTED", ["type", PRIMITIVE_TYPE_STR], void 0, schema, "type");
3580
3747
  } else report.addError("KEYWORD_TYPE_EXPECTED", ["type", ["string", "array"]], void 0, schema, "type");
3581
- if (this.options.noEmptyStrings === true) {
3582
- if (schema.type === "string" || isArray && schema.type.includes("string")) {
3583
- if (schema.minLength === void 0 && schema.enum === void 0 && schema.format === void 0) schema.minLength = 1;
3584
- }
3585
- }
3586
- if (this.options.noEmptyArrays === true) {
3587
- if (schema.type === "array" || isArray && schema.type.includes("array")) {
3588
- if (schema.minItems === void 0) schema.minItems = 1;
3589
- }
3590
- }
3591
- if (this.options.forceProperties === true) {
3592
- if (schema.type === "object" || isArray && schema.type.includes("object")) {
3593
- if (schema.properties === void 0 && schema.patternProperties === void 0) report.addError("KEYWORD_UNDEFINED_STRICT", ["properties"], void 0, schema, "properties");
3594
- }
3595
- }
3596
- if (this.options.forceItems === true) {
3597
- if (schema.type === "array" || isArray && schema.type.includes("array")) {
3598
- if (schema.items === void 0) report.addError("KEYWORD_UNDEFINED_STRICT", ["items"], void 0, schema, "items");
3599
- }
3600
- }
3601
- if (this.options.forceMinItems === true) {
3602
- if (schema.type === "array" || isArray && schema.type.includes("array")) {
3603
- if (schema.minItems === void 0) report.addError("KEYWORD_UNDEFINED_STRICT", ["minItems"], void 0, schema, "minItems");
3604
- }
3605
- }
3606
- if (this.options.forceMaxItems === true) {
3607
- if (schema.type === "array" || isArray && schema.type.includes("array")) {
3608
- if (schema.maxItems === void 0) report.addError("KEYWORD_UNDEFINED_STRICT", ["maxItems"], void 0, schema, "maxItems");
3609
- }
3610
- }
3611
- if (this.options.forceMinLength === true) {
3612
- if (schema.type === "string" || isArray && schema.type.includes("string")) {
3613
- if (schema.minLength === void 0 && schema.format === void 0 && schema.enum === void 0 && schema.pattern === void 0) report.addError("KEYWORD_UNDEFINED_STRICT", ["minLength"], void 0, schema, "minLength");
3614
- }
3615
- }
3616
- if (this.options.forceMaxLength === true) {
3617
- if (schema.type === "string" || isArray && schema.type.includes("string")) {
3618
- if (schema.maxLength === void 0 && schema.format === void 0 && schema.enum === void 0 && schema.pattern === void 0) report.addError("KEYWORD_UNDEFINED_STRICT", ["maxLength"], void 0, schema, "maxLength");
3619
- }
3620
- }
3748
+ if (this.options.noEmptyStrings === true && (schema.type === "string" || isArray && schema.type.includes("string")) && schema.minLength === void 0 && schema.enum === void 0 && schema.format === void 0) schema.minLength = 1;
3749
+ if (this.options.noEmptyArrays === true && (schema.type === "array" || isArray && schema.type.includes("array")) && schema.minItems === void 0) schema.minItems = 1;
3750
+ if (this.options.forceProperties === true && (schema.type === "object" || isArray && schema.type.includes("object")) && schema.properties === void 0 && schema.patternProperties === void 0) report.addError("KEYWORD_UNDEFINED_STRICT", ["properties"], void 0, schema, "properties");
3751
+ if (this.options.forceItems === true && (schema.type === "array" || isArray && schema.type.includes("array")) && schema.items === void 0) report.addError("KEYWORD_UNDEFINED_STRICT", ["items"], void 0, schema, "items");
3752
+ if (this.options.forceMinItems === true && (schema.type === "array" || isArray && schema.type.includes("array")) && schema.minItems === void 0) report.addError("KEYWORD_UNDEFINED_STRICT", ["minItems"], void 0, schema, "minItems");
3753
+ if (this.options.forceMaxItems === true && (schema.type === "array" || isArray && schema.type.includes("array")) && schema.maxItems === void 0) report.addError("KEYWORD_UNDEFINED_STRICT", ["maxItems"], void 0, schema, "maxItems");
3754
+ if (this.options.forceMinLength === true && (schema.type === "string" || isArray && schema.type.includes("string")) && schema.minLength === void 0 && schema.format === void 0 && schema.enum === void 0 && schema.pattern === void 0) report.addError("KEYWORD_UNDEFINED_STRICT", ["minLength"], void 0, schema, "minLength");
3755
+ if (this.options.forceMaxLength === true && (schema.type === "string" || isArray && schema.type.includes("string")) && schema.maxLength === void 0 && schema.format === void 0 && schema.enum === void 0 && schema.pattern === void 0) report.addError("KEYWORD_UNDEFINED_STRICT", ["maxLength"], void 0, schema, "maxLength");
3621
3756
  },
3622
- allOf: function(report, schema) {
3623
- if (Array.isArray(schema.allOf) === false) report.addError("KEYWORD_TYPE_EXPECTED", ["allOf", "array"], void 0, schema, "allOf");
3757
+ allOf(report, schema) {
3758
+ if (!Array.isArray(schema.allOf)) report.addError("KEYWORD_TYPE_EXPECTED", ["allOf", "array"], void 0, schema, "allOf");
3624
3759
  else if (schema.allOf.length === 0) report.addError("KEYWORD_MUST_BE", ["allOf", "an array with at least one element"], void 0, schema, "allOf");
3625
3760
  else for (let idx = 0; idx < schema.allOf.length; idx++) {
3626
3761
  report.path.push("allOf");
@@ -3630,8 +3765,8 @@ const SchemaValidators = {
3630
3765
  report.path.pop();
3631
3766
  }
3632
3767
  },
3633
- anyOf: function(report, schema) {
3634
- if (Array.isArray(schema.anyOf) === false) report.addError("KEYWORD_TYPE_EXPECTED", ["anyOf", "array"], void 0, schema, "anyOf");
3768
+ anyOf(report, schema) {
3769
+ if (!Array.isArray(schema.anyOf)) report.addError("KEYWORD_TYPE_EXPECTED", ["anyOf", "array"], void 0, schema, "anyOf");
3635
3770
  else if (schema.anyOf.length === 0) report.addError("KEYWORD_MUST_BE", ["anyOf", "an array with at least one element"], void 0, schema, "anyOf");
3636
3771
  else for (let idx = 0; idx < schema.anyOf.length; idx++) {
3637
3772
  report.path.push("anyOf");
@@ -3641,8 +3776,8 @@ const SchemaValidators = {
3641
3776
  report.path.pop();
3642
3777
  }
3643
3778
  },
3644
- oneOf: function(report, schema) {
3645
- if (Array.isArray(schema.oneOf) === false) report.addError("KEYWORD_TYPE_EXPECTED", ["oneOf", "array"], void 0, schema, "oneOf");
3779
+ oneOf(report, schema) {
3780
+ if (!Array.isArray(schema.oneOf)) report.addError("KEYWORD_TYPE_EXPECTED", ["oneOf", "array"], void 0, schema, "oneOf");
3646
3781
  else if (schema.oneOf.length === 0) report.addError("KEYWORD_MUST_BE", ["oneOf", "an array with at least one element"], void 0, schema, "oneOf");
3647
3782
  else for (let idx = 0; idx < schema.oneOf.length; idx++) {
3648
3783
  report.path.push("oneOf");
@@ -3652,16 +3787,17 @@ const SchemaValidators = {
3652
3787
  report.path.pop();
3653
3788
  }
3654
3789
  },
3655
- not: function(report, schema) {
3790
+ not(report, schema) {
3656
3791
  const notSchema = schema.not;
3657
- if (!(report.options.version === "draft-04" ? isObject(notSchema) : typeof notSchema === "boolean" || isObject(notSchema))) report.addError("KEYWORD_TYPE_EXPECTED", ["not", report.options.version === "draft-04" ? "object" : ["boolean", "object"]], void 0, schema, "not");
3658
- else {
3659
- report.path.push("not");
3660
- this.validateSchema(report, notSchema);
3661
- report.path.pop();
3792
+ if (!(report.options.version === "draft-04" ? isObject(notSchema) : typeof notSchema === "boolean" || isObject(notSchema))) {
3793
+ report.addError("KEYWORD_TYPE_EXPECTED", ["not", report.options.version === "draft-04" ? "object" : ["boolean", "object"]], void 0, schema, "not");
3794
+ return;
3662
3795
  }
3796
+ report.path.push("not");
3797
+ this.validateSchema(report, notSchema);
3798
+ report.path.pop();
3663
3799
  },
3664
- if: function(report, schema) {
3800
+ if(report, schema) {
3665
3801
  if (report.options.version !== "draft-07") return;
3666
3802
  const ifSchema = schema.if;
3667
3803
  if (!(typeof ifSchema === "boolean" || isObject(ifSchema))) {
@@ -3672,7 +3808,7 @@ const SchemaValidators = {
3672
3808
  this.validateSchema(report, ifSchema);
3673
3809
  report.path.pop();
3674
3810
  },
3675
- then: function(report, schema) {
3811
+ then(report, schema) {
3676
3812
  if (report.options.version !== "draft-07") return;
3677
3813
  const thenSchema = schema.then;
3678
3814
  if (!(typeof thenSchema === "boolean" || isObject(thenSchema))) {
@@ -3683,7 +3819,7 @@ const SchemaValidators = {
3683
3819
  this.validateSchema(report, thenSchema);
3684
3820
  report.path.pop();
3685
3821
  },
3686
- else: function(report, schema) {
3822
+ else(report, schema) {
3687
3823
  if (report.options.version !== "draft-07") return;
3688
3824
  const elseSchema = schema.else;
3689
3825
  if (!(typeof elseSchema === "boolean" || isObject(elseSchema))) {
@@ -3694,21 +3830,22 @@ const SchemaValidators = {
3694
3830
  this.validateSchema(report, elseSchema);
3695
3831
  report.path.pop();
3696
3832
  },
3697
- definitions: function(report, schema) {
3698
- if (!isObject(schema.definitions)) report.addError("KEYWORD_TYPE_EXPECTED", ["definitions", "object"], void 0, schema, "definitions");
3699
- else {
3700
- const keys = Object.keys(schema.definitions);
3701
- for (const key of keys) {
3702
- const val = schema.definitions[key];
3703
- report.path.push("definitions");
3704
- report.path.push(key);
3705
- this.validateSchema(report, val);
3706
- report.path.pop();
3707
- report.path.pop();
3708
- }
3833
+ definitions(report, schema) {
3834
+ if (!isObject(schema.definitions)) {
3835
+ report.addError("KEYWORD_TYPE_EXPECTED", ["definitions", "object"], void 0, schema, "definitions");
3836
+ return;
3837
+ }
3838
+ const keys = Object.keys(schema.definitions);
3839
+ for (const key of keys) {
3840
+ const val = schema.definitions[key];
3841
+ report.path.push("definitions");
3842
+ report.path.push(key);
3843
+ this.validateSchema(report, val);
3844
+ report.path.pop();
3845
+ report.path.pop();
3709
3846
  }
3710
3847
  },
3711
- $defs: function(report, schema) {
3848
+ $defs(report, schema) {
3712
3849
  if (report.options.version !== "draft2019-09" && report.options.version !== "draft2020-12") return;
3713
3850
  if (!isObject(schema.$defs)) {
3714
3851
  report.addError("KEYWORD_TYPE_EXPECTED", ["$defs", "object"], void 0, schema, "$defs");
@@ -3724,34 +3861,36 @@ const SchemaValidators = {
3724
3861
  report.path.pop();
3725
3862
  }
3726
3863
  },
3727
- format: function(report, schema) {
3864
+ format(report, schema) {
3728
3865
  if (this.options.formatAssertions === false) return;
3729
- if (typeof schema.format !== "string") report.addError("KEYWORD_TYPE_EXPECTED", ["format", "string"], void 0, schema, "format");
3730
- else {
3731
- const isModernDraft = this.options.version === "draft2019-09" || this.options.version === "draft2020-12";
3732
- if (!isFormatSupported(schema.format, this.options.customFormats) && this.options.ignoreUnknownFormats !== true && !isModernDraft) report.addError("UNKNOWN_FORMAT", [schema.format], void 0, schema, "format");
3866
+ if (typeof schema.format !== "string") {
3867
+ report.addError("KEYWORD_TYPE_EXPECTED", ["format", "string"], void 0, schema, "format");
3868
+ return;
3733
3869
  }
3870
+ const isModernDraft = this.options.version === "draft2019-09" || this.options.version === "draft2020-12";
3871
+ if (!isFormatSupported(schema.format, this.options.customFormats) && this.options.ignoreUnknownFormats !== true && !isModernDraft) report.addError("UNKNOWN_FORMAT", [schema.format], void 0, schema, "format");
3734
3872
  },
3735
- contentEncoding: function(report, schema) {
3873
+ contentEncoding(report, schema) {
3736
3874
  if (report.options.version !== "draft-07") return;
3737
3875
  if (typeof schema.contentEncoding !== "string") report.addError("KEYWORD_TYPE_EXPECTED", ["contentEncoding", "string"], void 0, schema, "contentEncoding");
3738
3876
  },
3739
- contentMediaType: function(report, schema) {
3877
+ contentMediaType(report, schema) {
3740
3878
  if (report.options.version !== "draft-07") return;
3741
3879
  if (typeof schema.contentMediaType !== "string") report.addError("KEYWORD_TYPE_EXPECTED", ["contentMediaType", "string"], void 0, schema, "contentMediaType");
3742
3880
  },
3743
- id: function(report, schema) {
3881
+ id(report, schema) {
3744
3882
  if (typeof schema.id !== "string") report.addError("KEYWORD_TYPE_EXPECTED", ["id", "string"], void 0, schema, "id");
3745
3883
  },
3746
- title: function(report, schema) {
3884
+ title(report, schema) {
3747
3885
  if (typeof schema.title !== "string") report.addError("KEYWORD_TYPE_EXPECTED", ["title", "string"], void 0, schema, "title");
3748
3886
  },
3749
- description: function(report, schema) {
3887
+ description(report, schema) {
3750
3888
  if (typeof schema.description !== "string") report.addError("KEYWORD_TYPE_EXPECTED", ["description", "string"], void 0, schema, "description");
3751
3889
  },
3752
- default: function() {}
3890
+ default() {}
3753
3891
  };
3754
3892
  var SchemaValidator = class {
3893
+ validator;
3755
3894
  constructor(validator) {
3756
3895
  this.validator = validator;
3757
3896
  }
@@ -3771,18 +3910,17 @@ var SchemaValidator = class {
3771
3910
  if (hasParentSchema) {
3772
3911
  if (schema.__$schemaResolved && schema.__$schemaResolved !== schema) {
3773
3912
  const subReport = new Report(report);
3774
- if (validate.call(this.validator, subReport, schema.__$schemaResolved, schema) === false) report.addError("PARENT_SCHEMA_VALIDATION_FAILED", void 0, subReport, schema, "$schema");
3913
+ if (!validate(this.validator, subReport, schema.__$schemaResolved, schema)) report.addError("PARENT_SCHEMA_VALIDATION_FAILED", void 0, subReport, schema, "$schema");
3775
3914
  } else if (this.validator.options.ignoreUnresolvableReferences !== true) report.addError("REF_UNRESOLVED", [schema.$schema], void 0, schema, "$schema");
3776
3915
  }
3777
3916
  if (this.validator.options.noTypeless === true) {
3778
3917
  if (schema.type !== void 0) {
3779
- let schemas = [];
3780
- if (Array.isArray(schema.anyOf)) schemas = schemas.concat(schema.anyOf);
3781
- if (Array.isArray(schema.oneOf)) schemas = schemas.concat(schema.oneOf);
3782
- if (Array.isArray(schema.allOf)) schemas = schemas.concat(schema.allOf);
3783
- schemas.forEach(function(sch) {
3918
+ const inheritType = (sch) => {
3784
3919
  if (!sch.type) sch.type = schema.type;
3785
- });
3920
+ };
3921
+ if (Array.isArray(schema.anyOf)) for (let i = 0; i < schema.anyOf.length; i++) inheritType(schema.anyOf[i]);
3922
+ if (Array.isArray(schema.oneOf)) for (let i = 0; i < schema.oneOf.length; i++) inheritType(schema.oneOf[i]);
3923
+ if (Array.isArray(schema.allOf)) for (let i = 0; i < schema.allOf.length; i++) inheritType(schema.allOf[i]);
3786
3924
  }
3787
3925
  if (schema.enum === void 0 && schema.type === void 0 && schema.anyOf === void 0 && schema.oneOf === void 0 && schema.not === void 0 && schema.$ref === void 0) report.addError("KEYWORD_UNDEFINED_STRICT", ["type"], void 0, schema, "type");
3788
3926
  }
@@ -3790,9 +3928,7 @@ var SchemaValidator = class {
3790
3928
  for (const key of keys) {
3791
3929
  if (key.startsWith("__")) continue;
3792
3930
  if (Object.hasOwn(SchemaValidators, key)) SchemaValidators[key].call(this, report, schema);
3793
- else if (!hasParentSchema) {
3794
- if (this.validator.options.noExtraKeywords === true) report.addError("KEYWORD_UNEXPECTED", [key], void 0, schema, void 0);
3795
- }
3931
+ else if (!hasParentSchema && this.validator.options.noExtraKeywords === true) report.addError("KEYWORD_UNEXPECTED", [key], void 0, schema);
3796
3932
  }
3797
3933
  if (this.validator.options.pedanticCheck === true) {
3798
3934
  if (schema.enum) {
@@ -3802,14 +3938,14 @@ var SchemaValidator = class {
3802
3938
  report.path.push("enum");
3803
3939
  for (let idx = 0; idx < schema.enum.length; idx++) {
3804
3940
  report.path.push(idx);
3805
- validate.call(this.validator, report, tmpSchema, schema.enum[idx]);
3941
+ validate(this.validator, report, tmpSchema, schema.enum[idx]);
3806
3942
  report.path.pop();
3807
3943
  }
3808
3944
  report.path.pop();
3809
3945
  }
3810
3946
  if (schema.default) {
3811
3947
  report.path.push("default");
3812
- validate.call(this.validator, report, schema, schema.default);
3948
+ validate(this.validator, report, schema, schema.default);
3813
3949
  report.path.pop();
3814
3950
  }
3815
3951
  }
@@ -3846,7 +3982,7 @@ var ZSchemaBase = class {
3846
3982
  * create a circular dependency).
3847
3983
  */
3848
3984
  _jsonValidate(report, schema, json) {
3849
- return validate.call(this, report, schema, json);
3985
+ return validate(this, report, schema, json);
3850
3986
  }
3851
3987
  getDefaultSchemaId() {
3852
3988
  return this.options.version && this.options.version !== "none" ? VERSION_SCHEMA_URL_MAPPING[this.options.version] : VERSION_SCHEMA_URL_MAPPING[defaultOptions.version];
@@ -3859,9 +3995,9 @@ var ZSchemaBase = class {
3859
3995
  if (!options) options = {};
3860
3996
  this.validateOptions = options;
3861
3997
  if (typeof schema !== "string" && typeof schema !== "boolean" && !isObject(schema)) {
3862
- const e = /* @__PURE__ */ new Error("Invalid .validate call - schema must be a string or object but " + whatIs(schema) + " was passed!");
3998
+ const e = /* @__PURE__ */ new Error(`Invalid .validate call - schema must be a string or object but ${whatIs(schema)} was passed!`);
3863
3999
  if (callback) {
3864
- setTimeout(function() {
4000
+ setTimeout(() => {
3865
4001
  callback(e, false);
3866
4002
  }, 0);
3867
4003
  return;
@@ -3876,9 +4012,9 @@ var ZSchemaBase = class {
3876
4012
  const schemaName = schema;
3877
4013
  _schema = this.scache.getSchema(report, schemaName);
3878
4014
  if (!_schema) {
3879
- const e = /* @__PURE__ */ new Error("Schema with id '" + schemaName + "' wasn't found in the validator cache!");
4015
+ const e = /* @__PURE__ */ new Error(`Schema with id '${schemaName}' wasn't found in the validator cache!`);
3880
4016
  if (callback) {
3881
- setTimeout(function() {
4017
+ setTimeout(() => {
3882
4018
  callback(e, false);
3883
4019
  }, 0);
3884
4020
  return;
@@ -3896,9 +4032,9 @@ var ZSchemaBase = class {
3896
4032
  report.rootSchema = _schema;
3897
4033
  _schema = get(_schema, options.schemaPath);
3898
4034
  if (!_schema) {
3899
- const e = /* @__PURE__ */ new Error("Schema path '" + options.schemaPath + "' wasn't found in the schema!");
4035
+ const e = /* @__PURE__ */ new Error(`Schema path '${options.schemaPath}' wasn't found in the schema!`);
3900
4036
  if (callback) {
3901
- setTimeout(function() {
4037
+ setTimeout(() => {
3902
4038
  callback(e, false);
3903
4039
  }, 0);
3904
4040
  return;
@@ -3906,7 +4042,7 @@ var ZSchemaBase = class {
3906
4042
  throw e;
3907
4043
  }
3908
4044
  }
3909
- if (!foundError) validate.call(this, report, _schema, json);
4045
+ if (!foundError) validate(this, report, _schema, json);
3910
4046
  if (callback) {
3911
4047
  report.processAsyncTasks(this.options.asyncTimeout, callback);
3912
4048
  return;
@@ -3977,8 +4113,8 @@ var ZSchemaBase = class {
3977
4113
  if (!err) return [];
3978
4114
  const details = err.details || [];
3979
4115
  const missingRefs = [];
3980
- function collect(details) {
3981
- for (const detail of details) {
4116
+ function collect(items) {
4117
+ for (const detail of items) {
3982
4118
  if (detail.code === "UNRESOLVABLE_REFERENCE" || detail.code === "SCHEMA_NOT_REACHABLE") missingRefs.push(detail.params[0]);
3983
4119
  if (detail.inner) collect(detail.inner);
3984
4120
  }
@@ -3994,9 +4130,13 @@ var ZSchemaBase = class {
3994
4130
  getMissingRemoteReferences(err) {
3995
4131
  const missingReferences = this.getMissingReferences(err);
3996
4132
  const missingRemoteReferences = [];
4133
+ const seen = /* @__PURE__ */ new Set();
3997
4134
  for (const ref of missingReferences) {
3998
4135
  const remoteReference = getRemotePath(ref);
3999
- if (remoteReference && !missingRemoteReferences.includes(remoteReference)) missingRemoteReferences.push(remoteReference);
4136
+ if (remoteReference && !seen.has(remoteReference)) {
4137
+ seen.add(remoteReference);
4138
+ missingRemoteReferences.push(remoteReference);
4139
+ }
4000
4140
  }
4001
4141
  return missingRemoteReferences;
4002
4142
  }
@@ -4009,24 +4149,25 @@ var ZSchemaBase = class {
4009
4149
  getResolvedSchema(schemaId) {
4010
4150
  const report = new Report(this.options);
4011
4151
  const schema = this.scache.getSchemaByUri(report, schemaId);
4012
- if (!schema) return void 0;
4152
+ if (!schema) return;
4013
4153
  const clonedSchema = deepClone(schema, this.options.maxRecursionDepth);
4014
4154
  const visited = /* @__PURE__ */ new WeakSet();
4015
- const cleanup = function(schema) {
4016
- let key;
4017
- const typeOf = whatIs(schema);
4155
+ const cleanup = (node) => {
4156
+ const typeOf = whatIs(node);
4018
4157
  if (typeOf !== "object" && typeOf !== "array") return;
4019
- if (visited.has(schema)) return;
4020
- visited.add(schema);
4021
- if (schema.$ref && schema.__$refResolved) {
4022
- const from = schema.__$refResolved;
4023
- const to = schema;
4024
- delete schema.$ref;
4025
- delete schema.__$refResolved;
4026
- for (key in from) copyProp(from, to, key);
4158
+ if (visited.has(node)) return;
4159
+ visited.add(node);
4160
+ const schemaNode = node;
4161
+ if (schemaNode.$ref && schemaNode.__$refResolved) {
4162
+ const from = schemaNode.__$refResolved;
4163
+ const to = schemaNode;
4164
+ delete schemaNode.$ref;
4165
+ delete schemaNode.__$refResolved;
4166
+ for (const key in from) if (Object.hasOwn(from, key)) copyProp(from, to, key);
4027
4167
  }
4028
- for (key in schema) if (Object.hasOwn(schema, key)) if (isInternalKey(key)) delete schema[key];
4029
- else cleanup(schema[key]);
4168
+ const record = node;
4169
+ for (const key in record) if (Object.hasOwn(record, key)) if (isInternalKey(key)) delete record[key];
4170
+ else cleanup(record[key]);
4030
4171
  };
4031
4172
  cleanup(clonedSchema);
4032
4173
  return clonedSchema;
@@ -4035,24 +4176,20 @@ var ZSchemaBase = class {
4035
4176
  //#endregion
4036
4177
  //#region src/z-schema.ts
4037
4178
  var ZSchema = class ZSchema extends ZSchemaBase {
4038
- /** @internal Use ZSchema.create() instead. */
4039
- constructor(options, token) {
4040
- super(options, token);
4041
- }
4042
4179
  /**
4043
4180
  * Register a global format validator available to all instances.
4044
4181
  * @param name - The format name (e.g. `'email'`, `'date'`).
4045
4182
  * @param validatorFunction - A sync or async function `(value: unknown) => boolean | Promise<boolean>`.
4046
4183
  */
4047
4184
  static registerFormat(name, validatorFunction) {
4048
- return registerFormat(name, validatorFunction);
4185
+ registerFormat(name, validatorFunction);
4049
4186
  }
4050
4187
  /**
4051
4188
  * Remove a globally registered format validator.
4052
4189
  * @param name - The format name to unregister.
4053
4190
  */
4054
4191
  static unregisterFormat(name) {
4055
- return unregisterFormat(name);
4192
+ unregisterFormat(name);
4056
4193
  }
4057
4194
  /** Returns the names of all globally registered format validators. */
4058
4195
  static getRegisteredFormats() {
@@ -4081,7 +4218,7 @@ var ZSchema = class ZSchema extends ZSchemaBase {
4081
4218
  * @param schemaReader - A function `(uri: string) => JsonSchema | undefined`, or `undefined` to clear.
4082
4219
  */
4083
4220
  static setSchemaReader(schemaReader) {
4084
- return setSchemaReader(schemaReader);
4221
+ setSchemaReader(schemaReader);
4085
4222
  }
4086
4223
  static schemaSymbol = schemaSymbol;
4087
4224
  static jsonSymbol = jsonSymbol;
@@ -4117,10 +4254,10 @@ var ZSchema = class ZSchema extends ZSchemaBase {
4117
4254
  try {
4118
4255
  this._validate(json, schema, options ?? {});
4119
4256
  return { valid: true };
4120
- } catch (err) {
4257
+ } catch (error) {
4121
4258
  return {
4122
4259
  valid: false,
4123
- err
4260
+ err: error
4124
4261
  };
4125
4262
  }
4126
4263
  }
@@ -4135,9 +4272,12 @@ var ZSchema = class ZSchema extends ZSchemaBase {
4135
4272
  validateAsync(json, schema, options) {
4136
4273
  return new Promise((resolve, reject) => {
4137
4274
  try {
4138
- this._validate(json, schema, options || {}, (err, valid) => err || valid !== true ? reject(err) : resolve(valid));
4139
- } catch (err) {
4140
- reject(err);
4275
+ this._validate(json, schema, options || {}, (err, valid) => {
4276
+ if (err || !valid) reject(err ?? /* @__PURE__ */ new Error("Validation failed"));
4277
+ else resolve(valid);
4278
+ });
4279
+ } catch (error) {
4280
+ reject(error instanceof Error ? error : new Error(String(error), { cause: error }));
4141
4281
  }
4142
4282
  });
4143
4283
  }
@@ -4158,10 +4298,10 @@ var ZSchema = class ZSchema extends ZSchemaBase {
4158
4298
  err
4159
4299
  });
4160
4300
  });
4161
- } catch (err) {
4301
+ } catch (error) {
4162
4302
  resolve({
4163
4303
  valid: false,
4164
- err
4304
+ err: error
4165
4305
  });
4166
4306
  }
4167
4307
  });
@@ -4184,10 +4324,10 @@ var ZSchema = class ZSchema extends ZSchemaBase {
4184
4324
  try {
4185
4325
  this._validateSchema(schemaOrArr);
4186
4326
  return { valid: true };
4187
- } catch (err) {
4327
+ } catch (error) {
4188
4328
  return {
4189
4329
  valid: false,
4190
- err
4330
+ err: error
4191
4331
  };
4192
4332
  }
4193
4333
  }
@@ -4197,10 +4337,6 @@ var ZSchema = class ZSchema extends ZSchemaBase {
4197
4337
  * Created via `ZSchema.create({ safe: true })`.
4198
4338
  */
4199
4339
  var ZSchemaSafe = class extends ZSchemaBase {
4200
- /** @internal Use ZSchema.create() instead. */
4201
- constructor(options, token) {
4202
- super(options, token);
4203
- }
4204
4340
  /**
4205
4341
  * Validate JSON data against a schema.
4206
4342
  * @param json - The data to validate.
@@ -4212,10 +4348,10 @@ var ZSchemaSafe = class extends ZSchemaBase {
4212
4348
  try {
4213
4349
  this._validate(json, schema, options);
4214
4350
  return { valid: true };
4215
- } catch (err) {
4351
+ } catch (error) {
4216
4352
  return {
4217
4353
  valid: false,
4218
- err
4354
+ err: error
4219
4355
  };
4220
4356
  }
4221
4357
  }
@@ -4228,10 +4364,10 @@ var ZSchemaSafe = class extends ZSchemaBase {
4228
4364
  try {
4229
4365
  this._validateSchema(schemaOrArr);
4230
4366
  return { valid: true };
4231
- } catch (err) {
4367
+ } catch (error) {
4232
4368
  return {
4233
4369
  valid: false,
4234
- err
4370
+ err: error
4235
4371
  };
4236
4372
  }
4237
4373
  }
@@ -4241,10 +4377,6 @@ var ZSchemaSafe = class extends ZSchemaBase {
4241
4377
  * Created via `ZSchema.create({ async: true })`.
4242
4378
  */
4243
4379
  var ZSchemaAsync = class extends ZSchemaBase {
4244
- /** @internal Use ZSchema.create() instead. */
4245
- constructor(options, token) {
4246
- super(options, token);
4247
- }
4248
4380
  /**
4249
4381
  * Validate JSON data against a schema asynchronously.
4250
4382
  * @param json - The data to validate.
@@ -4256,9 +4388,12 @@ var ZSchemaAsync = class extends ZSchemaBase {
4256
4388
  validate(json, schema, options = {}) {
4257
4389
  return new Promise((resolve, reject) => {
4258
4390
  try {
4259
- this._validate(json, schema, options, (err, valid) => err || valid !== true ? reject(err) : resolve(valid));
4260
- } catch (err) {
4261
- reject(err);
4391
+ this._validate(json, schema, options, (err, valid) => {
4392
+ if (err || !valid) reject(err ?? /* @__PURE__ */ new Error("Validation failed"));
4393
+ else resolve(valid);
4394
+ });
4395
+ } catch (error) {
4396
+ reject(error instanceof Error ? error : new Error(String(error), { cause: error }));
4262
4397
  }
4263
4398
  });
4264
4399
  }
@@ -4277,10 +4412,6 @@ var ZSchemaAsync = class extends ZSchemaBase {
4277
4412
  * Created via `ZSchema.create({ async: true, safe: true })`.
4278
4413
  */
4279
4414
  var ZSchemaAsyncSafe = class extends ZSchemaBase {
4280
- /** @internal Use ZSchema.create() instead. */
4281
- constructor(options, token) {
4282
- super(options, token);
4283
- }
4284
4415
  /**
4285
4416
  * Validate JSON data against a schema asynchronously.
4286
4417
  * The promise always resolves (never rejects).
@@ -4298,10 +4429,10 @@ var ZSchemaAsyncSafe = class extends ZSchemaBase {
4298
4429
  err
4299
4430
  });
4300
4431
  });
4301
- } catch (err) {
4432
+ } catch (error) {
4302
4433
  resolve({
4303
4434
  valid: false,
4304
- err
4435
+ err: error
4305
4436
  });
4306
4437
  }
4307
4438
  });
@@ -4315,10 +4446,10 @@ var ZSchemaAsyncSafe = class extends ZSchemaBase {
4315
4446
  try {
4316
4447
  this._validateSchema(schemaOrArr);
4317
4448
  return { valid: true };
4318
- } catch (err) {
4449
+ } catch (error) {
4319
4450
  return {
4320
4451
  valid: false,
4321
- err
4452
+ err: error
4322
4453
  };
4323
4454
  }
4324
4455
  }