z-schema 12.0.4 → 12.1.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 (176) hide show
  1. package/bin/z-schema +7 -2
  2. package/cjs/index.d.ts +541 -530
  3. package/cjs/index.js +3963 -7740
  4. package/dist/errors.d.mts +64 -0
  5. package/dist/errors.mjs +67 -0
  6. package/dist/format-validators.d.mts +14 -0
  7. package/dist/format-validators.mjs +261 -0
  8. package/dist/index.d.mts +10 -0
  9. package/dist/index.mjs +7 -0
  10. package/dist/json-schema-versions.d.mts +137 -0
  11. package/dist/json-schema-versions.mjs +11 -0
  12. package/dist/json-schema.d.mts +61 -0
  13. package/dist/json-schema.mjs +53 -0
  14. package/dist/json-validation.mjs +441 -0
  15. package/dist/report.d.mts +97 -0
  16. package/dist/report.mjs +194 -0
  17. package/dist/schema-cache.d.mts +23 -0
  18. package/dist/schema-cache.mjs +144 -0
  19. package/dist/schema-compiler.d.mts +23 -0
  20. package/dist/schema-compiler.mjs +265 -0
  21. package/dist/schema-validator.d.mts +15 -0
  22. package/dist/schema-validator.mjs +446 -0
  23. package/dist/schemas/draft-04-schema.mjs +125 -0
  24. package/dist/schemas/draft-06-schema.mjs +126 -0
  25. package/dist/schemas/draft-07-schema.mjs +141 -0
  26. package/dist/schemas/draft-2019-09-meta-applicator.mjs +46 -0
  27. package/dist/schemas/draft-2019-09-meta-content.mjs +15 -0
  28. package/dist/schemas/draft-2019-09-meta-core.mjs +52 -0
  29. package/dist/schemas/draft-2019-09-meta-format.mjs +11 -0
  30. package/dist/schemas/draft-2019-09-meta-meta-data.mjs +31 -0
  31. package/dist/schemas/draft-2019-09-meta-validation.mjs +80 -0
  32. package/dist/schemas/draft-2019-09-schema.mjs +39 -0
  33. package/dist/schemas/draft-2020-12-meta-applicator.mjs +45 -0
  34. package/dist/schemas/draft-2020-12-meta-content.mjs +15 -0
  35. package/dist/schemas/draft-2020-12-meta-core.mjs +46 -0
  36. package/dist/schemas/draft-2020-12-meta-format-annotation.mjs +11 -0
  37. package/dist/schemas/draft-2020-12-meta-format-assertion.mjs +11 -0
  38. package/dist/schemas/draft-2020-12-meta-meta-data.mjs +31 -0
  39. package/dist/schemas/draft-2020-12-meta-unevaluated.mjs +14 -0
  40. package/dist/schemas/draft-2020-12-meta-validation.mjs +80 -0
  41. package/dist/schemas/draft-2020-12-schema.mjs +55 -0
  42. package/dist/utils/array.mjs +54 -0
  43. package/dist/utils/base64.mjs +21 -0
  44. package/dist/utils/clone.mjs +42 -0
  45. package/dist/utils/constants.mjs +16 -0
  46. package/dist/utils/date.mjs +19 -0
  47. package/dist/utils/hostname.mjs +73 -0
  48. package/dist/utils/json.mjs +34 -0
  49. package/dist/utils/properties.mjs +11 -0
  50. package/dist/utils/schema-regex.mjs +49 -0
  51. package/dist/utils/symbols.mjs +5 -0
  52. package/dist/utils/time.mjs +42 -0
  53. package/dist/utils/unicode.mjs +12 -0
  54. package/dist/utils/uri.mjs +12 -0
  55. package/dist/utils/what-is.mjs +23 -0
  56. package/dist/validation/array.mjs +57 -0
  57. package/dist/validation/combinators.mjs +62 -0
  58. package/dist/validation/numeric.mjs +38 -0
  59. package/dist/validation/object.mjs +109 -0
  60. package/dist/validation/ref.mjs +49 -0
  61. package/dist/validation/shared.mjs +97 -0
  62. package/dist/validation/string.mjs +88 -0
  63. package/dist/validation/type.mjs +32 -0
  64. package/dist/z-schema-base.d.mts +85 -0
  65. package/dist/z-schema-base.mjs +230 -0
  66. package/dist/z-schema-options.d.mts +35 -0
  67. package/dist/z-schema-options.mjs +55 -0
  68. package/dist/z-schema-reader.d.mts +6 -0
  69. package/dist/z-schema-reader.mjs +10 -0
  70. package/dist/z-schema-versions.mjs +67 -0
  71. package/dist/z-schema.d.mts +193 -0
  72. package/dist/z-schema.mjs +300 -0
  73. package/package.json +49 -64
  74. package/src/index.ts +3 -3
  75. package/src/schema-compiler.ts +30 -10
  76. package/src/schema-validator.ts +1 -1
  77. package/src/utils/schema-regex.ts +13 -2
  78. package/src/z-schema-base.ts +1 -1
  79. package/src/z-schema-versions.ts +1 -2
  80. package/src/z-schema.ts +0 -1
  81. package/umd/ZSchema.js +5934 -8110
  82. package/umd/ZSchema.min.js +2 -1
  83. package/dist/errors.js +0 -72
  84. package/dist/format-validators.js +0 -392
  85. package/dist/index.js +0 -5
  86. package/dist/json-schema-versions.js +0 -8
  87. package/dist/json-schema.js +0 -84
  88. package/dist/json-validation.js +0 -728
  89. package/dist/package.json +0 -3
  90. package/dist/report.js +0 -265
  91. package/dist/schema-cache.js +0 -211
  92. package/dist/schema-compiler.js +0 -415
  93. package/dist/schema-validator.js +0 -721
  94. package/dist/schemas/draft-04-schema.json +0 -149
  95. package/dist/schemas/draft-06-schema.json +0 -155
  96. package/dist/schemas/draft-07-schema.json +0 -172
  97. package/dist/schemas/draft-2019-09-meta-applicator.json +0 -52
  98. package/dist/schemas/draft-2019-09-meta-content.json +0 -12
  99. package/dist/schemas/draft-2019-09-meta-core.json +0 -53
  100. package/dist/schemas/draft-2019-09-meta-format.json +0 -10
  101. package/dist/schemas/draft-2019-09-meta-meta-data.json +0 -32
  102. package/dist/schemas/draft-2019-09-meta-validation.json +0 -94
  103. package/dist/schemas/draft-2019-09-schema.json +0 -41
  104. package/dist/schemas/draft-2020-12-meta-applicator.json +0 -44
  105. package/dist/schemas/draft-2020-12-meta-content.json +0 -12
  106. package/dist/schemas/draft-2020-12-meta-core.json +0 -47
  107. package/dist/schemas/draft-2020-12-meta-format-annotation.json +0 -10
  108. package/dist/schemas/draft-2020-12-meta-format-assertion.json +0 -10
  109. package/dist/schemas/draft-2020-12-meta-meta-data.json +0 -32
  110. package/dist/schemas/draft-2020-12-meta-unevaluated.json +0 -11
  111. package/dist/schemas/draft-2020-12-meta-validation.json +0 -94
  112. package/dist/schemas/draft-2020-12-schema.json +0 -57
  113. package/dist/types/errors.d.ts +0 -64
  114. package/dist/types/format-validators.d.ts +0 -11
  115. package/dist/types/index.d.ts +0 -14
  116. package/dist/types/json-schema-versions.d.ts +0 -142
  117. package/dist/types/json-schema.d.ts +0 -66
  118. package/dist/types/json-validation.d.ts +0 -6
  119. package/dist/types/report.d.ts +0 -94
  120. package/dist/types/schema-cache.d.ts +0 -27
  121. package/dist/types/schema-compiler.d.ts +0 -31
  122. package/dist/types/schema-validator.d.ts +0 -10
  123. package/dist/types/utils/array.d.ts +0 -9
  124. package/dist/types/utils/base64.d.ts +0 -2
  125. package/dist/types/utils/clone.d.ts +0 -2
  126. package/dist/types/utils/constants.d.ts +0 -19
  127. package/dist/types/utils/date.d.ts +0 -1
  128. package/dist/types/utils/hostname.d.ts +0 -2
  129. package/dist/types/utils/json.d.ts +0 -9
  130. package/dist/types/utils/properties.d.ts +0 -1
  131. package/dist/types/utils/schema-regex.d.ts +0 -10
  132. package/dist/types/utils/symbols.d.ts +0 -2
  133. package/dist/types/utils/time.d.ts +0 -12
  134. package/dist/types/utils/unicode.d.ts +0 -5
  135. package/dist/types/utils/uri.d.ts +0 -4
  136. package/dist/types/utils/what-is.d.ts +0 -4
  137. package/dist/types/validation/array.d.ts +0 -12
  138. package/dist/types/validation/combinators.d.ts +0 -10
  139. package/dist/types/validation/numeric.d.ts +0 -8
  140. package/dist/types/validation/object.d.ts +0 -13
  141. package/dist/types/validation/ref.d.ts +0 -11
  142. package/dist/types/validation/shared.d.ts +0 -26
  143. package/dist/types/validation/string.d.ts +0 -9
  144. package/dist/types/validation/type.d.ts +0 -6
  145. package/dist/types/z-schema-base.d.ts +0 -87
  146. package/dist/types/z-schema-options.d.ts +0 -35
  147. package/dist/types/z-schema-reader.d.ts +0 -4
  148. package/dist/types/z-schema-versions.d.ts +0 -1
  149. package/dist/types/z-schema.d.ts +0 -191
  150. package/dist/utils/array.js +0 -69
  151. package/dist/utils/base64.js +0 -29
  152. package/dist/utils/clone.js +0 -59
  153. package/dist/utils/constants.js +0 -19
  154. package/dist/utils/date.js +0 -21
  155. package/dist/utils/hostname.js +0 -146
  156. package/dist/utils/json.js +0 -70
  157. package/dist/utils/properties.js +0 -10
  158. package/dist/utils/schema-regex.js +0 -52
  159. package/dist/utils/symbols.js +0 -2
  160. package/dist/utils/time.js +0 -50
  161. package/dist/utils/unicode.js +0 -12
  162. package/dist/utils/uri.js +0 -15
  163. package/dist/utils/what-is.js +0 -32
  164. package/dist/validation/array.js +0 -127
  165. package/dist/validation/combinators.js +0 -106
  166. package/dist/validation/numeric.js +0 -97
  167. package/dist/validation/object.js +0 -237
  168. package/dist/validation/ref.js +0 -70
  169. package/dist/validation/shared.js +0 -136
  170. package/dist/validation/string.js +0 -170
  171. package/dist/validation/type.js +0 -55
  172. package/dist/z-schema-base.js +0 -286
  173. package/dist/z-schema-options.js +0 -99
  174. package/dist/z-schema-reader.js +0 -7
  175. package/dist/z-schema-versions.js +0 -110
  176. package/dist/z-schema.js +0 -287
