z-schema 10.0.0 → 12.0.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 (138) hide show
  1. package/README.md +35 -17
  2. package/cjs/index.d.ts +345 -34
  3. package/cjs/index.js +4446 -1685
  4. package/dist/errors.js +5 -0
  5. package/dist/format-validators.js +131 -107
  6. package/dist/json-schema-versions.js +4 -1
  7. package/dist/json-schema.js +50 -16
  8. package/dist/json-validation.js +524 -669
  9. package/dist/report.js +37 -16
  10. package/dist/schema-cache.js +76 -18
  11. package/dist/schema-compiler.js +72 -47
  12. package/dist/schema-validator.js +117 -52
  13. package/dist/schemas/draft-07-schema.json +172 -0
  14. package/dist/schemas/draft-2019-09-meta-applicator.json +52 -0
  15. package/dist/schemas/draft-2019-09-meta-content.json +12 -0
  16. package/dist/schemas/draft-2019-09-meta-core.json +53 -0
  17. package/dist/schemas/draft-2019-09-meta-format.json +10 -0
  18. package/dist/schemas/draft-2019-09-meta-meta-data.json +32 -0
  19. package/dist/schemas/draft-2019-09-meta-validation.json +94 -0
  20. package/dist/schemas/draft-2019-09-schema.json +41 -0
  21. package/dist/schemas/draft-2020-12-meta-applicator.json +44 -0
  22. package/dist/schemas/draft-2020-12-meta-content.json +12 -0
  23. package/dist/schemas/draft-2020-12-meta-core.json +47 -0
  24. package/dist/schemas/draft-2020-12-meta-format-annotation.json +10 -0
  25. package/dist/schemas/draft-2020-12-meta-format-assertion.json +10 -0
  26. package/dist/schemas/draft-2020-12-meta-meta-data.json +32 -0
  27. package/dist/schemas/draft-2020-12-meta-unevaluated.json +11 -0
  28. package/dist/schemas/draft-2020-12-meta-validation.json +94 -0
  29. package/dist/schemas/draft-2020-12-schema.json +57 -0
  30. package/dist/types/errors.d.ts +4 -0
  31. package/dist/types/index.d.ts +2 -1
  32. package/dist/types/json-schema-versions.d.ts +128 -9
  33. package/dist/types/json-schema.d.ts +28 -11
  34. package/dist/types/json-validation.d.ts +2 -3
  35. package/dist/types/report.d.ts +14 -4
  36. package/dist/types/schema-cache.d.ts +7 -0
  37. package/dist/types/schema-compiler.d.ts +5 -3
  38. package/dist/types/schema-validator.d.ts +2 -2
  39. package/dist/types/utils/array.d.ts +8 -1
  40. package/dist/types/utils/base64.d.ts +2 -0
  41. package/dist/types/utils/clone.d.ts +1 -1
  42. package/dist/types/utils/date.d.ts +1 -0
  43. package/dist/types/utils/hostname.d.ts +2 -0
  44. package/dist/types/utils/json.d.ts +2 -1
  45. package/dist/types/utils/properties.d.ts +0 -1
  46. package/dist/types/utils/time.d.ts +12 -0
  47. package/dist/types/utils/unicode.d.ts +3 -12
  48. package/dist/types/validation/array.d.ts +12 -0
  49. package/dist/types/validation/combinators.d.ts +10 -0
  50. package/dist/types/validation/numeric.d.ts +8 -0
  51. package/dist/types/validation/object.d.ts +13 -0
  52. package/dist/types/validation/ref.d.ts +11 -0
  53. package/dist/types/validation/shared.d.ts +26 -0
  54. package/dist/types/validation/string.d.ts +9 -0
  55. package/dist/types/validation/type.d.ts +6 -0
  56. package/dist/types/z-schema-base.d.ts +39 -1
  57. package/dist/types/z-schema-options.d.ts +3 -0
  58. package/dist/types/z-schema.d.ts +144 -8
  59. package/dist/utils/array.js +49 -7
  60. package/dist/utils/base64.js +29 -0
  61. package/dist/utils/clone.js +13 -12
  62. package/dist/utils/date.js +21 -0
  63. package/dist/utils/hostname.js +146 -0
  64. package/dist/utils/json.js +11 -6
  65. package/dist/utils/properties.js +1 -6
  66. package/dist/utils/time.js +50 -0
  67. package/dist/utils/unicode.js +8 -41
  68. package/dist/utils/uri.js +1 -1
  69. package/dist/validation/array.js +128 -0
  70. package/dist/validation/combinators.js +107 -0
  71. package/dist/validation/numeric.js +97 -0
  72. package/dist/validation/object.js +238 -0
  73. package/dist/validation/ref.js +70 -0
  74. package/dist/validation/shared.js +136 -0
  75. package/dist/validation/string.js +178 -0
  76. package/dist/validation/type.js +55 -0
  77. package/dist/z-schema-base.js +52 -32
  78. package/dist/z-schema-options.js +12 -8
  79. package/dist/z-schema-versions.js +92 -9
  80. package/dist/z-schema.js +135 -38
  81. package/package.json +22 -8
  82. package/src/errors.ts +8 -0
  83. package/src/format-validators.ts +146 -105
  84. package/src/index.ts +10 -1
  85. package/src/json-schema-versions.ts +181 -11
  86. package/src/json-schema.ts +102 -35
  87. package/src/json-validation.ts +653 -724
  88. package/src/report.ts +42 -20
  89. package/src/schema-cache.ts +94 -18
  90. package/src/schema-compiler.ts +94 -51
  91. package/src/schema-validator.ts +132 -56
  92. package/src/schemas/draft-07-schema.json +172 -0
  93. package/src/schemas/draft-2019-09-meta-applicator.json +53 -0
  94. package/src/schemas/draft-2019-09-meta-content.json +14 -0
  95. package/src/schemas/draft-2019-09-meta-core.json +54 -0
  96. package/src/schemas/draft-2019-09-meta-format.json +11 -0
  97. package/src/schemas/draft-2019-09-meta-meta-data.json +34 -0
  98. package/src/schemas/draft-2019-09-meta-validation.json +95 -0
  99. package/src/schemas/draft-2019-09-schema.json +42 -0
  100. package/src/schemas/draft-2020-12-meta-applicator.json +45 -0
  101. package/src/schemas/draft-2020-12-meta-content.json +14 -0
  102. package/src/schemas/draft-2020-12-meta-core.json +48 -0
  103. package/src/schemas/draft-2020-12-meta-format-annotation.json +11 -0
  104. package/src/schemas/draft-2020-12-meta-format-assertion.json +11 -0
  105. package/src/schemas/draft-2020-12-meta-meta-data.json +34 -0
  106. package/src/schemas/draft-2020-12-meta-unevaluated.json +12 -0
  107. package/src/schemas/draft-2020-12-meta-validation.json +95 -0
  108. package/src/schemas/draft-2020-12-schema.json +58 -0
  109. package/src/utils/array.ts +51 -7
  110. package/src/utils/base64.ts +32 -0
  111. package/src/utils/clone.ts +16 -12
  112. package/src/utils/date.ts +23 -0
  113. package/src/utils/hostname.ts +174 -0
  114. package/src/utils/json.ts +15 -6
  115. package/src/utils/properties.ts +1 -7
  116. package/src/utils/time.ts +73 -0
  117. package/src/utils/unicode.ts +8 -39
  118. package/src/utils/uri.ts +1 -1
  119. package/src/validation/array.ts +158 -0
  120. package/src/validation/combinators.ts +132 -0
  121. package/src/validation/numeric.ts +120 -0
  122. package/src/validation/object.ts +318 -0
  123. package/src/validation/ref.ts +85 -0
  124. package/src/validation/shared.ts +191 -0
  125. package/src/validation/string.ts +224 -0
  126. package/src/validation/type.ts +66 -0
  127. package/src/z-schema-base.ts +54 -36
  128. package/src/z-schema-options.ts +15 -8
  129. package/src/z-schema-versions.ts +107 -12
  130. package/src/z-schema.ts +158 -42
  131. package/umd/ZSchema.js +4446 -1685
  132. package/umd/ZSchema.min.js +1 -1
  133. package/dist/schemas/draft-04-hyper-schema.json +0 -135
  134. package/dist/schemas/draft-06-hyper-schema.json +0 -132
  135. package/dist/schemas/draft-06-links.json +0 -43
  136. package/src/schemas/draft-04-hyper-schema.json +0 -136
  137. package/src/schemas/draft-06-hyper-schema.json +0 -133
  138. package/src/schemas/draft-06-links.json +0 -43
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # z-schema
2
2
 
