z-schema 8.5.0 → 9.0.1
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.
- package/README.md +101 -38
- package/bin/z-schema +16 -12
- package/cjs/index.d.ts +218 -206
- package/cjs/index.js +3012 -4688
- package/dist/errors.js +12 -0
- package/dist/format-validators.js +83 -19
- package/dist/index.js +2 -0
- package/dist/json-schema.js +3 -0
- package/dist/json-validation.js +28 -8
- package/dist/report.js +17 -6
- package/dist/schema-cache.js +4 -21
- package/dist/schema-compiler.js +6 -4
- package/dist/schema-validator.js +4 -4
- package/dist/types/errors.d.ts +10 -0
- package/dist/types/format-validators.d.ts +2 -4
- package/dist/types/index.d.ts +8 -4
- package/dist/types/json-schema.d.ts +4 -2
- package/dist/types/json-validation.d.ts +4 -4
- package/dist/types/report.d.ts +11 -19
- package/dist/types/schema-cache.d.ts +3 -5
- package/dist/types/schema-compiler.d.ts +3 -3
- package/dist/types/schema-validator.d.ts +4 -4
- package/dist/types/z-schema-base.d.ts +40 -0
- package/dist/types/z-schema-options.d.ts +31 -0
- package/dist/types/z-schema-reader.d.ts +4 -0
- package/dist/types/z-schema.d.ts +36 -80
- package/dist/utils/clone.js +5 -8
- package/dist/z-schema-base.js +257 -0
- package/dist/z-schema-options.js +88 -0
- package/dist/z-schema-reader.js +7 -0
- package/dist/z-schema.js +104 -353
- package/package.json +5 -4
- package/src/errors.ts +17 -0
- package/src/format-validators.ts +81 -24
- package/src/index.ts +10 -5
- package/src/json-schema.ts +10 -2
- package/src/json-validation.ts +58 -38
- package/src/report.ts +28 -28
- package/src/schema-cache.ts +8 -24
- package/src/schema-compiler.ts +10 -7
- package/src/schema-validator.ts +8 -7
- package/src/utils/clone.ts +5 -8
- package/src/z-schema-base.ts +318 -0
- package/src/z-schema-options.ts +126 -0
- package/src/z-schema-reader.ts +14 -0
- package/src/z-schema.ts +123 -461
- package/umd/ZSchema.js +4380 -6051
- package/umd/ZSchema.min.js +1 -1
package/README.md
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
- [What](#what)
|
|
10
10
|
- [Versions](#versions)
|
|
11
|
+
- [Getting started](#getting-started)
|
|
11
12
|
- [Usage](#usage)
|
|
12
13
|
- [Features](#features)
|
|
13
14
|
- [Options](#options)
|
|
@@ -22,28 +23,40 @@ What is a JSON Schema? Find here: [https://json-schema.org/](https://json-schema
|
|
|
22
23
|
|
|
23
24
|
- v6 - old version which has been around a long time, supports JSON Schema draft-04
|
|
24
25
|
- v7 - modernized version (to ESM module with Typescript) which passes all tests from JSON Schema Test Suite for draft-04
|
|
25
|
-
- v8 - by default assumes all schemas without $schema tag are draft-04, the old behaviour from v7 can be explicitly turned on by specifying `validator =
|
|
26
|
+
- v8 - by default assumes all schemas without $schema tag are draft-04, the old behaviour from v7 can be explicitly turned on by specifying `validator = ZSchema.create({ version: 'none' });`
|
|
27
|
+
- v9 - new api, `new ZSchema()` replaced by `ZSchema.create()` for initialization
|
|
26
28
|
|
|
27
|
-
##
|
|
29
|
+
## Getting started
|
|
28
30
|
|
|
29
31
|
Validator will try to perform sync validation when possible for speed, but supports async callbacks when they are necessary.
|
|
30
32
|
|
|
31
33
|
### ESM and Typescript:
|
|
32
34
|
|
|
33
|
-
```
|
|
35
|
+
```typescript
|
|
34
36
|
import ZSchema from 'z-schema';
|
|
35
|
-
const validator =
|
|
36
|
-
console.log(validator.validate(1, { type: 'number' })); // true
|
|
37
|
-
console.log(validator.validate(1, { type: 'string' })); // false
|
|
37
|
+
const validator = ZSchema.create();
|
|
38
38
|
```
|
|
39
39
|
|
|
40
40
|
### CommonJs:
|
|
41
41
|
|
|
42
42
|
```javascript
|
|
43
43
|
const ZSchema = require('z-schema');
|
|
44
|
-
const validator =
|
|
45
|
-
|
|
46
|
-
|
|
44
|
+
const validator = ZSchema.create();
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### Browser:
|
|
48
|
+
|
|
49
|
+
```html
|
|
50
|
+
<script type="text/javascript" src="z-schema/umd/ZSchema.min.js"></script>
|
|
51
|
+
<script type="text/javascript">
|
|
52
|
+
var validator = ZSchema.create();
|
|
53
|
+
try {
|
|
54
|
+
validator.validate('string', { type: 'string' });
|
|
55
|
+
console.log('Validation passed');
|
|
56
|
+
} catch (error) {
|
|
57
|
+
console.log('Validation failed:', error.details);
|
|
58
|
+
}
|
|
59
|
+
</script>
|
|
47
60
|
```
|
|
48
61
|
|
|
49
62
|
### CLI:
|
|
@@ -56,14 +69,68 @@ z-schema mySchema.json myJson.json
|
|
|
56
69
|
z-schema --strictMode mySchema.json myJson.json
|
|
57
70
|
```
|
|
58
71
|
|
|
72
|
+
## Usage
|
|
73
|
+
|
|
74
|
+
### Schema Validation
|
|
75
|
+
|
|
76
|
+
You can pre-validate and compile schemas using the `validateSchema` method. This is useful for server startup to ensure all schemas are valid and to resolve `$ref` references between schemas.
|
|
77
|
+
|
|
78
|
+
```javascript
|
|
79
|
+
const schemas = [
|
|
80
|
+
{
|
|
81
|
+
id: 'personDetails',
|
|
82
|
+
type: 'object',
|
|
83
|
+
properties: {
|
|
84
|
+
firstName: { type: 'string' },
|
|
85
|
+
lastName: { type: 'string' },
|
|
86
|
+
},
|
|
87
|
+
required: ['firstName', 'lastName'],
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
id: 'addressDetails',
|
|
91
|
+
type: 'object',
|
|
92
|
+
properties: {
|
|
93
|
+
street: { type: 'string' },
|
|
94
|
+
city: { type: 'string' },
|
|
95
|
+
},
|
|
96
|
+
required: ['street', 'city'],
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
id: 'personWithAddress',
|
|
100
|
+
allOf: [{ $ref: 'personDetails' }, { $ref: 'addressDetails' }],
|
|
101
|
+
},
|
|
102
|
+
];
|
|
103
|
+
|
|
104
|
+
try {
|
|
105
|
+
validator.validateSchema(schemas);
|
|
106
|
+
console.log('All schemas are valid and compiled');
|
|
107
|
+
} catch (error) {
|
|
108
|
+
console.log('Schema validation failed:', error.details);
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
59
112
|
### Sync mode:
|
|
60
113
|
|
|
114
|
+
The `validate` method automatically compiles and validates the schema before validating the JSON data against it. For better performance, you can pre-compile schemas using `validateSchema` during initialization.
|
|
115
|
+
|
|
61
116
|
```javascript
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
117
|
+
try {
|
|
118
|
+
validator.validate(json, schema);
|
|
119
|
+
// validation passed
|
|
120
|
+
} catch (error) {
|
|
121
|
+
// this will return a native error object with name and message
|
|
122
|
+
console.log(error.name); // 'z-schema validation error'
|
|
123
|
+
console.log(error.message); // common error message
|
|
124
|
+
// this will return an array of validation errors encountered
|
|
125
|
+
console.log(error.details); // array of detailed errors
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Or use validateSafe for object-based result
|
|
129
|
+
const result = validator.validateSafe(json, schema);
|
|
130
|
+
if (!result.valid) {
|
|
131
|
+
console.log(result.errs); // array of error objects
|
|
132
|
+
}
|
|
133
|
+
|
|
67
134
|
...
|
|
68
135
|
```
|
|
69
136
|
|
|
@@ -80,7 +147,7 @@ import ZSchema from 'z-schema';
|
|
|
80
147
|
import db from './db';
|
|
81
148
|
|
|
82
149
|
// Initialize ZSchema
|
|
83
|
-
const validator =
|
|
150
|
+
const validator = ZSchema.create();
|
|
84
151
|
|
|
85
152
|
// Register async and sync format validators
|
|
86
153
|
validator.registerFormat('user-exists', async (input: unknown): Promise<boolean> => {
|
|
@@ -137,56 +204,52 @@ const payload = {
|
|
|
137
204
|
|
|
138
205
|
// Validate asynchronously
|
|
139
206
|
try {
|
|
140
|
-
|
|
207
|
+
const validator = ZSchema.create({ async: true });
|
|
208
|
+
await validator.validate(payload, personSchema);
|
|
141
209
|
console.log('✅ Validation successful!');
|
|
142
210
|
} catch (err) {
|
|
143
211
|
console.log('❌ Validation failed:', err);
|
|
144
212
|
}
|
|
145
213
|
|
|
146
214
|
// or validate without try-catch
|
|
147
|
-
const
|
|
215
|
+
const validator = ZSchema.create({ async: true, safe: true });
|
|
216
|
+
const res = await validator.validate(payload, personSchema);
|
|
148
217
|
if (res.valid) {
|
|
149
218
|
console.log('✅ Validation successful!');
|
|
150
219
|
} else {
|
|
151
|
-
console.log('❌ Validation failed:', res.
|
|
220
|
+
console.log('❌ Validation failed:', res.err);
|
|
152
221
|
}
|
|
153
222
|
```
|
|
154
223
|
|
|
155
|
-
### Browser:
|
|
156
|
-
|
|
157
|
-
```html
|
|
158
|
-
<script type="text/javascript" src="z-schema/umd/ZSchema.min.js"></script>
|
|
159
|
-
<script type="text/javascript">
|
|
160
|
-
var validator = new ZSchema();
|
|
161
|
-
console.log(validator.validate('string', { type: 'string' }));
|
|
162
|
-
</script>
|
|
163
|
-
```
|
|
164
|
-
|
|
165
224
|
### Remote references and schemas:
|
|
166
225
|
|
|
167
226
|
In case you have some remote references in your schemas, you have to download those schemas before using validator.
|
|
168
227
|
Otherwise you'll get `UNRESOLVABLE_REFERENCE` error when trying to compile a schema.
|
|
169
228
|
|
|
170
229
|
```javascript
|
|
171
|
-
var validator =
|
|
230
|
+
var validator = ZSchema.create();
|
|
172
231
|
var json = {};
|
|
173
232
|
var schema = { "$ref": "http://json-schema.org/draft-04/schema#" };
|
|
174
233
|
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
//
|
|
178
|
-
|
|
179
|
-
//
|
|
234
|
+
try {
|
|
235
|
+
validator.validate(json, schema);
|
|
236
|
+
// This won't reach here due to unresolvable reference
|
|
237
|
+
} catch (error) {
|
|
238
|
+
// error.details will contain the validation errors
|
|
239
|
+
console.log(error.details[0].code); // "UNRESOLVABLE_REFERENCE"
|
|
240
|
+
}
|
|
180
241
|
|
|
181
242
|
var requiredUrl = "http://json-schema.org/draft-04/schema";
|
|
182
243
|
request(requiredUrl, function (error, response, body) {
|
|
183
244
|
|
|
184
245
|
validator.setRemoteReference(requiredUrl, JSON.parse(body));
|
|
185
246
|
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
247
|
+
try {
|
|
248
|
+
validator.validate(json, schema);
|
|
249
|
+
// validation passed
|
|
250
|
+
} catch (error) {
|
|
251
|
+
// shouldn't happen after setting remote reference
|
|
252
|
+
}
|
|
190
253
|
|
|
191
254
|
}
|
|
192
255
|
```
|
package/bin/z-schema
CHANGED
|
@@ -44,10 +44,11 @@ program
|
|
|
44
44
|
|
|
45
45
|
var options = {};
|
|
46
46
|
var defaultOptions = ZSchema.getDefaultOptions();
|
|
47
|
+
var programOptions = program._optionValues; // { breakOnFirstError: true }
|
|
47
48
|
|
|
48
49
|
for (var key in defaultOptions) {
|
|
49
|
-
if (
|
|
50
|
-
options[key] =
|
|
50
|
+
if (programOptions[key] != null) {
|
|
51
|
+
options[key] = programOptions[key];
|
|
51
52
|
}
|
|
52
53
|
}
|
|
53
54
|
|
|
@@ -72,28 +73,31 @@ function readJson(fileName) {
|
|
|
72
73
|
return ret;
|
|
73
74
|
}
|
|
74
75
|
|
|
75
|
-
var validator =
|
|
76
|
+
var validator = ZSchema.create(options);
|
|
76
77
|
var schemaFilePath = program.args.shift();
|
|
77
78
|
var schema = readJson(schemaFilePath);
|
|
79
|
+
schema.id = schemaFilePath;
|
|
78
80
|
|
|
79
81
|
function validateWithAutomaticDownloads(filePath, data, schema, callback) {
|
|
80
82
|
var lastResult;
|
|
83
|
+
var lastErrors;
|
|
81
84
|
|
|
82
85
|
function finish() {
|
|
83
|
-
callback(
|
|
86
|
+
callback(lastErrors, lastResult);
|
|
84
87
|
}
|
|
85
88
|
|
|
86
89
|
function validate() {
|
|
87
90
|
if (data !== undefined) {
|
|
88
|
-
|
|
91
|
+
var result = validator.validateSafe(data, schema);
|
|
92
|
+
lastResult = result.valid;
|
|
93
|
+
lastErrors = result.valid ? null : result.err.details;
|
|
89
94
|
} else {
|
|
90
|
-
|
|
95
|
+
var result = validator.validateSchemaSafe(schema);
|
|
96
|
+
lastResult = result.valid;
|
|
97
|
+
lastErrors = result.valid ? null : result.err.details;
|
|
91
98
|
}
|
|
92
99
|
|
|
93
|
-
|
|
94
|
-
// console.log(JSON.stringify(validator.getLastErrors(), null, 4));
|
|
95
|
-
|
|
96
|
-
var missingReferences = validator.getMissingRemoteReferences();
|
|
100
|
+
var missingReferences = validator.getMissingRemoteReferences(result.err);
|
|
97
101
|
if (missingReferences.length > 0) {
|
|
98
102
|
var finished = 0;
|
|
99
103
|
missingReferences.forEach(function (url) {
|
|
@@ -150,7 +154,7 @@ function validateJsons() {
|
|
|
150
154
|
var json = readJson(filePath);
|
|
151
155
|
validateWithAutomaticDownloads(filePath, json, schema, function (errs, isValid) {
|
|
152
156
|
if (!isValid) {
|
|
153
|
-
console.log(JSON.stringify(
|
|
157
|
+
console.log(JSON.stringify(errs, null, 4));
|
|
154
158
|
console.log('json #' + i + ' validation failed');
|
|
155
159
|
process.exitCode = 1;
|
|
156
160
|
} else {
|
|
@@ -163,7 +167,7 @@ function validateJsons() {
|
|
|
163
167
|
// validate schema
|
|
164
168
|
validateWithAutomaticDownloads(schemaFilePath, undefined, schema, function (errs, isValid) {
|
|
165
169
|
if (!isValid) {
|
|
166
|
-
console.log(JSON.stringify(
|
|
170
|
+
console.log(JSON.stringify(errs, null, 4));
|
|
167
171
|
console.log('schema validation failed');
|
|
168
172
|
process.exit(1);
|
|
169
173
|
} else {
|