@@ -1,87 +0,0 @@
1
- import type { ValidateError } from './errors.js';
2
- import type { FormatValidatorFn } from './format-validators.js';
3
- import type { JsonSchema, JsonSchemaInternal } from './json-schema-versions.js';
4
- import type { ZSchemaOptions } from './z-schema-options.js';
5
- import { type Errors } from './errors.js';
6
- import { Report } from './report.js';
7
- import { SchemaCache } from './schema-cache.js';
8
- import { SchemaCompiler } from './schema-compiler.js';
9
- import { SchemaValidator } from './schema-validator.js';
10
- export interface ValidateOptions {
11
- schemaPath?: string;
12
- includeErrors?: Array<keyof typeof Errors>;
13
- excludeErrors?: Array<keyof typeof Errors>;
14
- }
15
- export type ValidateResponse = {
16
- valid: boolean;
17
- err?: ValidateError;
18
- };
19
- export type ValidateCallback = (err: ValidateResponse['err'], valid: ValidateResponse['valid']) => void;
20
- /**
21
- * Module-private symbol used by `ZSchema.create()` to authorise construction.
22
- * Not exported — external code cannot instantiate ZSchema variants directly.
23
- */
24
- export declare const FACTORY_TOKEN: unique symbol;
25
- export declare class ZSchemaBase {
26
- scache: SchemaCache;
27
- sc: SchemaCompiler;
28
- sv: SchemaValidator;
29
- validateOptions: ValidateOptions;
30
- options: ZSchemaOptions;
31
- constructor(options: ZSchemaOptions | undefined, token: symbol);
32
- /**
33
- * Internal recursive JSON validation — delegates to the `validate` function
34
- * in `json-validation.ts`. Exposed as a method so that per-keyword validator
35
- * modules (array, combinators, object) can call back into the core validator
36
- * via `this` without importing `json-validation.ts` directly (which would
37
- * create a circular dependency).
38
- */
39
- _jsonValidate(report: Report, schema: boolean | JsonSchemaInternal, json: unknown): boolean;
40
- getDefaultSchemaId(): string;
41
- _validate(json: unknown, schema: JsonSchema | string, options: ValidateOptions, callback: ValidateCallback): void;
42
- _validate(json: unknown, schema: JsonSchema | string, callback: ValidateCallback): void;
43
- _validate(json: unknown, schema: JsonSchema | string, options: ValidateOptions): true;
44
- _validate(json: unknown, schema: JsonSchema | string): true;
45
- _validateSchema(schemaOrArr: JsonSchema | JsonSchema[]): true;
46
- /**
47
- * Register a format validator on this instance only (does not affect other instances or the global registry).
48
- * @param name - The format name.
49
- * @param validatorFunction - A sync or async function `(value: unknown) => boolean | Promise<boolean>`.
50
- */
51
- registerFormat(name: string, validatorFunction: FormatValidatorFn): void;
52
- /**
53
- * Unregister an instance-scoped format validator.
54
- * @param name - The format name to unregister.
55
- */
56
- unregisterFormat(name: string): void;
57
- /** Returns the names of format validators registered on this instance. */
58
- getRegisteredFormats(): string[];
59
- /** Returns all supported format names (global + instance-registered). */
60
- getSupportedFormats(): string[];
61
- /**
62
- * Register a remote schema in this instance's cache so `$ref` can resolve to it.
63
- * @param uri - The URI the schema will be known by.
64
- * @param schema - The schema object or JSON string.
65
- * @param validationOptions - Optional options used for schema preparation.
66
- */
67
- setRemoteReference(uri: string, schema: string | JsonSchema, validationOptions?: ZSchemaOptions): void;
68
- /**
69
- * Extract unresolvable `$ref` URIs from a validation error.
70
- * @param err - A `ValidateError` from a failed validation.
71
- * @returns An array of unresolvable reference URIs.
72
- */
73
- getMissingReferences(err: ValidateError): string[];
74
- /**
75
- * Extract unresolvable **remote** `$ref` URIs from a validation error (local fragment-only refs are excluded).
76
- * @param err - A `ValidateError` from a failed validation.
77
- * @returns An array of remote reference base URIs.
78
- */
79
- getMissingRemoteReferences(err: ValidateError): string[];
80
- /**
81
- * Resolve a previously compiled schema by its `$id` / `id`, cleaning up internal bookkeeping properties
82
- * and inlining resolved `$ref` targets.
83
- * @param schemaId - The schema identifier to look up.
84
- * @returns A clean, resolved copy of the schema, or `undefined` if not found.
85
- */
86
- getResolvedSchema(schemaId: string): JsonSchema | undefined;
87
- }
@@ -1,35 +0,0 @@
1
- import type { FormatValidatorFn } from './format-validators.js';
2
- import type { Report } from './report.js';
3
- import { type JsonSchemaVersion } from './json-schema-versions.js';
4
- import { DEFAULT_MAX_RECURSION_DEPTH, MAX_ASYNC_TIMEOUT } from './utils/constants.js';
5
- export { DEFAULT_MAX_RECURSION_DEPTH, MAX_ASYNC_TIMEOUT };
6
- export interface ZSchemaOptions {
7
- version?: JsonSchemaVersion | 'none';
8
- asyncTimeout?: number;
9
- forceAdditional?: boolean;
10
- assumeAdditional?: boolean | string[];
11
- enumCaseInsensitiveComparison?: boolean;
12
- forceItems?: boolean;
13
- forceMinItems?: boolean;
14
- forceMaxItems?: boolean;
15
- forceMinLength?: boolean;
16
- forceMaxLength?: boolean;
17
- forceProperties?: boolean;
18
- ignoreUnresolvableReferences?: boolean;
19
- noExtraKeywords?: boolean;
20
- noTypeless?: boolean;
21
- noEmptyStrings?: boolean;
22
- noEmptyArrays?: boolean;
23
- strictUris?: boolean;
24
- strictMode?: boolean;
25
- reportPathAsArray?: boolean;
26
- breakOnFirstError?: boolean;
27
- pedanticCheck?: boolean;
28
- ignoreUnknownFormats?: boolean;
29
- formatAssertions?: boolean | null;
30
- customValidator?: (report: Report, schema: unknown, json: unknown) => void;
31
- customFormats?: Record<string, FormatValidatorFn | null>;
32
- maxRecursionDepth?: number;
33
- }
34
- export declare const defaultOptions: ZSchemaOptions;
35
- export declare const normalizeOptions: (options?: ZSchemaOptions) => ZSchemaOptions;
@@ -1,4 +0,0 @@
1
- import type { JsonSchema } from './json-schema-versions.js';
2
- export type SchemaReader = (uri: string) => JsonSchema;
3
- export declare function getSchemaReader(): SchemaReader | undefined;
4
- export declare function setSchemaReader(schemaReader: SchemaReader | undefined): void;
@@ -1 +0,0 @@
1
- export {};
@@ -1,191 +0,0 @@
1
- import type { FormatValidatorFn } from './format-validators.js';
2
- import type { JsonSchema } from './json-schema-versions.js';
3
- import type { ValidateOptions, ValidateResponse } from './z-schema-base.js';
4
- import type { ZSchemaOptions } from './z-schema-options.js';
5
- import type { SchemaReader } from './z-schema-reader.js';
6
- import './z-schema-versions.js';
7
- import { ZSchemaBase } from './z-schema-base.js';
8
- export declare class ZSchema extends ZSchemaBase {
9
- /** @internal Use ZSchema.create() instead. */
10
- constructor(options: ZSchemaOptions | undefined, token: symbol);
11
- /**
12
- * Register a global format validator available to all instances.
13
- * @param name - The format name (e.g. `'email'`, `'date'`).
14
- * @param validatorFunction - A sync or async function `(value: unknown) => boolean | Promise<boolean>`.
15
- */
16
- static registerFormat(name: string, validatorFunction: FormatValidatorFn): void;
17
- /**
18
- * Remove a globally registered format validator.
19
- * @param name - The format name to unregister.
20
- */
21
- static unregisterFormat(name: string): void;
22
- /** Returns the names of all globally registered format validators. */
23
- static getRegisteredFormats(): string[];
24
- /** Returns a deep clone of the default options. */
25
- static getDefaultOptions(): ZSchemaOptions;
26
- /**
27
- * Register a remote schema in the global cache so any instance can resolve `$ref` to it.
28
- * @param uri - The URI the schema will be known by.
29
- * @param schema - The schema object or JSON string.
30
- * @param validationOptions - Optional options used for schema preparation.
31
- */
32
- static setRemoteReference(uri: string, schema: string | JsonSchema, validationOptions?: ZSchemaOptions): void;
33
- /** Returns the current global schema reader, or `undefined` if none is set. */
34
- static getSchemaReader(): SchemaReader | undefined;
35
- /**
36
- * Set a global schema reader function used to resolve remote `$ref` URIs.
37
- * @param schemaReader - A function `(uri: string) => JsonSchema | undefined`, or `undefined` to clear.
38
- */
39
- static setSchemaReader(schemaReader: SchemaReader | undefined): void;
40
- static schemaSymbol: symbol;
41
- static jsonSymbol: symbol;
42
- /**
43
- * Create a validator instance.
44
- *
45
- * The returned type depends on the `async` and `safe` options:
46
- * - `{}` → `ZSchema` — `validate()` returns `true` or throws.
47
- * - `{ safe: true }` → `ZSchemaSafe` — `validate()` returns `{ valid, err? }`.
48
- * - `{ async: true }` → `ZSchemaAsync` — `validate()` returns `Promise<true>` or rejects.
49
- * - `{ async: true, safe: true }` → `ZSchemaAsyncSafe` — `validate()` returns `Promise<{ valid, err? }>`.
50
- *
51
- * @param options - Validator configuration. See `ZSchemaOptions` for all available settings.
52
- * @returns A validator instance of the appropriate variant.
53
- *
54
- * @example
55
- * ```ts
56
- * const validator = ZSchema.create();
57
- * validator.validate(data, schema); // throws on error
58
- *
59
- * const safe = ZSchema.create({ safe: true });
60
- * const result = safe.validate(data, schema); // { valid, err? }
61
- * ```
62
- */
63
- static create(options: ZSchemaOptions & {
64
- async: true;
65
- safe: true;
66
- }): ZSchemaAsyncSafe;
67
- static create(options: ZSchemaOptions & {
68
- async: true;
69
- }): ZSchemaAsync;
70
- static create(options: ZSchemaOptions & {
71
- safe: true;
72
- }): ZSchemaSafe;
73
- static create(options?: ZSchemaOptions): ZSchema;
74
- /**
75
- * Validate JSON data against a schema.
76
- * @param json - The data to validate.
77
- * @param schema - A JSON Schema object or a schema id string (previously registered via `validateSchema`).
78
- * @param options - Per-call options (`schemaPath`, `includeErrors`, `excludeErrors`).
79
- * @returns `true` if valid.
80
- * @throws {@link ValidateError} if validation fails, with a `details` array of structured errors.
81
- */
82
- validate(json: unknown, schema: JsonSchema | string, options?: ValidateOptions): true;
83
- /**
84
- * Validate JSON data against a schema, returning a result object instead of throwing.
85
- * @param json - The data to validate.
86
- * @param schema - A JSON Schema object or a schema id string.
87
- * @param options - Per-call options.
88
- * @returns `{ valid: true }` on success, or `{ valid: false, err: ValidateError }` on failure.
89
- */
90
- validateSafe(json: unknown, schema: JsonSchema | string, options?: ValidateOptions): ValidateResponse;
91
- /**
92
- * Validate JSON data against a schema asynchronously (supports async format validators).
93
- * @param json - The data to validate.
94
- * @param schema - A JSON Schema object or a schema id string.
95
- * @param options - Per-call options.
96
- * @returns A promise that resolves to `true` if valid.
97
- * @throws {@link ValidateError} if validation fails (the promise rejects).
98
- */
99
- validateAsync(json: unknown, schema: JsonSchema | string, options?: ValidateOptions): Promise<true>;
100
- /**
101
- * Validate JSON data against a schema asynchronously, returning a result object.
102
- * The promise always resolves (never rejects).
103
- * @param json - The data to validate.
104
- * @param schema - A JSON Schema object or a schema id string.
105
- * @param options - Per-call options.
106
- * @returns A promise resolving to `{ valid: true }` or `{ valid: false, err: ValidateError }`.
107
- */
108
- validateAsyncSafe(json: unknown, schema: JsonSchema | string, options?: ValidateOptions): Promise<ValidateResponse>;
109
- /**
110
- * Validate one or more JSON Schemas, compiling and caching them for later use with `validate()`.
111
- * @param schemaOrArr - A single schema or an array of schemas (for cross-referencing).
112
- * @returns `true` if all schemas are valid.
113
- * @throws {@link ValidateError} if any schema is invalid.
114
- */
115
- validateSchema(schemaOrArr: JsonSchema | JsonSchema[]): true;
116
- /**
117
- * Validate one or more JSON Schemas, returning a result object instead of throwing.
118
- * @param schemaOrArr - A single schema or an array of schemas.
119
- * @returns `{ valid: true }` on success, or `{ valid: false, err: ValidateError }` on failure.
120
- */
121
- validateSchemaSafe(schemaOrArr: JsonSchema | JsonSchema[]): ValidateResponse;
122
- }
123
- /**
124
- * Synchronous safe validator — `validate()` returns `{ valid, err? }` instead of throwing.
125
- * Created via `ZSchema.create({ safe: true })`.
126
- */
127
- export declare class ZSchemaSafe extends ZSchemaBase {
128
- /** @internal Use ZSchema.create() instead. */
129
- constructor(options: ZSchemaOptions | undefined, token: symbol);
130
- /**
131
- * Validate JSON data against a schema.
132
- * @param json - The data to validate.
133
- * @param schema - A JSON Schema object or a schema id string.
134
- * @param options - Per-call options.
135
- * @returns `{ valid: true }` on success, or `{ valid: false, err: ValidateError }` on failure.
136
- */
137
- validate(json: unknown, schema: JsonSchema | string, options?: ValidateOptions): ValidateResponse;
138
- /**
139
- * Validate one or more JSON Schemas.
140
- * @param schemaOrArr - A single schema or an array of schemas.
141
- * @returns `{ valid: true }` on success, or `{ valid: false, err: ValidateError }` on failure.
142
- */
143
- validateSchema(schemaOrArr: JsonSchema | JsonSchema[]): ValidateResponse;
144
- }
145
- /**
146
- * Asynchronous throw validator — `validate()` returns `Promise<true>` or rejects.
147
- * Created via `ZSchema.create({ async: true })`.
148
- */
149
- export declare class ZSchemaAsync extends ZSchemaBase {
150
- /** @internal Use ZSchema.create() instead. */
151
- constructor(options: ZSchemaOptions | undefined, token: symbol);
152
- /**
153
- * Validate JSON data against a schema asynchronously.
154
- * @param json - The data to validate.
155
- * @param schema - A JSON Schema object or a schema id string.
156
- * @param options - Per-call options.
157
- * @returns A promise that resolves to `true` if valid.
158
- * @throws {@link ValidateError} if validation fails (the promise rejects).
159
- */
160
- validate(json: unknown, schema: JsonSchema | string, options?: ValidateOptions): Promise<true>;
161
- /**
162
- * Validate one or more JSON Schemas (synchronous, throws on error).
163
- * @param schemaOrArr - A single schema or an array of schemas.
164
- * @returns `true` if all schemas are valid.
165
- * @throws {@link ValidateError} if any schema is invalid.
166
- */
167
- validateSchema(schemaOrArr: JsonSchema | JsonSchema[]): true;
168
- }
169
- /**
170
- * Asynchronous safe validator — `validate()` returns `Promise<{ valid, err? }>` (never rejects).
171
- * Created via `ZSchema.create({ async: true, safe: true })`.
172
- */
173
- export declare class ZSchemaAsyncSafe extends ZSchemaBase {
174
- /** @internal Use ZSchema.create() instead. */
175
- constructor(options: ZSchemaOptions | undefined, token: symbol);
176
- /**
177
- * Validate JSON data against a schema asynchronously.
178
- * The promise always resolves (never rejects).
179
- * @param json - The data to validate.
180
- * @param schema - A JSON Schema object or a schema id string.
181
- * @param options - Per-call options.
182
- * @returns A promise resolving to `{ valid: true }` or `{ valid: false, err: ValidateError }`.
183
- */
184
- validate(json: unknown, schema: JsonSchema | string, options?: ValidateOptions): Promise<ValidateResponse>;
185
- /**
186
- * Validate one or more JSON Schemas.
187
- * @param schemaOrArr - A single schema or an array of schemas.
188
- * @returns `{ valid: true }` on success, or `{ valid: false, err: ValidateError }` on failure.
189
- */
190
- validateSchema(schemaOrArr: JsonSchema | JsonSchema[]): ValidateResponse;
191
- }
@@ -1,69 +0,0 @@
1
- import { areEqual } from './json.js';
2
- /**
3
- * Check if all elements in an array are unique.
4
- *
5
- * Uses a Set-based fast path for arrays of pure primitives (O(n)).
6
- * Falls back to pairwise deep comparison (O(n²)) when the array contains
7
- * objects or arrays that need structural equality checks.
8
- */
9
- export const isUniqueArray = (arr, indexes, maxDepth) => {
10
- const l = arr.length;
11
- if (l <= 1)
12
- return true;
13
- // Fast path: if every element is a primitive, use a Set.
14
- // We distinguish types so that e.g. 1 !== '1' and 0 !== false.
15
- let allPrimitive = true;
16
- for (let i = 0; i < l; i++) {
17
- const v = arr[i];
18
- if (v !== null && typeof v === 'object') {
19
- allPrimitive = false;
20
- break;
21
- }
22
- }
23
- if (allPrimitive) {
24
- // Prefix each value with its type so "1" (number) !== "1" (string).
25
- const seen = new Set();
26
- for (let i = 0; i < l; i++) {
27
- const v = arr[i];
28
- const key = typeof v + ':' + String(v);
29
- if (seen.has(key)) {
30
- // Find the first occurrence for the indexes report.
31
- if (indexes) {
32
- for (let j = 0; j < i; j++) {
33
- const prev = arr[j];
34
- if (typeof prev === typeof v && prev === v) {
35
- indexes.push(j, i);
36
- break;
37
- }
38
- }
39
- }
40
- return false;
41
- }
42
- seen.add(key);
43
- }
44
- return true;
45
- }
46
- // Slow path: at least one element is an object/array — need deep comparison.
47
- for (let i = 0; i < l; i++) {
48
- for (let j = i + 1; j < l; j++) {
49
- if (areEqual(arr[i], arr[j], { maxDepth })) {
50
- if (indexes) {
51
- indexes.push(i, j);
52
- }
53
- return false;
54
- }
55
- }
56
- }
57
- return true;
58
- };
59
- export const difference = (bigSet, subSet) => {
60
- const exclusions = new Set(subSet);
61
- const arr = [];
62
- let idx = bigSet.length;
63
- while (idx--) {
64
- if (!exclusions.has(bigSet[idx])) {
65
- arr.push(bigSet[idx]);
66
- }
67
- }
68
- return arr;
69
- };
@@ -1,29 +0,0 @@
1
- const base64Pattern = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
2
- export const isValidBase64 = (value) => {
3
- if (value.length % 4 !== 0) {
4
- return false;
5
- }
6
- return base64Pattern.test(value);
7
- };
8
- export const decodeBase64 = (value) => {
9
- if (!isValidBase64(value)) {
10
- return undefined;
11
- }
12
- if (typeof atob === 'function') {
13
- try {
14
- return atob(value);
15
- }
16
- catch {
17
- return undefined;
18
- }
19
- }
20
- if (typeof Buffer !== 'undefined') {
21
- try {
22
- return Buffer.from(value, 'base64').toString('utf8');
23
- }
24
- catch {
25
- return undefined;
26
- }
27
- }
28
- return undefined;
29
- };
@@ -1,59 +0,0 @@
1
- import { DEFAULT_MAX_RECURSION_DEPTH } from './constants.js';
2
- import { copyProp } from './properties.js';
3
- export const shallowClone = (src) => {
4
- if (src == null || typeof src !== 'object') {
5
- return src;
6
- }
7
- let res;
8
- if (Array.isArray(src)) {
9
- res = [];
10
- for (let i = 0; i < src.length; i++) {
11
- res[i] = src[i];
12
- }
13
- }
14
- else {
15
- res = {};
16
- const keys = Object.keys(src).sort();
17
- for (const key of keys) {
18
- copyProp(src, res, key);
19
- }
20
- }
21
- return res;
22
- };
23
- export const deepClone = (src, maxDepth = DEFAULT_MAX_RECURSION_DEPTH) => {
24
- let vidx = 0;
25
- const visited = new Map();
26
- const cloned = [];
27
- const cloneDeepInner = (src, _depth) => {
28
- if (typeof src !== 'object' || src === null) {
29
- return src;
30
- }
31
- if (_depth >= maxDepth) {
32
- throw new Error(`Maximum recursion depth (${maxDepth}) exceeded in deepClone. ` +
33
- 'If your schema or data is deeply nested and valid, increase the maxRecursionDepth option.');
34
- }
35
- let res;
36
- const cidx = visited.get(src);
37
- if (cidx !== undefined) {
38
- return cloned[cidx];
39
- }
40
- visited.set(src, vidx++);
41
- if (Array.isArray(src)) {
42
- res = [];
43
- cloned.push(res);
44
- for (let i = 0; i < src.length; i++) {
45
- res[i] = cloneDeepInner(src[i], _depth + 1);
46
- }
47
- }
48
- else {
49
- res = {};
50
- cloned.push(res);
51
- const keys = Object.keys(src).sort();
52
- for (const key of keys) {
53
- copyProp(src, res, key, (v) => cloneDeepInner(v, _depth + 1));
54
- }
55
- }
56
- return res;
57
- };
58
- return cloneDeepInner(src, 0);
59
- };
@@ -1,19 +0,0 @@
1
- /**
2
- * Default maximum recursion depth for deeply nested schema/data traversal.
3
- * Used as the default for {@link ZSchemaOptions.maxRecursionDepth} and
4
- * internal helpers like `deepClone` and `collectIds`.
5
- */
6
- export const DEFAULT_MAX_RECURSION_DEPTH = 100;
7
- /**
8
- * Maximum allowed value for {@link ZSchemaOptions.asyncTimeout} in milliseconds.
9
- * Values exceeding this limit are clamped during option normalization to
10
- * prevent resource exhaustion (CWE-400).
11
- */
12
- export const MAX_ASYNC_TIMEOUT = 60_000;
13
- /**
14
- * Maximum allowed length for a JSON Schema `pattern` regular expression string.
15
- * Patterns exceeding this limit are rejected by {@link compileSchemaRegex} to
16
- * mitigate Regular Expression Denial-of-Service (CWE-1333) and regex injection
17
- * (CWE-95).
18
- */
19
- export const MAX_SCHEMA_REGEX_LENGTH = 10_000;
@@ -1,21 +0,0 @@
1
- const isLeapYear = (year) => year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
2
- const getDaysInMonth = (year, month) => {
3
- switch (month) {
4
- case 2:
5
- return isLeapYear(year) ? 29 : 28;
6
- case 4:
7
- case 6:
8
- case 9:
9
- case 11:
10
- return 30;
11
- default:
12
- return 31;
13
- }
14
- };
15
- export const isValidRfc3339Date = (year, month, day) => {
16
- if (month < 1 || month > 12) {
17
- return false;
18
- }
19
- const maxDay = getDaysInMonth(year, month);
20
- return day >= 1 && day <= maxDay;
21
- };
@@ -1,146 +0,0 @@
1
- import punycode from 'punycode/punycode.js';
2
- import isIPModule from 'validator/lib/isIP.js';
3
- const IDN_SEPARATOR_REGEX = /[\u3002\uff0e\uff61]/g;
4
- const IDN_SEPARATOR_TEST_REGEX = /[\u3002\uff0e\uff61]/;
5
- const splitHostnameLabels = (hostname) => {
6
- if (hostname.length === 0 || hostname.length > 255) {
7
- return null;
8
- }
9
- if (hostname.startsWith('.') || hostname.endsWith('.')) {
10
- return null;
11
- }
12
- const labels = hostname.split('.');
13
- if (labels.some((label) => label.length === 0 || label.length > 63)) {
14
- return null;
15
- }
16
- return labels;
17
- };
18
- const isAsciiHostnameLabel = (label) => /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(label);
19
- const isGreek = (char) => /\p{Script=Greek}/u.test(char);
20
- const isHebrew = (char) => /\p{Script=Hebrew}/u.test(char);
21
- const hasCjkKanaOrHan = (input) => /[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u.test(input);
22
- const toUnicodeLabel = (label) => {
23
- if (!/^xn--/i.test(label)) {
24
- return label;
25
- }
26
- try {
27
- return punycode.toUnicode(label.toLowerCase());
28
- }
29
- catch (_e) {
30
- return null;
31
- }
32
- };
33
- const isValidIdnUnicodeLabel = (label) => {
34
- if (label.startsWith('-') || label.endsWith('-')) {
35
- return false;
36
- }
37
- if (label.length >= 4 && label[2] === '-' && label[3] === '-' && !/^xn--/i.test(label)) {
38
- return false;
39
- }
40
- if (/^\p{M}/u.test(label)) {
41
- return false;
42
- }
43
- if (/[\u302e\u302f\u0640\u07fa]/u.test(label)) {
44
- return false;
45
- }
46
- for (let idx = 0; idx < label.length; idx++) {
47
- const char = label[idx];
48
- if (char === '\u00b7') {
49
- if (idx === 0 || idx === label.length - 1 || label[idx - 1] !== 'l' || label[idx + 1] !== 'l') {
50
- return false;
51
- }
52
- }
53
- if (char === '\u0375') {
54
- if (idx === label.length - 1 || !isGreek(label[idx + 1])) {
55
- return false;
56
- }
57
- }
58
- if (char === '\u05f3' || char === '\u05f4') {
59
- if (idx === 0 || !isHebrew(label[idx - 1])) {
60
- return false;
61
- }
62
- }
63
- if (char === '\u200d') {
64
- if (idx === 0 || label[idx - 1] !== '\u094d') {
65
- return false;
66
- }
67
- }
68
- }
69
- if (label.includes('\u30fb') && !hasCjkKanaOrHan(label.replace(/\u30fb/g, ''))) {
70
- return false;
71
- }
72
- const hasArabicIndic = /[\u0660-\u0669]/.test(label);
73
- const hasExtendedArabicIndic = /[\u06f0-\u06f9]/.test(label);
74
- if (hasArabicIndic && hasExtendedArabicIndic) {
75
- return false;
76
- }
77
- return true;
78
- };
79
- /*
80
- http://json-schema.org/latest/json-schema-validation.html#anchor114
81
- A string instance is valid against this attribute if it is a valid
82
- representation for an Internet host name, as defined by RFC 1034, section 3.1 [RFC1034].
83
-
84
- http://tools.ietf.org/html/rfc1034#section-3.5
85
-
86
- <digit> ::= any one of the ten digits 0 through 9
87
- var digit = /[0-9]/;
88
-
89
- <letter> ::= any one of the 52 alphabetic characters A through Z in upper case and a through z in lower case
90
- var letter = /[a-zA-Z]/;
91
-
92
- <let-dig> ::= <letter> | <digit>
93
- var letDig = /[0-9a-zA-Z]/;
94
-
95
- <let-dig-hyp> ::= <let-dig> | "-"
96
- var letDigHyp = /[-0-9a-zA-Z]/;
97
-
98
- <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
99
- var ldhStr = /[-0-9a-zA-Z]+/;
100
-
101
- <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
102
- var label = /[a-zA-Z](([-0-9a-zA-Z]+)?[0-9a-zA-Z])?/;
103
-
104
- <subdomain> ::= <label> | <subdomain> "." <label>
105
- var subdomain = /^[a-zA-Z](([-0-9a-zA-Z]+)?[0-9a-zA-Z])?(\.[a-zA-Z](([-0-9a-zA-Z]+)?[0-9a-zA-Z])?)*$/;
106
-
107
- <domain> ::= <subdomain> | " "
108
- var domain = null;
109
- */
110
- export const isValidHostname = (hostname) => {
111
- // eslint-disable-next-line no-control-regex
112
- if (IDN_SEPARATOR_TEST_REGEX.test(hostname) || /[^\x00-\x7F]/.test(hostname)) {
113
- return false;
114
- }
115
- if (isIPModule.default(hostname, 4)) {
116
- return false;
117
- }
118
- const labels = splitHostnameLabels(hostname);
119
- if (labels === null) {
120
- return false;
121
- }
122
- for (const label of labels) {
123
- if (!isAsciiHostnameLabel(label)) {
124
- return false;
125
- }
126
- const unicodeLabel = toUnicodeLabel(label);
127
- if (unicodeLabel === null || !isValidIdnUnicodeLabel(unicodeLabel)) {
128
- return false;
129
- }
130
- }
131
- return true;
132
- };
133
- export const isValidIdnHostname = (hostname) => {
134
- const normalizedHostname = hostname.replace(IDN_SEPARATOR_REGEX, '.');
135
- const labels = splitHostnameLabels(normalizedHostname);
136
- if (labels === null) {
137
- return false;
138
- }
139
- for (const label of labels) {
140
- const unicodeLabel = toUnicodeLabel(label);
141
- if (unicodeLabel === null || !isValidIdnUnicodeLabel(unicodeLabel)) {
142
- return false;
143
- }
144
- }
145
- return true;
146
- };