3
- JSON Schema validator for Node.js and browsers. Supports **draft-04** and **draft-06** (default).
3
+ Fast, lightweight JSON Schema validator for Node.js and browsers with **full support for the latest JSON Schema draft (2020-12)**, plus draft-2019-09, draft-07, draft-06, and draft-04.
4
4
 
5
5
  [![NPM](https://nodei.co/npm/z-schema.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/z-schema)
6
6
 
@@ -63,15 +63,24 @@ z-schema --strictMode mySchema.json myData.json
63
63
 
64
64
  ## Usage
65
65
 
66
+ `ZSchema.create()` returns one of four validator variants based on the `async` and `safe` options:
67
+
68
+ | Options | Class | `validate()` returns |
69
+ | ----------------------------- | ------------------ | -------------------------- |
70
+ | `{}` | `ZSchema` | `true` (throws on error) |
71
+ | `{ safe: true }` | `ZSchemaSafe` | `{ valid, err? }` |
72
+ | `{ async: true }` | `ZSchemaAsync` | `Promise<true>` (rejects) |
73
+ | `{ async: true, safe: true }` | `ZSchemaAsyncSafe` | `Promise<{ valid, err? }>` |
74
+
66
75
  ### Sync Validation (Throw Mode)
67
76
 
68
77
  By default, `validate` throws a `ValidateError` on failure. The error has a `details` array with structured error info.
69
78
 
70
79
  ```typescript
71
- const validator = ZSchema.create();
80
+ const validator = ZSchema.create(); // returns ZSchema
72
81
 
73
82
  try {
74
- validator.validate(json, schema);
83
+ validator.validate(json, schema); // returns true
75
84
  } catch (error) {
76
85
  console.log(error.name); // 'z-schema validation error'
77
86
  console.log(error.message); // summary message
@@ -81,35 +90,41 @@ try {
81
90
 
82
91
  ### Sync Validation (Safe Mode)
83
92
 
84
- Use `ZSchema.create({ safe: true })` to get a result object instead of exceptions.
93
+ Use `{ safe: true }` to get a `ZSchemaSafe` instance whose `validate()` returns a result object instead of throwing.
85
94
 
86
95
  ```typescript
87
- const validator = ZSchema.create({ safe: true });
96
+ const validator = ZSchema.create({ safe: true }); // returns ZSchemaSafe
88
97
 
89
- const result = validator.validate(json, schema);
98
+ const result = validator.validate(json, schema); // { valid: boolean, err?: ValidateError }
90
99
  if (!result.valid) {
91
- console.log(result.err); // ValidateError with .details
100
+ console.log(result.err!.details);
92
101
  }
93
102
  ```
94
103
 
95
- ### Async Validation
104
+ ### Async Validation (Throw Mode)
96
105
 
97
- Pass `{ async: true }` to support async format validators. The `validate` method returns a Promise.
106
+ Pass `{ async: true }` to support async format validators. Returns a `ZSchemaAsync` instance whose `validate()` returns a `Promise`.
98
107
 
99
108
  ```typescript
100
- const validator = ZSchema.create({ async: true });
109
+ const validator = ZSchema.create({ async: true }); // returns ZSchemaAsync
101
110
 
102
111
  try {
103
- await validator.validate(json, schema);
112
+ await validator.validate(json, schema); // Promise<true>
104
113
  } catch (error) {
105
114
  console.log(error.details);
106
115
  }
116
+ ```
117
+
118
+ ### Async Validation (Safe Mode)
119
+
120
+ Combine both options to get a `ZSchemaAsyncSafe` instance — the promise always resolves (never rejects) with a result object.
121
+
122
+ ```typescript
123
+ const validator = ZSchema.create({ async: true, safe: true }); // returns ZSchemaAsyncSafe
107
124
 
108
- // Or combine with safe mode:
109
- const safeValidator = ZSchema.create({ async: true, safe: true });
110
- const result = await safeValidator.validate(json, schema);
125
+ const result = await validator.validate(json, schema); // Promise<{ valid, err? }>
111
126
  if (!result.valid) {
112
- console.log(result.err);
127
+ console.log(result.err!.details);
113
128
  }
114
129
  ```
115
130
 
@@ -173,8 +188,10 @@ ZSchema.setSchemaReader((uri: string) => {
173
188
 
174
189
  | Version | Changes |
175
190
  | ------- | ------------------------------------------------------------------------------------------------- |
176
- | **v10** | Default version is **draft-06**. Implemented draft-06 tests from JSON Schema Test suite. |
177
- | **v9** | New factory API: `ZSchema.create()` replaces `new ZSchema()`. Default draft is **draft-06**. |
191
+ | **v12** | Default version is **draft2020-12**. Full support for **draft-2020-12** and **draft-2019-09**. |
192
+ | **v11** | Default version is **draft-07**. Implemented draft-07 tests from JSON Schema Test Suite. |
193
+ | **v10** | Default version is **draft-06**. Implemented draft-06 tests from JSON Schema Test Suite. |
194
+ | **v9** | New factory API: `ZSchema.create()` replaces `new ZSchema()`. New cache algorithms. |
178
195
  | **v8** | Schemas without `$schema` default to draft-04. Use `{ version: 'none' }` for the old v7 behavior. |
179
196
  | **v7** | Rewritten in TypeScript/ESM. Passes all JSON Schema Test Suite tests for draft-04. |
180
197
  | **v6** | Legacy version. Draft-04 support. |
@@ -194,6 +211,7 @@ See [docs/options.md](docs/options.md) for all constructor and per-call options.
194
211
  | [docs/usage.md](docs/usage.md) | Detailed usage guide with all validation modes, error handling, and advanced features |
195
212
  | [docs/options.md](docs/options.md) | Constructor options and per-call validation options |
196
213
  | [docs/features.md](docs/features.md) | Feature catalog with examples |
214
+ | [docs/MIGRATION.md](docs/MIGRATION.md) | Migration guide for upgrading between major versions |
197
215
  | [docs/architecture.md](docs/architecture.md) | Internal architecture, module structure, and public API reference |
198
216
  | [docs/conventions.md](docs/conventions.md) | Code style, naming, and formatting conventions |
199
217
  | [docs/testing.md](docs/testing.md) | Test framework, running tests, and writing new tests |
package/cjs/index.d.ts CHANGED
@@ -33,8 +33,10 @@ interface ZSchemaOptions {
33
33
  breakOnFirstError?: boolean;
34
34
  pedanticCheck?: boolean;
35
35
  ignoreUnknownFormats?: boolean;
36
+ formatAssertions?: boolean | null;
36
37
  customValidator?: (report: Report, schema: unknown, json: unknown) => void;
37
38
  customFormats?: Record<string, FormatValidatorFn | null>;
39
+ maxRecursionDepth?: number;
38
40
  }
39
41
 
40
42
  interface SchemaErrorDetail {
@@ -79,7 +81,7 @@ interface SchemaErrorDetail {
79
81
  * The schema keyword that caused this validation error.
80
82
  * Example: "required", "type", "minLength"
81
83
  */
82
- keyword?: keyof JsonSchema;
84
+ keyword?: keyof JsonSchemaAll;
83
85
  }
84
86
  interface ReportOptions {
85
87
  maxErrors?: number;
@@ -92,6 +94,9 @@ type AsyncTask = [TaskFn, TaskFnArgs, TaskProcessFn];
92
94
  declare class Report {
93
95
  asyncTasks: AsyncTask[];
94
96
  commonErrorMessage?: string;
97
+ __$recursiveAnchorStack: JsonSchemaInternal[];
98
+ __$dynamicScopeStack: JsonSchemaInternal[];
99
+ __validationResultCache: Map<unknown, Map<unknown, boolean>>;
95
100
  errors: SchemaErrorDetail[];
96
101
  json?: unknown;
97
102
  path: Array<number | string>;
@@ -106,15 +111,22 @@ declare class Report {
106
111
  constructor(parentReport: Report, reportOptions: ReportOptions, validateOptions?: ValidateOptions);
107
112
  isValid(): boolean;
108
113
  addAsyncTask<FV, FN extends (...args: any[]) => FV>(fn: FN, args: Parameters<FN>, asyncTaskResultProcessFn: (result: ReturnType<FN>) => void): void;
114
+ /**
115
+ * Like {@link addAsyncTask}, but automatically saves the current `path` and
116
+ * restores it around `processFn`. This eliminates the manual
117
+ * path-save/restore boilerplate that every async-aware validator would
118
+ * otherwise need.
119
+ */
120
+ addAsyncTaskWithPath(fn: (...args: any[]) => any, args: any[], processFn: (result: any) => void): void;
109
121
  getAncestor(id: string): Report | undefined;
110
122
  processAsyncTasks(timeout: number | undefined, callback: ValidateCallback): void;
111
123
  getPath(returnPathAsString?: boolean): string | (string | number)[];
112
124
  getSchemaPath(): Array<string | number>;
113
125
  getSchemaId(): string | undefined;
114
126
  hasError(errCode: string, errParams: Array<any>): boolean;
115
- addError(errCode: ErrorCode, errParams?: ErrorParam[], subReports?: Report | Report[], schema?: JsonSchema | boolean, keyword?: keyof JsonSchema): void;
127
+ addError(errCode: ErrorCode, errParams?: ErrorParam[], subReports?: Report | Report[], schema?: JsonSchema | boolean, keyword?: keyof JsonSchemaAll): void;
116
128
  getJson(): unknown;
117
- addCustomError(errorCode: ErrorCode, errorMessage: string, params?: ErrorParam[], subReports?: Report | Report[], schema?: JsonSchema | boolean, keyword?: keyof JsonSchema): void;
129
+ addCustomError(errorCode: ErrorCode, errorMessage: string, params?: ErrorParam[], subReports?: Report | Report[], schema?: JsonSchema | boolean, keyword?: keyof JsonSchemaAll): void;
118
130
  }
119
131
 
120
132
  type ErrorCode = keyof typeof Errors;
@@ -132,6 +144,7 @@ declare const Errors: {
132
144
  ARRAY_LENGTH_LONG: string;
133
145
  ARRAY_UNIQUE: string;
134
146
  ARRAY_ADDITIONAL_ITEMS: string;
147
+ ARRAY_UNEVALUATED_ITEMS: string;
135
148
  MULTIPLE_OF: string;
136
149
  MINIMUM: string;
137
150
  MINIMUM_EXCLUSIVE: string;
@@ -141,6 +154,7 @@ declare const Errors: {
141
154
  OBJECT_PROPERTIES_MAXIMUM: string;
142
155
  OBJECT_MISSING_REQUIRED_PROPERTY: string;
143
156
  OBJECT_ADDITIONAL_PROPERTIES: string;
157
+ OBJECT_UNEVALUATED_PROPERTIES: string;
144
158
  OBJECT_DEPENDENCY_KEY: string;
145
159
  MIN_LENGTH: string;
146
160
  MAX_LENGTH: string;
@@ -166,6 +180,8 @@ declare const Errors: {
166
180
  CONST: string;
167
181
  CONTAINS: string;
168
182
  PROPERTY_NAMES: string;
183
+ COLLECT_EVALUATED_DEPTH_EXCEEDED: string;
184
+ MAX_RECURSION_DEPTH_EXCEEDED: string;
169
185
  };
170
186
  declare class ValidateError extends Error {
171
187
  name: string;
@@ -194,8 +210,8 @@ declare class SchemaValidator {
194
210
  private validator;
195
211
  constructor(validator: ZSchemaBase);
196
212
  get options(): ZSchemaOptions;
197
- validateArrayOfSchemas(report: Report, arr: JsonSchemaInternal[]): boolean;
198
- validateSchema(report: Report, schema: JsonSchemaInternal | JsonSchemaInternal[]): boolean;
213
+ validateArrayOfSchemas(report: Report, arr: Array<JsonSchemaInternal | boolean>): boolean;
214
+ validateSchema(report: Report, schema: JsonSchemaInternal | boolean | Array<JsonSchemaInternal | boolean>): boolean;
199
215
  }
200
216
 
201
217
  interface ValidateOptions {
@@ -214,26 +230,59 @@ declare class ZSchemaBase {
214
230
  sv: SchemaValidator;
215
231
  validateOptions: ValidateOptions;
216
232
  options: ZSchemaOptions;
217
- constructor(options?: ZSchemaOptions);
233
+ constructor(options: ZSchemaOptions | undefined, token: symbol);
218
234
  getDefaultSchemaId(): string;
219
235
  _validate(json: unknown, schema: JsonSchema | string, options: ValidateOptions, callback: ValidateCallback): void;
220
236
  _validate(json: unknown, schema: JsonSchema | string, callback: ValidateCallback): void;
221
237
  _validate(json: unknown, schema: JsonSchema | string, options: ValidateOptions): true;
222
238
  _validate(json: unknown, schema: JsonSchema | string): true;
223
239
  _validateSchema(schemaOrArr: JsonSchema | JsonSchema[]): true;
240
+ /**
241
+ * Register a format validator on this instance only (does not affect other instances or the global registry).
242
+ * @param name - The format name.
243
+ * @param validatorFunction - A sync or async function `(value: unknown) => boolean | Promise<boolean>`.
244
+ */
224
245
  registerFormat(name: string, validatorFunction: FormatValidatorFn): void;
246
+ /**
247
+ * Unregister an instance-scoped format validator.
248
+ * @param name - The format name to unregister.
249
+ */
225
250
  unregisterFormat(name: string): void;
251
+ /** Returns the names of format validators registered on this instance. */
226
252
  getRegisteredFormats(): string[];
253
+ /** Returns all supported format names (global + instance-registered). */
227
254
  getSupportedFormats(): string[];
255
+ /**
256
+ * Register a remote schema in this instance's cache so `$ref` can resolve to it.
257
+ * @param uri - The URI the schema will be known by.
258
+ * @param schema - The schema object or JSON string.
259
+ * @param validationOptions - Optional options used for schema preparation.
260
+ */
228
261
  setRemoteReference(uri: string, schema: string | JsonSchema, validationOptions?: ZSchemaOptions): void;
262
+ /**
263
+ * Extract unresolvable `$ref` URIs from a validation error.
264
+ * @param err - A `ValidateError` from a failed validation.
265
+ * @returns An array of unresolvable reference URIs.
266
+ */
229
267
  getMissingReferences(err: ValidateError): string[];
268
+ /**
269
+ * Extract unresolvable **remote** `$ref` URIs from a validation error (local fragment-only refs are excluded).
270
+ * @param err - A `ValidateError` from a failed validation.
271
+ * @returns An array of remote reference base URIs.
272
+ */
230
273
  getMissingRemoteReferences(err: ValidateError): string[];
274
+ /**
275
+ * Resolve a previously compiled schema by its `$id` / `id`, cleaning up internal bookkeeping properties
276
+ * and inlining resolved `$ref` targets.
277
+ * @param schemaId - The schema identifier to look up.
278
+ * @returns A clean, resolved copy of the schema, or `undefined` if not found.
279
+ */
231
280
  getResolvedSchema(schemaId: string): JsonSchema | undefined;
232
281
  }
233
282
 
234
283
  interface Reference {
235
284
  ref: string;
236
- key: '$ref' | '$schema';
285
+ key: '$ref' | '$schema' | '$recursiveRef' | '$dynamicRef';
237
286
  obj: JsonSchemaInternal;
238
287
  path: Array<string | number>;
239
288
  }
@@ -248,82 +297,251 @@ declare class SchemaCompiler {
248
297
  compileArrayOfSchemasLoop(mainReport: Report, arr: JsonSchemaInternal[]): number;
249
298
  }
250
299
 
300
+ /**
301
+ * Properties present in ALL JSON Schema drafts (04 through 2020-12) with
302
+ * identical types. Draft-specific additions live on the individual draft
303
+ * interfaces in `json-schema-versions.ts`.
304
+ */
251
305
  interface JsonSchemaCommon {
252
306
  $ref?: string;
253
307
  $schema?: string;
254
- id?: string;
255
308
  title?: string;
256
309
  description?: string;
257
310
  default?: unknown;
258
- definitions?: Record<string, JsonSchema>;
259
311
  type?: string | string[];
260
- properties?: Record<string, JsonSchema>;
261
- patternProperties?: Record<string, JsonSchema>;
312
+ enum?: Array<unknown>;
313
+ format?: string;
262
314
  multipleOf?: number;
263
315
  minimum?: number;
264
316
  maximum?: number;
317
+ /** Draft-04: `boolean` modifier on `minimum`/`maximum`. Draft-06+: standalone `number`. */
318
+ exclusiveMinimum?: boolean | number;
319
+ /** Draft-04: `boolean` modifier on `minimum`/`maximum`. Draft-06+: standalone `number`. */
320
+ exclusiveMaximum?: boolean | number;
265
321
  minLength?: number;
266
322
  maxLength?: number;
267
323
  pattern?: string;
324
+ items?: JsonSchema | boolean | Array<JsonSchema | boolean>;
268
325
  additionalItems?: boolean | JsonSchema;
269
- items?: JsonSchema | JsonSchema[];
270
326
  minItems?: number;
271
327
  maxItems?: number;
272
328
  uniqueItems?: boolean;
329
+ properties?: Record<string, JsonSchema | boolean>;
330
+ patternProperties?: Record<string, JsonSchema>;
331
+ additionalProperties?: boolean | JsonSchema;
332
+ required?: string[];
273
333
  minProperties?: number;
274
334
  maxProperties?: number;
275
- required?: string[];
276
- additionalProperties?: boolean | JsonSchema;
277
335
  dependencies?: Record<string, string[] | JsonSchema>;
278
- enum?: Array<unknown>;
279
- format?: string;
280
336
  allOf?: JsonSchema[];
281
337
  anyOf?: JsonSchema[];
282
338
  oneOf?: JsonSchema[];
283
339
  not?: JsonSchema;
340
+ definitions?: Record<string, JsonSchema>;
284
341
  }
285
342
  type JsonSchemaType = 'array' | 'boolean' | 'integer' | 'null' | 'number' | 'object' | 'string';
286
343
  interface ZSchemaInternalProperties {
287
344
  __$compiled?: unknown;
288
345
  __$missingReferences?: Reference[];
289
346
  __$refResolved?: JsonSchema;
347
+ __$dynamicRefResolved?: JsonSchema;
348
+ __$recursiveRefResolved?: JsonSchema;
349
+ __$resourceRoot?: JsonSchemaInternal;
290
350
  __$schemaResolved?: unknown;
291
351
  __$validated?: boolean;
292
352
  __$validationOptions?: ZSchemaOptions;
293
- __$visited?: boolean;
294
353
  }
295
354
 
296
- type JsonSchemaVersion = 'draft-04' | 'draft-06';
297
- type JsonSchema = JsonSchemaDraft4 | JsonSchemaDraft6;
298
- type JsonSchemaInternal = JsonSchema & ZSchemaInternalProperties;
355
+ type JsonSchemaVersion = 'draft-04' | 'draft-06' | 'draft-07' | 'draft2019-09' | 'draft2020-12';
356
+ /** Union of all draft-specific schema interfaces — the public API type. */
357
+ type JsonSchema = JsonSchemaDraft4 | JsonSchemaDraft6 | JsonSchemaDraft7 | JsonSchemaDraft201909 | JsonSchemaDraft202012;
358
+ /**
359
+ * Superset of ALL draft-specific properties with the widest possible types.
360
+ * Use inside the validator where the active draft is not known at compile time.
361
+ *
362
+ * NOTE: this is a manually defined interface (not a computed intersection)
363
+ * because `exclusiveMinimum` is `boolean` in Draft-04 and `number` in
364
+ * Draft-06+, which would yield `never` in a plain intersection.
365
+ */
366
+ interface JsonSchemaAll extends JsonSchemaCommon {
367
+ /** Pre-`$id` identifier (draft-04 only). */
368
+ id?: string;
369
+ /** Schema identifier (replaces `id` from draft-06 onward). */
370
+ $id?: string;
371
+ const?: unknown;
372
+ contains?: JsonSchema;
373
+ propertyNames?: JsonSchema;
374
+ examples?: unknown[];
375
+ if?: JsonSchema | boolean;
376
+ then?: JsonSchema | boolean;
377
+ else?: JsonSchema | boolean;
378
+ contentEncoding?: string;
379
+ contentMediaType?: string;
380
+ $defs?: Record<string, JsonSchema>;
381
+ $anchor?: string;
382
+ $vocabulary?: Record<string, boolean>;
383
+ $recursiveAnchor?: boolean;
384
+ $recursiveRef?: string;
385
+ dependentSchemas?: Record<string, JsonSchema>;
386
+ dependentRequired?: Record<string, string[]>;
387
+ unevaluatedItems?: JsonSchema | boolean;
388
+ unevaluatedProperties?: JsonSchema | boolean;
389
+ maxContains?: number;
390
+ minContains?: number;
391
+ $dynamicAnchor?: string;
392
+ $dynamicRef?: string;
393
+ prefixItems?: Array<JsonSchema | boolean>;
394
+ }
395
+ /**
396
+ * Internal schema type used throughout the validator. Based on `JsonSchemaAll`
397
+ * so that validators can access any draft-specific property without narrowing.
398
+ */
399
+ type JsonSchemaInternal = JsonSchemaAll & ZSchemaInternalProperties;
400
+ /**
401
+ * JSON Schema Draft-04.
402
+ *
403
+ * Key differences from later drafts:
404
+ * - Uses `id` instead of `$id`.
405
+ * - `exclusiveMinimum`/`exclusiveMaximum` are boolean modifiers on `minimum`/`maximum`
406
+ * (inherited as `boolean | number` from `JsonSchemaCommon` for cross-draft compatibility).
407
+ * - No `const`, `contains`, `propertyNames`, `examples`, `if`/`then`/`else`.
408
+ *
409
+ * @see https://json-schema.org/draft-04/draft-zyp-json-schema-04
410
+ */
299
411
  interface JsonSchemaDraft4 extends JsonSchemaCommon {
300
- exclusiveMaximum?: boolean;
301
- exclusiveMinimum?: boolean;
412
+ /** Schema identifier (draft-04). Replaced by `$id` in draft-06+. */
413
+ id?: string;
302
414
  }
415
+ /**
416
+ * JSON Schema Draft-06.
417
+ *
418
+ * Additions over Draft-04:
419
+ * - `$id` replaces `id`.
420
+ * - `exclusiveMinimum`/`exclusiveMaximum` changed to standalone `number` values.
421
+ * - Added `const`, `contains`, `propertyNames`, `examples`.
422
+ *
423
+ * @see https://json-schema.org/draft-06/draft-wright-json-schema-validation-01
424
+ */
303
425
  interface JsonSchemaDraft6 extends JsonSchemaCommon {
304
426
  $id?: string;
305
- examples?: unknown[];
306
427
  const?: unknown;
307
428
  contains?: JsonSchema;
308
429
  propertyNames?: JsonSchema;
309
- exclusiveMaximum?: number;
310
- exclusiveMinimum?: number;
430
+ examples?: unknown[];
431
+ }
432
+ /**
433
+ * JSON Schema Draft-07.
434
+ *
435
+ * Additions over Draft-06:
436
+ * - `if`/`then`/`else` conditional applicators.
437
+ * - `contentEncoding`, `contentMediaType`.
438
+ *
439
+ * @see https://json-schema.org/draft-07/draft-handrews-json-schema-validation-01
440
+ */
441
+ interface JsonSchemaDraft7 extends JsonSchemaDraft6 {
442
+ if?: JsonSchema | boolean;
443
+ then?: JsonSchema | boolean;
444
+ else?: JsonSchema | boolean;
445
+ contentEncoding?: string;
446
+ contentMediaType?: string;
447
+ }
448
+ /**
449
+ * JSON Schema Draft 2019-09.
450
+ *
451
+ * Additions over Draft-07:
452
+ * - `$defs` (replaces `definitions`), `$anchor`, `$vocabulary`.
453
+ * - `$recursiveAnchor`/`$recursiveRef` for recursive references.
454
+ * - `dependentSchemas`/`dependentRequired` (split from `dependencies`).
455
+ * - `unevaluatedItems`/`unevaluatedProperties`.
456
+ * - `maxContains`/`minContains`.
457
+ *
458
+ * @see https://json-schema.org/draft/2019-09/release-notes
459
+ */
460
+ interface JsonSchemaDraft201909 extends JsonSchemaDraft7 {
461
+ $defs?: Record<string, JsonSchema>;
462
+ $anchor?: string;
463
+ $vocabulary?: Record<string, boolean>;
464
+ $recursiveAnchor?: boolean;
465
+ $recursiveRef?: string;
466
+ dependentSchemas?: Record<string, JsonSchema>;
467
+ dependentRequired?: Record<string, string[]>;
468
+ unevaluatedItems?: JsonSchema | boolean;
469
+ unevaluatedProperties?: JsonSchema | boolean;
470
+ maxContains?: number;
471
+ minContains?: number;
472
+ }
473
+ /**
474
+ * JSON Schema Draft 2020-12.
475
+ *
476
+ * Additions over Draft 2019-09:
477
+ * - `$dynamicAnchor`/`$dynamicRef` replace `$recursiveAnchor`/`$recursiveRef`.
478
+ * - `prefixItems` replaces the array form of `items`.
479
+ *
480
+ * @see https://json-schema.org/draft/2020-12/release-notes
481
+ */
482
+ interface JsonSchemaDraft202012 extends JsonSchemaDraft201909 {
483
+ $dynamicAnchor?: string;
484
+ $dynamicRef?: string;
485
+ prefixItems?: Array<JsonSchema | boolean>;
311
486
  }
312
487
 
313
488
  type SchemaReader = (uri: string) => JsonSchema;
314
489
 
315
490
  declare class ZSchema extends ZSchemaBase {
316
- /** @deprecated Use ZSchema.create() instead. */
317
- private constructor();
491
+ /** @internal Use ZSchema.create() instead. */
492
+ constructor(options: ZSchemaOptions | undefined, token: symbol);
493
+ /**
494
+ * Register a global format validator available to all instances.
495
+ * @param name - The format name (e.g. `'email'`, `'date'`).
496
+ * @param validatorFunction - A sync or async function `(value: unknown) => boolean | Promise<boolean>`.
497
+ */
318
498
  static registerFormat(name: string, validatorFunction: FormatValidatorFn): void;
499
+ /**
500
+ * Remove a globally registered format validator.
501
+ * @param name - The format name to unregister.
502
+ */
319
503
  static unregisterFormat(name: string): void;
504
+ /** Returns the names of all globally registered format validators. */
320
505
  static getRegisteredFormats(): string[];
506
+ /** Returns a deep clone of the default options. */
321
507
  static getDefaultOptions(): ZSchemaOptions;
508
+ /**
509
+ * Register a remote schema in the global cache so any instance can resolve `$ref` to it.
510
+ * @param uri - The URI the schema will be known by.
511
+ * @param schema - The schema object or JSON string.
512
+ * @param validationOptions - Optional options used for schema preparation.
513
+ */
322
514
  static setRemoteReference(uri: string, schema: string | JsonSchema, validationOptions?: ZSchemaOptions): void;
515
+ /** Returns the current global schema reader, or `undefined` if none is set. */
323
516
  static getSchemaReader(): SchemaReader | undefined;
517
+ /**
518
+ * Set a global schema reader function used to resolve remote `$ref` URIs.
519
+ * @param schemaReader - A function `(uri: string) => JsonSchema | undefined`, or `undefined` to clear.
520
+ */
324
521
  static setSchemaReader(schemaReader: SchemaReader | undefined): void;
325
522
  static schemaSymbol: symbol;
326
523
  static jsonSymbol: symbol;
524
+ /**
525
+ * Create a validator instance.
526
+ *
527
+ * The returned type depends on the `async` and `safe` options:
528
+ * - `{}` → `ZSchema` — `validate()` returns `true` or throws.
529
+ * - `{ safe: true }` → `ZSchemaSafe` — `validate()` returns `{ valid, err? }`.
530
+ * - `{ async: true }` → `ZSchemaAsync` — `validate()` returns `Promise<true>` or rejects.
531
+ * - `{ async: true, safe: true }` → `ZSchemaAsyncSafe` — `validate()` returns `Promise<{ valid, err? }>`.
532
+ *
533
+ * @param options - Validator configuration. See `ZSchemaOptions` for all available settings.
534
+ * @returns A validator instance of the appropriate variant.
535
+ *
536
+ * @example
537
+ * ```ts
538
+ * const validator = ZSchema.create();
539
+ * validator.validate(data, schema); // throws on error
540
+ *
541
+ * const safe = ZSchema.create({ safe: true });
542
+ * const result = safe.validate(data, schema); // { valid, err? }
543
+ * ```
544
+ */
327
545
  static create(options: ZSchemaOptions & {
328
546
  async: true;
329
547
  safe: true;
@@ -335,31 +553,124 @@ declare class ZSchema extends ZSchemaBase {
335
553
  safe: true;
336
554
  }): ZSchemaSafe;
337
555
  static create(options?: ZSchemaOptions): ZSchema;
556
+ /**
557
+ * Validate JSON data against a schema.
558
+ * @param json - The data to validate.
559
+ * @param schema - A JSON Schema object or a schema id string (previously registered via `validateSchema`).
560
+ * @param options - Per-call options (`schemaPath`, `includeErrors`, `excludeErrors`).
561
+ * @returns `true` if valid.
562
+ * @throws {@link ValidateError} if validation fails, with a `details` array of structured errors.
563
+ */
338
564
  validate(json: unknown, schema: JsonSchema | string, options?: ValidateOptions): true;
565
+ /**
566
+ * Validate JSON data against a schema, returning a result object instead of throwing.
567
+ * @param json - The data to validate.
568
+ * @param schema - A JSON Schema object or a schema id string.
569
+ * @param options - Per-call options.
570
+ * @returns `{ valid: true }` on success, or `{ valid: false, err: ValidateError }` on failure.
571
+ */
339
572
  validateSafe(json: unknown, schema: JsonSchema | string, options?: ValidateOptions): ValidateResponse;
573
+ /**
574
+ * Validate JSON data against a schema asynchronously (supports async format validators).
575
+ * @param json - The data to validate.
576
+ * @param schema - A JSON Schema object or a schema id string.
577
+ * @param options - Per-call options.
578
+ * @returns A promise that resolves to `true` if valid.
579
+ * @throws {@link ValidateError} if validation fails (the promise rejects).
580
+ */
340
581
  validateAsync(json: unknown, schema: JsonSchema | string, options?: ValidateOptions): Promise<true>;
582
+ /**
583
+ * Validate JSON data against a schema asynchronously, returning a result object.
584
+ * The promise always resolves (never rejects).
585
+ * @param json - The data to validate.
586
+ * @param schema - A JSON Schema object or a schema id string.
587
+ * @param options - Per-call options.
588
+ * @returns A promise resolving to `{ valid: true }` or `{ valid: false, err: ValidateError }`.
589
+ */
341
590
  validateAsyncSafe(json: unknown, schema: JsonSchema | string, options?: ValidateOptions): Promise<ValidateResponse>;
591
+ /**
592
+ * Validate one or more JSON Schemas, compiling and caching them for later use with `validate()`.
593
+ * @param schemaOrArr - A single schema or an array of schemas (for cross-referencing).
594
+ * @returns `true` if all schemas are valid.
595
+ * @throws {@link ValidateError} if any schema is invalid.
596
+ */
342
597
  validateSchema(schemaOrArr: JsonSchema | JsonSchema[]): true;
598
+ /**
599
+ * Validate one or more JSON Schemas, returning a result object instead of throwing.
600
+ * @param schemaOrArr - A single schema or an array of schemas.
601
+ * @returns `{ valid: true }` on success, or `{ valid: false, err: ValidateError }` on failure.
602
+ */
343
603
  validateSchemaSafe(schemaOrArr: JsonSchema | JsonSchema[]): ValidateResponse;
344
604
  }
605
+ /**
606
+ * Synchronous safe validator — `validate()` returns `{ valid, err? }` instead of throwing.
607
+ * Created via `ZSchema.create({ safe: true })`.
608
+ */
345
609
  declare class ZSchemaSafe extends ZSchemaBase {
346
- /** @deprecated Use ZSchema.create() instead. */
347
- private constructor();
610
+ /** @internal Use ZSchema.create() instead. */
611
+ constructor(options: ZSchemaOptions | undefined, token: symbol);
612
+ /**
613
+ * Validate JSON data against a schema.
614
+ * @param json - The data to validate.
615
+ * @param schema - A JSON Schema object or a schema id string.
616
+ * @param options - Per-call options.
617
+ * @returns `{ valid: true }` on success, or `{ valid: false, err: ValidateError }` on failure.
618
+ */
348
619
  validate(json: unknown, schema: JsonSchema | string, options?: ValidateOptions): ValidateResponse;
620
+ /**
621
+ * Validate one or more JSON Schemas.
622
+ * @param schemaOrArr - A single schema or an array of schemas.
623
+ * @returns `{ valid: true }` on success, or `{ valid: false, err: ValidateError }` on failure.
624
+ */
349
625
  validateSchema(schemaOrArr: JsonSchema | JsonSchema[]): ValidateResponse;
350
626
  }
627
+ /**
628
+ * Asynchronous throw validator — `validate()` returns `Promise<true>` or rejects.
629
+ * Created via `ZSchema.create({ async: true })`.
630
+ */
351
631
  declare class ZSchemaAsync extends ZSchemaBase {
352
- /** @deprecated Use ZSchema.create() instead. */
353
- private constructor();
632
+ /** @internal Use ZSchema.create() instead. */
633
+ constructor(options: ZSchemaOptions | undefined, token: symbol);
634
+ /**
635
+ * Validate JSON data against a schema asynchronously.
636
+ * @param json - The data to validate.
637
+ * @param schema - A JSON Schema object or a schema id string.
638
+ * @param options - Per-call options.
639
+ * @returns A promise that resolves to `true` if valid.
640
+ * @throws {@link ValidateError} if validation fails (the promise rejects).
641
+ */
354
642
  validate(json: unknown, schema: JsonSchema | string, options?: ValidateOptions): Promise<true>;
643
+ /**
644
+ * Validate one or more JSON Schemas (synchronous, throws on error).
645
+ * @param schemaOrArr - A single schema or an array of schemas.
646
+ * @returns `true` if all schemas are valid.
647
+ * @throws {@link ValidateError} if any schema is invalid.
648
+ */
355
649
  validateSchema(schemaOrArr: JsonSchema | JsonSchema[]): true;
356
650
  }
651
+ /**
652
+ * Asynchronous safe validator — `validate()` returns `Promise<{ valid, err? }>` (never rejects).
653
+ * Created via `ZSchema.create({ async: true, safe: true })`.
654
+ */
357
655
  declare class ZSchemaAsyncSafe extends ZSchemaBase {
358
- /** @deprecated Use ZSchema.create() instead. */
359
- private constructor();
656
+ /** @internal Use ZSchema.create() instead. */
657
+ constructor(options: ZSchemaOptions | undefined, token: symbol);
658
+ /**
659
+ * Validate JSON data against a schema asynchronously.
660
+ * The promise always resolves (never rejects).
661
+ * @param json - The data to validate.
662
+ * @param schema - A JSON Schema object or a schema id string.
663
+ * @param options - Per-call options.
664
+ * @returns A promise resolving to `{ valid: true }` or `{ valid: false, err: ValidateError }`.
665
+ */
360
666
  validate(json: unknown, schema: JsonSchema | string, options?: ValidateOptions): Promise<ValidateResponse>;
667
+ /**
668
+ * Validate one or more JSON Schemas.
669
+ * @param schemaOrArr - A single schema or an array of schemas.
670
+ * @returns `{ valid: true }` on success, or `{ valid: false, err: ValidateError }` on failure.
671
+ */
361
672
  validateSchema(schemaOrArr: JsonSchema | JsonSchema[]): ValidateResponse;
362
673
  }
363
674
 
364
675
  export { Errors, Report, ValidateError, ZSchema, ZSchemaAsync, ZSchemaAsyncSafe, ZSchemaSafe, ZSchema as default, getFormatValidators, getRegisteredFormats, getSupportedFormats, isFormatSupported, registerFormat, unregisterFormat };
365
- export type { ErrorCode, ErrorParam, FormatValidatorFn, FormatValidatorsOptions, JsonSchema, JsonSchemaType, SchemaErrorDetail, SchemaReader, ValidateOptions, ValidateResponse, ZSchemaOptions };
676
+ export type { ErrorCode, ErrorParam, FormatValidatorFn, FormatValidatorsOptions, JsonSchema, JsonSchemaCommon, JsonSchemaDraft201909, JsonSchemaDraft202012, JsonSchemaDraft4, JsonSchemaDraft6, JsonSchemaDraft7, JsonSchemaType, JsonSchemaVersion, SchemaErrorDetail, SchemaReader, ValidateOptions, ValidateResponse, ZSchemaOptions };