@cleverbrush/schema 1.0.0-beta.0 → 1.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/package.json +2 -2
  2. package/src/builders/UnionSchemaBuilder.ts +1 -6
  3. package/src/index.ts +1 -13
  4. package/src/schema.ts +9 -104
  5. package/src/schemaRegistry.builders.test.ts +35 -80
  6. package/src/schemaRegistry.test.ts +2 -1916
  7. package/src/schemaRegistry.ts +55 -126
  8. package/dist/builders/AliasSchemaBuilder.d.ts +0 -14
  9. package/dist/builders/AliasSchemaBuilder.js +0 -91
  10. package/dist/builders/ArraySchemaBuilder.d.ts +0 -15
  11. package/dist/builders/ArraySchemaBuilder.js +0 -141
  12. package/dist/builders/BooleanSchemaBuilder.d.ts +0 -31
  13. package/dist/builders/BooleanSchemaBuilder.js +0 -90
  14. package/dist/builders/FunctionSchemaBuilder.d.ts +0 -25
  15. package/dist/builders/FunctionSchemaBuilder.js +0 -66
  16. package/dist/builders/NumberSchemaBuilder.d.ts +0 -61
  17. package/dist/builders/NumberSchemaBuilder.js +0 -206
  18. package/dist/builders/ObjectSchemaBuilder.d.ts +0 -83
  19. package/dist/builders/ObjectSchemaBuilder.js +0 -344
  20. package/dist/builders/SchemaBuilder.d.ts +0 -36
  21. package/dist/builders/SchemaBuilder.js +0 -88
  22. package/dist/builders/StringSchemaBuilder.d.ts +0 -14
  23. package/dist/builders/StringSchemaBuilder.js +0 -140
  24. package/dist/builders/UnionSchemaBuilder.d.ts +0 -10
  25. package/dist/builders/UnionSchemaBuilder.js +0 -100
  26. package/dist/defaultSchemas.d.ts +0 -4
  27. package/dist/defaultSchemas.js +0 -45
  28. package/dist/index.d.ts +0 -42
  29. package/dist/index.js +0 -35
  30. package/dist/schema.d.ts +0 -242
  31. package/dist/schema.js +0 -2
  32. package/dist/schemaRegistry.d.ts +0 -54
  33. package/dist/schemaRegistry.js +0 -301
  34. package/dist/validators/validateArray.d.ts +0 -3
  35. package/dist/validators/validateArray.js +0 -60
  36. package/dist/validators/validateBoolean.d.ts +0 -2
  37. package/dist/validators/validateBoolean.js +0 -30
  38. package/dist/validators/validateFunction.d.ts +0 -2
  39. package/dist/validators/validateFunction.js +0 -21
  40. package/dist/validators/validateNumber.d.ts +0 -2
  41. package/dist/validators/validateNumber.js +0 -69
  42. package/dist/validators/validateObject.d.ts +0 -3
  43. package/dist/validators/validateObject.js +0 -95
  44. package/dist/validators/validateString.d.ts +0 -2
  45. package/dist/validators/validateString.js +0 -50
  46. package/dist/validators/validateUnion.d.ts +0 -3
  47. package/dist/validators/validateUnion.js +0 -30
  48. package/src/builders/AliasSchemaBuilder.test.ts +0 -124
  49. package/src/builders/AliasSchemaBuilder.ts +0 -250
@@ -1,301 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const validateNumber_js_1 = require("./validators/validateNumber.js");
4
- const validateBoolean_js_1 = require("./validators/validateBoolean.js");
5
- const validateString_js_1 = require("./validators/validateString.js");
6
- const validateArray_js_1 = require("./validators/validateArray.js");
7
- const validateObject_js_1 = require("./validators/validateObject.js");
8
- const validateUnion_js_1 = require("./validators/validateUnion.js");
9
- const validateFunction_js_1 = require("./validators/validateFunction.js");
10
- const NumberSchemaBuilder_js_1 = require("./builders/NumberSchemaBuilder.js");
11
- const UnionSchemaBuilder_js_1 = require("./builders/UnionSchemaBuilder.js");
12
- const ObjectSchemaBuilder_js_1 = require("./builders/ObjectSchemaBuilder.js");
13
- const StringSchemaBuilder_js_1 = require("./builders/StringSchemaBuilder.js");
14
- const BooleanSchemaBuilder_js_1 = require("./builders/BooleanSchemaBuilder.js");
15
- const ArraySchemaBuilder_js_1 = require("./builders/ArraySchemaBuilder.js");
16
- const AliasSchemaBuilder_js_1 = require("./builders/AliasSchemaBuilder.js");
17
- const FunctionSchemaBuilder_js_1 = require("./builders/FunctionSchemaBuilder.js");
18
- const defaultSchemas_js_1 = require("./defaultSchemas.js");
19
- const SchemaBuilder_js_1 = require("./builders/SchemaBuilder.js");
20
- const defaultSchemaNames = ['string', 'boolean', 'number', 'array', 'function'];
21
- const defaultSchemasValidationStrategies = {
22
- number: (obj, schema) => (0, validateNumber_js_1.validateNumber)(obj, schema),
23
- boolean: (obj, schema) => (0, validateBoolean_js_1.validateBoolean)(obj, schema),
24
- string: (obj, schema) => (0, validateString_js_1.validateString)(obj, schema),
25
- array: (obj, schema, validator) => (0, validateArray_js_1.validateArray)(obj, schema, validator),
26
- function: (obj, schema) => (0, validateFunction_js_1.validateFunction)(obj, schema)
27
- };
28
- const isDefaultType = (name) => defaultSchemaNames.indexOf(name) !== -1;
29
- class SchemaRegistry {
30
- _schemasMap = new Map();
31
- _schemasCache = null;
32
- _preprocessorsMap = new Map();
33
- get preprocessors() {
34
- return this._preprocessorsMap;
35
- }
36
- addPreprocessor(name, preprocessor) {
37
- if (this._preprocessorsMap.has(name))
38
- throw new Error(`Preprocessor '${name}' is already registered`);
39
- if (typeof preprocessor !== 'function') {
40
- throw new Error('preprocessor must be a function');
41
- }
42
- this._preprocessorsMap.set(name, preprocessor);
43
- return this;
44
- }
45
- addSchemaFrom(oldName, name, param) {
46
- if (!this._schemasMap.has(oldName.toString())) {
47
- throw new Error(`unknown schema name ${oldName.toString()}`);
48
- }
49
- const oldSchema = this._schemasMap.get(oldName.toString());
50
- const schema = typeof param === 'function'
51
- ? param({
52
- schema: oldSchema,
53
- alias: AliasSchemaBuilder_js_1.alias,
54
- array: ArraySchemaBuilder_js_1.array,
55
- boolean: BooleanSchemaBuilder_js_1.boolean,
56
- func: FunctionSchemaBuilder_js_1.func,
57
- number: NumberSchemaBuilder_js_1.number,
58
- object: ObjectSchemaBuilder_js_1.object,
59
- string: StringSchemaBuilder_js_1.string,
60
- union: UnionSchemaBuilder_js_1.union
61
- })
62
- : param;
63
- if (Array.isArray(schema)) {
64
- this._schemasMap.set(name.toString(), schema);
65
- this._schemasCache = null;
66
- return this;
67
- }
68
- if (typeof schema !== 'object')
69
- throw new Error('Array or Object is required');
70
- this._schemasMap.set(name.toString(), {
71
- ...(schema instanceof SchemaBuilder_js_1.SchemaBuilder
72
- ? schema._schema
73
- : schema)
74
- });
75
- this._schemasCache = null;
76
- return this;
77
- }
78
- addSchema(name, param) {
79
- if (typeof name !== 'string' || !name)
80
- throw new Error('Name is required');
81
- if (isDefaultType(name.toString()))
82
- throw new Error(`You can't add a schema named "${name}" because it's a name of a default schema, please consider another name to be used`);
83
- if (this._schemasMap.has(name.toString())) {
84
- throw new Error(`Schema "${name}" already exists`);
85
- }
86
- const schema = typeof param === 'function'
87
- ? param({
88
- alias: AliasSchemaBuilder_js_1.alias,
89
- external: AliasSchemaBuilder_js_1.externalAlias,
90
- array: ArraySchemaBuilder_js_1.array,
91
- boolean: BooleanSchemaBuilder_js_1.boolean,
92
- number: NumberSchemaBuilder_js_1.number,
93
- object: ObjectSchemaBuilder_js_1.object,
94
- string: StringSchemaBuilder_js_1.string,
95
- union: UnionSchemaBuilder_js_1.union,
96
- func: FunctionSchemaBuilder_js_1.func
97
- })
98
- : param;
99
- if (Array.isArray(schema)) {
100
- this._schemasMap.set(name.toString(), schema);
101
- this._schemasCache = null;
102
- return this;
103
- }
104
- if (typeof schema !== 'object')
105
- throw new Error('Array or Object is required');
106
- this._schemasMap.set(name.toString(), schema instanceof SchemaBuilder_js_1.SchemaBuilder ? schema.clone() : schema);
107
- this._schemasCache = null;
108
- return this;
109
- }
110
- get schemas() {
111
- if (this._schemasCache)
112
- return this._schemasCache;
113
- const res = {};
114
- for (const key of this._schemasMap.keys()) {
115
- const parts = key.split('.');
116
- let curr = res;
117
- for (let i = 0; i < parts.length; i++) {
118
- if (i === parts.length - 1) {
119
- curr[parts[i]] = {
120
- validate: async (value) => {
121
- const result = await this.validate(this._schemasMap.get(key), value);
122
- if (!result.valid) {
123
- return result;
124
- }
125
- return {
126
- ...result,
127
- object: value
128
- };
129
- },
130
- schema: this._schemasMap.get(key)
131
- };
132
- }
133
- else {
134
- if (typeof curr[parts[i]] === 'undefined') {
135
- curr[parts[i]] = {};
136
- }
137
- }
138
- curr = curr[parts[i]];
139
- }
140
- }
141
- this._schemasCache = res;
142
- return this._schemasCache;
143
- }
144
- async validateDefaultType(name, value, mergeSchema) {
145
- const strategy = defaultSchemasValidationStrategies[name];
146
- let finalSchema = defaultSchemas_js_1.defaultSchemas[name];
147
- if (strategy) {
148
- if (typeof mergeSchema === 'object' && mergeSchema) {
149
- finalSchema = Object.assign({}, finalSchema, mergeSchema);
150
- }
151
- if (typeof mergeSchema === 'number') {
152
- finalSchema = {
153
- ...finalSchema,
154
- equals: mergeSchema
155
- };
156
- mergeSchema;
157
- }
158
- let preliminaryResult = await strategy(value, finalSchema, this);
159
- if (!preliminaryResult.valid)
160
- return preliminaryResult;
161
- preliminaryResult = await this.checkValidators(finalSchema, value);
162
- return preliminaryResult;
163
- }
164
- throw new Error('not implemented');
165
- }
166
- async checkValidators(schema, value) {
167
- if (!schema.isRequired && typeof value === 'undefined') {
168
- return {
169
- valid: true
170
- };
171
- }
172
- if (Array.isArray(schema.validators)) {
173
- const validatorsResults = await Promise.allSettled(schema.validators.map((v) => Promise.resolve(v(value))));
174
- const rejections = validatorsResults
175
- .filter((f) => f.status === 'rejected')
176
- .map((f) => f.reason);
177
- const errors = validatorsResults
178
- .filter((f) => f.status === 'fulfilled' &&
179
- typeof f.value !== 'boolean' &&
180
- f.value.valid === false)
181
- .map((f) => f.value)
182
- .map((f) => f.errors);
183
- if (rejections.length === 0 && errors.length === 0) {
184
- return {
185
- valid: true
186
- };
187
- }
188
- return {
189
- valid: false,
190
- errors: [...rejections, ...errors]
191
- };
192
- }
193
- return {
194
- valid: true
195
- };
196
- }
197
- async validate(schemaToValidate, obj) {
198
- if (!schemaToValidate)
199
- throw new Error('schemaName is required');
200
- const schema = schemaToValidate instanceof SchemaBuilder_js_1.SchemaBuilder
201
- ? schemaToValidate._schema
202
- : schemaToValidate;
203
- if (typeof schema === 'string') {
204
- if (isDefaultType(schema)) {
205
- return await this.validateDefaultType(schema, obj);
206
- }
207
- else if (typeof this._schemasMap.get(schema) !== 'undefined') {
208
- if (Array.isArray(this._schemasMap.get(schema))) {
209
- return this.validate(this._schemasMap.get(schema), obj);
210
- }
211
- const objSchema = Object.assign({}, defaultSchemas_js_1.defaultSchemas.object, this._schemasMap.get(schema));
212
- const res = await (0, validateObject_js_1.validateObject)(obj, objSchema, this);
213
- if (!res.valid)
214
- return res;
215
- return await this.checkValidators(objSchema, obj);
216
- }
217
- else {
218
- return await this.validateDefaultType('string', obj, {
219
- type: 'string',
220
- equals: schema
221
- });
222
- }
223
- }
224
- if (Array.isArray(schema)) {
225
- for (let i = 0; i < schema.length; i++) {
226
- const res = await this.validate(schema[i], obj);
227
- if (res.valid) {
228
- return res;
229
- }
230
- }
231
- return {
232
- valid: false,
233
- errors: ['object does not match any schema']
234
- };
235
- }
236
- if (typeof schema === 'number') {
237
- return await this.validateDefaultType('number', obj, schema);
238
- }
239
- if (typeof schema === 'object') {
240
- const spec = schema;
241
- if (typeof spec.type !== 'string')
242
- throw new Error('Schema has no type');
243
- if (isDefaultType(spec.type)) {
244
- return await this.validateDefaultType(spec.type, obj, schema);
245
- }
246
- else if (spec.type === 'alias') {
247
- if (spec.isRequired === false && typeof obj === 'undefined') {
248
- return {
249
- valid: true
250
- };
251
- }
252
- if (spec.isNullable === true && obj === null) {
253
- return {
254
- valid: true
255
- };
256
- }
257
- const registry = (spec.externalRegistry ||
258
- this);
259
- const alias = registry._schemasMap.get(spec.schemaName);
260
- if (typeof alias === 'undefined') {
261
- throw new Error(`Unknown schema alias - ${spec.schemaName}`);
262
- }
263
- if (Array.isArray(alias)) {
264
- if ((!spec.isRequired && typeof obj === 'undefined') ||
265
- (spec.isNullable && obj === null)) {
266
- return {
267
- valid: true
268
- };
269
- }
270
- return await registry.validate(alias, obj);
271
- }
272
- if (typeof alias !== 'object')
273
- throw new Error('it is only possible to use a full schema schema definition as alias');
274
- let schemaToValidate = alias;
275
- if (alias instanceof SchemaBuilder_js_1.SchemaBuilder) {
276
- if (typeof schema.isRequired === 'boolean') {
277
- schemaToValidate = schemaToValidate[schema.isRequired ? 'required' : 'optional']();
278
- }
279
- if (typeof schema.isNullable === 'boolean') {
280
- schemaToValidate = schemaToValidate[schema.isNullable ? 'nullable' : 'notNullable']();
281
- }
282
- }
283
- return await registry.validate(schemaToValidate, obj);
284
- }
285
- else if (spec.type === 'union') {
286
- return await (0, validateUnion_js_1.validateUnion)(obj, spec, this);
287
- }
288
- else if (spec.type === 'object') {
289
- const preliminaryResult = await (0, validateObject_js_1.validateObject)(obj, schema, this);
290
- if (!preliminaryResult.valid)
291
- return preliminaryResult;
292
- return await this.checkValidators(schema, obj);
293
- }
294
- else if (spec.type === 'function') {
295
- return await (0, validateFunction_js_1.validateFunction)(obj, spec);
296
- }
297
- }
298
- throw new Error("Couldn't understand the Schema provided");
299
- }
300
- }
301
- exports.default = SchemaRegistry;
@@ -1,3 +0,0 @@
1
- import { ArraySchema, ValidationResult } from '../schema.js';
2
- import SchemaRegistry from '../schemaRegistry.js';
3
- export declare const validateArray: (obj: any, schema: ArraySchema<any>, validator: SchemaRegistry<any>) => Promise<ValidationResult>;
@@ -1,60 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateArray = void 0;
4
- const validateArray = async (obj, schema, validator) => {
5
- if (typeof obj === 'undefined' &&
6
- typeof schema === 'object' &&
7
- schema.isRequired === false) {
8
- return {
9
- valid: true
10
- };
11
- }
12
- if (!Array.isArray(obj))
13
- return {
14
- valid: false,
15
- errors: ['expected type array']
16
- };
17
- if (schema.preprocessor) {
18
- const preprocessor = typeof schema.preprocessor === 'function'
19
- ? schema.preprocessor
20
- : validator.preprocessors.get(schema.preprocessor);
21
- if (typeof preprocessor !== 'function') {
22
- throw new Error(`unknown preprocessor '${schema.preprocessor}'`);
23
- }
24
- for (let i = 0; i < obj.length; i++) {
25
- obj[i] = await Promise.resolve(preprocessor(obj[i]));
26
- }
27
- }
28
- if (typeof schema.minLength === 'number' && obj.length < schema.minLength) {
29
- return {
30
- valid: false,
31
- errors: [`expected to be at least ${schema.minLength} chars long`]
32
- };
33
- }
34
- if (typeof schema.maxLength === 'number' && obj.length > schema.maxLength) {
35
- return {
36
- valid: false,
37
- errors: [`expected to be at most ${schema.maxLength} chars long`]
38
- };
39
- }
40
- if (typeof schema.ofType !== 'undefined') {
41
- const results = await Promise.all(obj.map((i) => validator.validate(schema.ofType, i)));
42
- const errors = results
43
- .filter((r) => !r.valid)
44
- .map((r) => r.errors)
45
- .flat(Infinity);
46
- if (errors.length) {
47
- return {
48
- valid: false,
49
- errors
50
- };
51
- }
52
- return {
53
- valid: true
54
- };
55
- }
56
- return {
57
- valid: true
58
- };
59
- };
60
- exports.validateArray = validateArray;
@@ -1,2 +0,0 @@
1
- import { BooleanSchema, ValidationResult } from '../schema.js';
2
- export declare const validateBoolean: (obj: any, schema: BooleanSchema) => Promise<ValidationResult>;
@@ -1,30 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateBoolean = void 0;
4
- const validateBoolean = async (obj, schema) => {
5
- if (typeof obj === 'undefined' &&
6
- typeof schema === 'object' &&
7
- schema.isRequired === false) {
8
- return {
9
- valid: true
10
- };
11
- }
12
- if (typeof obj !== 'boolean')
13
- return {
14
- valid: false,
15
- errors: [`expected type boolean, but saw ${typeof obj}`]
16
- };
17
- const bool = obj;
18
- if (typeof schema.equals === 'boolean') {
19
- return schema.equals === bool
20
- ? { valid: true }
21
- : {
22
- valid: false,
23
- errors: [`must be equal to ${schema.equals}`]
24
- };
25
- }
26
- return {
27
- valid: true
28
- };
29
- };
30
- exports.validateBoolean = validateBoolean;
@@ -1,2 +0,0 @@
1
- import { FunctionSchema, ValidationResult } from '../schema.js';
2
- export declare const validateFunction: (obj: any, schema: FunctionSchema) => Promise<ValidationResult>;
@@ -1,21 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateFunction = void 0;
4
- const validateFunction = async (obj, schema) => {
5
- if (typeof obj === 'undefined' &&
6
- typeof schema === 'object' &&
7
- schema.isRequired === false) {
8
- return {
9
- valid: true
10
- };
11
- }
12
- if (typeof obj !== 'function')
13
- return {
14
- valid: false,
15
- errors: [`expected type function, but saw ${typeof obj}`]
16
- };
17
- return {
18
- valid: true
19
- };
20
- };
21
- exports.validateFunction = validateFunction;
@@ -1,2 +0,0 @@
1
- import { NumberSchema, ValidationResult } from '../schema.js';
2
- export declare const validateNumber: (obj: any, schema: NumberSchema) => Promise<ValidationResult>;
@@ -1,69 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateNumber = void 0;
4
- const validateNumber = async (obj, schema) => {
5
- if (typeof obj === 'undefined' &&
6
- typeof schema === 'object' &&
7
- schema.isRequired === false) {
8
- return {
9
- valid: true
10
- };
11
- }
12
- if (typeof obj !== 'number')
13
- return {
14
- valid: false,
15
- errors: [`expected type number, but saw ${typeof obj}`]
16
- };
17
- if (typeof schema === 'number') {
18
- return obj === schema
19
- ? { valid: true }
20
- : {
21
- valid: false,
22
- errors: [`should be equal to ${schema}`]
23
- };
24
- }
25
- const num = obj;
26
- if (schema.ensureNotNaN && Number.isNaN(num)) {
27
- return {
28
- valid: false,
29
- errors: ['is not expected to be NaN']
30
- };
31
- }
32
- if (schema.ensureIsFinite &&
33
- !Number.isFinite(num) &&
34
- schema.ensureNotNaN &&
35
- !Number.isNaN(num)) {
36
- return {
37
- valid: false,
38
- errors: ['is expected to be a finite number']
39
- };
40
- }
41
- if (typeof schema.equals !== 'undefined' && num !== schema.equals) {
42
- return {
43
- valid: false,
44
- errors: [`expected to be equal to ${schema.equals}`]
45
- };
46
- }
47
- if (typeof schema.min !== 'undefined') {
48
- if (typeof schema.min !== 'number')
49
- throw new Error('min constraint should be a number');
50
- if (num < schema.min)
51
- return {
52
- valid: false,
53
- errors: [`expected to be at least ${schema.min}`]
54
- };
55
- }
56
- if (typeof schema.max !== 'undefined') {
57
- if (typeof schema.max !== 'number')
58
- throw new Error('max constraint should be a number');
59
- if (num > schema.max)
60
- return {
61
- valid: false,
62
- errors: [`expected to be no more than ${schema.max}`]
63
- };
64
- }
65
- return {
66
- valid: true
67
- };
68
- };
69
- exports.validateNumber = validateNumber;
@@ -1,3 +0,0 @@
1
- import { ObjectSchema, ValidationResult } from '../schema.js';
2
- import SchemaRegistry from '../schemaRegistry.js';
3
- export declare const validateObject: (obj: any, schema: ObjectSchema<any>, validator: SchemaRegistry<any>) => Promise<ValidationResult>;
@@ -1,95 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateObject = void 0;
4
- const validateObject = async (obj, schema, validator) => {
5
- if (typeof obj === 'undefined' &&
6
- typeof schema === 'object' &&
7
- schema.isRequired === false) {
8
- return {
9
- valid: true
10
- };
11
- }
12
- if (typeof obj !== 'object') {
13
- return {
14
- valid: false,
15
- errors: [
16
- `expected to have type='object', but saw '${typeof obj}' instead`
17
- ]
18
- };
19
- }
20
- if (typeof schema.preprocessors === 'object' && schema.preprocessors) {
21
- await Promise.all(Object.keys(schema.preprocessors).map(async (key) => {
22
- if (key === '*')
23
- return;
24
- if (typeof schema.preprocessors[key] === 'function') {
25
- const res = await Promise.resolve(schema.preprocessors[key](obj[key]));
26
- if (typeof res !== 'undefined') {
27
- obj[key] = res;
28
- }
29
- else {
30
- delete obj[key];
31
- }
32
- }
33
- else {
34
- const preprocessor = validator.preprocessors.get(schema.preprocessors[key]);
35
- if (typeof preprocessor !== 'function') {
36
- throw new Error(`preprocessor '${schema.preprocessors[key]}' is unknown`);
37
- }
38
- const res = await Promise.resolve(preprocessor(obj[key]));
39
- if (typeof res !== 'undefined') {
40
- obj[key] = res;
41
- }
42
- else {
43
- delete obj[key];
44
- }
45
- }
46
- }));
47
- if ('*' in schema.preprocessors) {
48
- const objectPreprocessor = schema.preprocessors['*'];
49
- if (typeof objectPreprocessor === 'function') {
50
- await Promise.resolve(objectPreprocessor(obj));
51
- }
52
- else {
53
- const preprocessor = validator.preprocessors.get(objectPreprocessor);
54
- if (typeof preprocessor !== 'function') {
55
- throw new Error(`preprocessor '${objectPreprocessor}' is unknown`);
56
- }
57
- await Promise.resolve(preprocessor(obj));
58
- }
59
- }
60
- }
61
- if (typeof schema.properties === 'object' && schema.properties) {
62
- const errors = [
63
- ...(await Promise.all(Object.entries(schema.properties).map(async ([name, schema]) => {
64
- const result = await validator.validate(schema, obj[name]);
65
- if (result.valid)
66
- return result;
67
- return {
68
- valid: false,
69
- errors: (result.errors || []).map((e) => `->${name} ${e}`)
70
- };
71
- }))),
72
- ...(schema.noUnknownProperties === false
73
- ? []
74
- : Object.keys(obj)
75
- .filter((k) => !(k in schema.properties))
76
- .map((k) => ({
77
- valid: false,
78
- errors: [`-> ${k} - unknown field`]
79
- })))
80
- ]
81
- .filter((r) => !r.valid)
82
- .map((r) => r.errors)
83
- .flat(Infinity);
84
- if (errors.length) {
85
- return {
86
- valid: false,
87
- errors
88
- };
89
- }
90
- }
91
- return {
92
- valid: true
93
- };
94
- };
95
- exports.validateObject = validateObject;
@@ -1,2 +0,0 @@
1
- import { StringSchema, ValidationResult } from '../schema.js';
2
- export declare const validateString: (obj: any, schema: StringSchema) => Promise<ValidationResult>;
@@ -1,50 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateString = void 0;
4
- const validateString = async (obj, schema) => {
5
- if (typeof obj === 'undefined' &&
6
- typeof schema === 'object' &&
7
- schema.isRequired === false) {
8
- return {
9
- valid: true
10
- };
11
- }
12
- if (typeof obj !== 'string')
13
- return {
14
- valid: false,
15
- errors: [`expected type string, but saw ${typeof obj}`]
16
- };
17
- if (typeof schema === 'string') {
18
- return obj === schema
19
- ? { valid: true }
20
- : {
21
- valid: false,
22
- errors: [`should be equal to ${schema}`]
23
- };
24
- }
25
- const str = obj;
26
- if (typeof schema.equals === 'string' && str !== schema.equals) {
27
- return {
28
- valid: false,
29
- errors: [
30
- `expected to be equal to '${schema.equals}' but saw '${str}'`
31
- ]
32
- };
33
- }
34
- if (typeof schema.minLength === 'number' && str.length < schema.minLength) {
35
- return {
36
- valid: false,
37
- errors: [`expected to be at least ${schema.minLength} chars long`]
38
- };
39
- }
40
- if (typeof schema.maxLength === 'number' && str.length > schema.maxLength) {
41
- return {
42
- valid: false,
43
- errors: [`expected to be at most ${schema.maxLength} chars long`]
44
- };
45
- }
46
- return {
47
- valid: true
48
- };
49
- };
50
- exports.validateString = validateString;
@@ -1,3 +0,0 @@
1
- import { UnionSchema, ValidationResult } from '../schema.js';
2
- import SchemaRegistry from '../schemaRegistry.js';
3
- export declare const validateUnion: (obj: any, schema: UnionSchema<any>, validator: SchemaRegistry<any>) => Promise<ValidationResult>;