@cleverbrush/schema 1.0.0-beta.4 → 1.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 (76) hide show
  1. package/README.md +118 -320
  2. package/dist/builders/AnySchemaBuilder.d.ts +76 -0
  3. package/dist/builders/AnySchemaBuilder.js +112 -0
  4. package/dist/builders/ArraySchemaBuilder.d.ts +112 -14
  5. package/dist/builders/ArraySchemaBuilder.js +254 -111
  6. package/dist/builders/BooleanSchemaBuilder.d.ts +69 -29
  7. package/dist/builders/BooleanSchemaBuilder.js +134 -74
  8. package/dist/builders/DateSchemaBuilder.d.ts +177 -0
  9. package/dist/builders/DateSchemaBuilder.js +433 -0
  10. package/dist/builders/FunctionSchemaBuilder.d.ts +59 -23
  11. package/dist/builders/FunctionSchemaBuilder.js +103 -56
  12. package/dist/builders/NumberSchemaBuilder.d.ts +159 -59
  13. package/dist/builders/NumberSchemaBuilder.js +345 -165
  14. package/dist/builders/ObjectSchemaBuilder.d.ts +357 -81
  15. package/dist/builders/ObjectSchemaBuilder.js +519 -283
  16. package/dist/builders/SchemaBuilder.d.ts +158 -34
  17. package/dist/builders/SchemaBuilder.js +258 -71
  18. package/dist/builders/StringSchemaBuilder.d.ts +138 -13
  19. package/dist/builders/StringSchemaBuilder.js +261 -115
  20. package/dist/builders/UnionSchemaBuilder.d.ts +129 -9
  21. package/dist/builders/UnionSchemaBuilder.js +196 -75
  22. package/dist/index.d.ts +20 -40
  23. package/dist/index.js +19 -32
  24. package/dist/utils/transaction.d.ts +46 -0
  25. package/dist/utils/transaction.js +178 -0
  26. package/package.json +27 -14
  27. package/dist/defaultSchemas.d.ts +0 -4
  28. package/dist/defaultSchemas.js +0 -45
  29. package/dist/schema.d.ts +0 -230
  30. package/dist/schema.js +0 -2
  31. package/dist/schemaRegistry.d.ts +0 -49
  32. package/dist/schemaRegistry.js +0 -278
  33. package/dist/validators/validateArray.d.ts +0 -3
  34. package/dist/validators/validateArray.js +0 -60
  35. package/dist/validators/validateBoolean.d.ts +0 -2
  36. package/dist/validators/validateBoolean.js +0 -30
  37. package/dist/validators/validateFunction.d.ts +0 -2
  38. package/dist/validators/validateFunction.js +0 -21
  39. package/dist/validators/validateNumber.d.ts +0 -2
  40. package/dist/validators/validateNumber.js +0 -69
  41. package/dist/validators/validateObject.d.ts +0 -3
  42. package/dist/validators/validateObject.js +0 -95
  43. package/dist/validators/validateString.d.ts +0 -2
  44. package/dist/validators/validateString.js +0 -50
  45. package/dist/validators/validateUnion.d.ts +0 -3
  46. package/dist/validators/validateUnion.js +0 -30
  47. package/src/builders/ArraySchemaBuilder.test.ts +0 -270
  48. package/src/builders/ArraySchemaBuilder.ts +0 -381
  49. package/src/builders/BooleanSchemaBuilder.test.ts +0 -196
  50. package/src/builders/BooleanSchemaBuilder.ts +0 -155
  51. package/src/builders/FunctionSchemaBuilder.test.ts +0 -134
  52. package/src/builders/FunctionSchemaBuilder.ts +0 -109
  53. package/src/builders/NumberSchemaBuilder.test.ts +0 -493
  54. package/src/builders/NumberSchemaBuilder.ts +0 -789
  55. package/src/builders/ObjectSchemaBuilder.test.ts +0 -657
  56. package/src/builders/ObjectSchemaBuilder.ts +0 -794
  57. package/src/builders/SchemaBuilder.test.ts +0 -73
  58. package/src/builders/SchemaBuilder.ts +0 -135
  59. package/src/builders/StringSchemaBuilder.test.ts +0 -318
  60. package/src/builders/StringSchemaBuilder.ts +0 -392
  61. package/src/builders/UnionSchemaBuilder.test.ts +0 -162
  62. package/src/builders/UnionSchemaBuilder.ts +0 -154
  63. package/src/defaultSchemas.ts +0 -44
  64. package/src/index.ts +0 -66
  65. package/src/schema.ts +0 -827
  66. package/src/schemaRegistry.builders.test.ts +0 -1393
  67. package/src/schemaRegistry.test.ts +0 -118
  68. package/src/schemaRegistry.ts +0 -461
  69. package/src/validators/validateArray.ts +0 -76
  70. package/src/validators/validateBoolean.ts +0 -36
  71. package/src/validators/validateFunction.ts +0 -25
  72. package/src/validators/validateNumber.ts +0 -82
  73. package/src/validators/validateObject.ts +0 -119
  74. package/src/validators/validateString.ts +0 -59
  75. package/src/validators/validateUnion.ts +0 -36
  76. package/tsconfig.json +0 -16
@@ -1,15 +1,113 @@
1
- import { ISchemaBuilder } from './SchemaBuilder.js';
2
- import { Schema } from '../schema.js';
3
- export interface IArraySchemaBuilder<TRequired extends boolean = true, TNullable extends boolean = false, TOfType extends Schema | undefined = undefined, TMaxLength extends number | undefined = undefined, TMinLength extends number | undefined = undefined> extends ISchemaBuilder<TRequired, TNullable> {
4
- optional(): IArraySchemaBuilder<false, TNullable, TOfType, TMaxLength, TMinLength>;
5
- required(): IArraySchemaBuilder<true, TNullable, TOfType, TMaxLength, TMinLength>;
6
- ofType<T extends Schema>(schema: T): IArraySchemaBuilder<TRequired, TNullable, T, TMaxLength, TMinLength>;
7
- nullable(): IArraySchemaBuilder<TRequired, true, TOfType, TMaxLength, TMinLength>;
8
- notNullable(): IArraySchemaBuilder<TRequired, false, TOfType, TMaxLength, TMinLength>;
9
- clearOfType(): IArraySchemaBuilder<TRequired, TNullable, undefined, TMaxLength, TMinLength>;
10
- maxLength<T extends number>(length: T): IArraySchemaBuilder<TRequired, TNullable, TOfType, T, TMinLength>;
11
- clearMaxLength(): IArraySchemaBuilder<TRequired, TNullable, TOfType, undefined, TMinLength>;
12
- minLength<T extends number>(length: T): IArraySchemaBuilder<TRequired, TNullable, TOfType, TMaxLength, T>;
13
- clearMinLength(): IArraySchemaBuilder<TRequired, TNullable, TOfType, TMaxLength, TMinLength>;
1
+ import { SchemaBuilder, ValidationResult, ValidationContext, InferType } from './SchemaBuilder.js';
2
+ type ArraySchemaBuilderCreateProps<TElementSchema extends SchemaBuilder<any, any>, R extends boolean = true> = Partial<ReturnType<ArraySchemaBuilder<TElementSchema, R>['introspect']>>;
3
+ /**
4
+ * Similar to the `Array` type in TypeScript. It can be used to validate arrays of any type.
5
+ * It can also be used to validate arrays of specific type.
6
+ * For example, if you want to validate an array of numbers,
7
+ * you can use `array(number())` to create a schema builder.
8
+ * If you want to validate an array of users, you can use
9
+ * `array().of(object({ name: string(), age: number() }))` to create a schema builder.
10
+ * If you want to validate an array of numbers or strings,
11
+ * you can use `array(union(number()).or(string()))`.
12
+ *
13
+ * Also you can limit the length of the array by using `minLength`
14
+ * and `maxLength` methods.
15
+ *
16
+ * **NOTE** this class is exported only to give opportunity to extend it
17
+ * by inheriting. It is not recommended to create an instance of this class
18
+ * directly. Use {@link array | array()} function instead.
19
+ * @see {@link array}
20
+ */
21
+ export declare class ArraySchemaBuilder<TElementSchema extends SchemaBuilder<any, any>, TRequired extends boolean = true, TExplicitType = undefined, TResult = TExplicitType extends undefined ? TElementSchema extends undefined ? Array<any> : TElementSchema extends SchemaBuilder<infer T1, infer T2> ? Array<InferType<SchemaBuilder<T1, T2>>> : never : TExplicitType> extends SchemaBuilder<TResult, TRequired> {
22
+ #private;
23
+ /**
24
+ * @hidden
25
+ */
26
+ static create(props: ArraySchemaBuilderCreateProps<any, any>): ArraySchemaBuilder<SchemaBuilder<any, any>, true, undefined, any[]>;
27
+ private constructor();
28
+ /**
29
+ * @hidden
30
+ */
31
+ hasType<T>(notUsed?: T): ArraySchemaBuilder<TElementSchema, true, T>;
32
+ /**
33
+ * @hidden
34
+ */
35
+ clearHasType(): ArraySchemaBuilder<TElementSchema, TRequired, undefined>;
36
+ /**
37
+ * Performs validion of the schema over `object`. Basically runs
38
+ * validators, preprocessors and checks for required (if schema is not optional).
39
+ * @param context Optional `ValidationContext` settings.
40
+ */
41
+ validate(object: TResult, context?: ValidationContext): Promise<ValidationResult<TResult>>;
42
+ /**
43
+ * @hidden
44
+ */
45
+ protected createFromProps<TReq extends boolean>(props: ArraySchemaBuilderCreateProps<TElementSchema, TReq>): this;
46
+ /**
47
+ * @hidden
48
+ */
49
+ required(): ArraySchemaBuilder<TElementSchema, true, TExplicitType>;
50
+ /**
51
+ * @hidden
52
+ */
53
+ optional(): ArraySchemaBuilder<TElementSchema, false, TExplicitType>;
54
+ introspect(): {
55
+ /**
56
+ * Schema of array item (if defined)
57
+ */
58
+ elementSchema: TElementSchema | undefined;
59
+ /**
60
+ * Min length of a valid array
61
+ */
62
+ minLength: number | undefined;
63
+ /**
64
+ * Max length of a valid array
65
+ */
66
+ maxLength: number | undefined;
67
+ type: string;
68
+ isRequired: boolean;
69
+ preprocessors: readonly import("./SchemaBuilder.js").Preprocessor<TResult>[];
70
+ validators: readonly import("./SchemaBuilder.js").Validator<TResult>[];
71
+ };
72
+ /**
73
+ * Set a schema that every array item has to satisfy. If it is not set,
74
+ * Item of any type is allowed.
75
+ * @param schema Schema that every array item has to satisfy
76
+ */
77
+ of<TSchema extends SchemaBuilder<any, any>>(schema: TSchema): ArraySchemaBuilder<TSchema, TRequired, TExplicitType>;
78
+ clearOf(): ArraySchemaBuilder<any, TRequired, TExplicitType>;
79
+ /**
80
+ * Set minimal length of the valid array value for schema.
81
+ */
82
+ minLength<T extends number>(length: T): ArraySchemaBuilder<TElementSchema, TRequired, TExplicitType>;
83
+ /**
84
+ * Clear minimal length of the valid array value for schema.
85
+ */
86
+ clearMinLength(): ArraySchemaBuilder<TElementSchema, TRequired, TExplicitType>;
87
+ /**
88
+ * Set max length of the valid array value for schema.
89
+ */
90
+ maxLength<T extends number>(length: T): ArraySchemaBuilder<TElementSchema, TRequired, TExplicitType>;
91
+ /**
92
+ * Clear max length of the valid array value for schema.
93
+ */
94
+ clearMaxLength(): ArraySchemaBuilder<TElementSchema, TRequired, TExplicitType>;
14
95
  }
15
- export declare const array: () => IArraySchemaBuilder<true, false, undefined, undefined, undefined>;
96
+ /**
97
+ * Creates a `Array` schema.
98
+ *
99
+ * @example
100
+ * ```typescript
101
+ * const schema = array().minLength(2).maxLength(5).of(string());
102
+ * // [] - invalid
103
+ * // ['a', 'b'] - valid
104
+ * // ['a', 'b', 'c', 'd', 'e', 'f'] - invalid
105
+ * // ['a', 'b', 'c', 'd', 'e'] - valid
106
+ * // ['a', 'b', 'c', 'd', 1] - invalid
107
+ * // ['a', 'b', null] - invalid
108
+ * // null - invalid
109
+ * // undefined - invalid
110
+ * ```
111
+ */
112
+ export declare const array: <TElementSchema extends SchemaBuilder<any, any>>(elementSchema?: TElementSchema | undefined) => ArraySchemaBuilder<TElementSchema, true, undefined, TElementSchema extends undefined ? any[] : TElementSchema extends SchemaBuilder<infer T1, infer T2 extends boolean> ? (T2 extends true ? T1 : T1 | undefined)[] : never>;
113
+ export {};
@@ -1,141 +1,284 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.array = void 0;
4
- const SchemaBuilder_js_1 = require("./SchemaBuilder.js");
5
- const defaultSchemas_js_1 = require("../defaultSchemas.js");
6
- class ArraySchemaBuilder extends SchemaBuilder_js_1.SchemaBuilder {
7
- clone() {
8
- return ArraySchemaBuilder.create(this._schema);
1
+ import { SchemaBuilder } from './SchemaBuilder.js';
2
+ /**
3
+ * Similar to the `Array` type in TypeScript. It can be used to validate arrays of any type.
4
+ * It can also be used to validate arrays of specific type.
5
+ * For example, if you want to validate an array of numbers,
6
+ * you can use `array(number())` to create a schema builder.
7
+ * If you want to validate an array of users, you can use
8
+ * `array().of(object({ name: string(), age: number() }))` to create a schema builder.
9
+ * If you want to validate an array of numbers or strings,
10
+ * you can use `array(union(number()).or(string()))`.
11
+ *
12
+ * Also you can limit the length of the array by using `minLength`
13
+ * and `maxLength` methods.
14
+ *
15
+ * **NOTE** this class is exported only to give opportunity to extend it
16
+ * by inheriting. It is not recommended to create an instance of this class
17
+ * directly. Use {@link array | array()} function instead.
18
+ * @see {@link array}
19
+ */
20
+ export class ArraySchemaBuilder extends SchemaBuilder {
21
+ #minLength;
22
+ #maxLength;
23
+ #elementSchema;
24
+ /**
25
+ * @hidden
26
+ */
27
+ static create(props) {
28
+ return new ArraySchemaBuilder({
29
+ type: 'array',
30
+ ...props
31
+ });
9
32
  }
10
- get _schema() {
11
- return Object.assign({
12
- type: this.type
13
- }, this.getCommonSchema(), typeof this._ofType !== 'undefined'
14
- ? {
15
- ofType: this._ofType
16
- }
17
- : {}, typeof this._minLength !== 'undefined'
18
- ? { minLength: this._minLength }
19
- : {}, typeof this._maxLength !== 'undefined'
20
- ? { maxLength: this._maxLength }
21
- : {});
33
+ constructor(props) {
34
+ super(props);
35
+ if (typeof props.minLength === 'number') {
36
+ this.#minLength = props.minLength;
37
+ }
38
+ if (typeof props.maxLength === 'number') {
39
+ this.#maxLength = props.maxLength;
40
+ }
41
+ if (props.elementSchema instanceof SchemaBuilder) {
42
+ this.#elementSchema = props.elementSchema;
43
+ }
44
+ }
45
+ /**
46
+ * @hidden
47
+ */
48
+ hasType(
49
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
50
+ notUsed) {
51
+ return this.createFromProps({
52
+ ...this.introspect()
53
+ });
22
54
  }
23
- static create(obj) {
24
- return new ArraySchemaBuilder(obj);
55
+ /**
56
+ * @hidden
57
+ */
58
+ clearHasType() {
59
+ return this.createFromProps({
60
+ ...this.introspect()
61
+ });
25
62
  }
26
- constructor(obj) {
27
- super(obj);
28
- if (typeof obj === 'object' && obj) {
29
- if (typeof obj.ofType !== 'undefined') {
30
- this._ofType =
31
- obj.ofType instanceof SchemaBuilder_js_1.SchemaBuilder
32
- ? obj.ofType.clone()
33
- : { ...obj.ofType };
34
- }
35
- if (typeof obj.maxLength !== 'undefined') {
36
- this._maxLength = obj.maxLength;
63
+ /**
64
+ * Performs validion of the schema over `object`. Basically runs
65
+ * validators, preprocessors and checks for required (if schema is not optional).
66
+ * @param context Optional `ValidationContext` settings.
67
+ */
68
+ async validate(object, context) {
69
+ const superResult = await super.preValidate(object, context);
70
+ const { valid, context: prevalidationContext, errors, transaction: preValidationTransaction } = superResult;
71
+ const { path } = prevalidationContext;
72
+ if (!valid) {
73
+ return {
74
+ valid,
75
+ errors
76
+ };
77
+ }
78
+ const { object: { validatedObject: objToValidate } } = preValidationTransaction;
79
+ if ((typeof objToValidate === 'undefined' || objToValidate === null) &&
80
+ this.isRequired === false) {
81
+ return {
82
+ valid: true,
83
+ object: objToValidate
84
+ };
85
+ }
86
+ if (!Array.isArray(objToValidate)) {
87
+ return {
88
+ valid: false,
89
+ errors: [{ message: 'array expected', path: path }]
90
+ };
91
+ }
92
+ if (typeof this.#maxLength === 'number' &&
93
+ objToValidate.length > this.#maxLength) {
94
+ return {
95
+ valid: false,
96
+ errors: [
97
+ {
98
+ message: `cannot contain more than ${this.#maxLength} elements`,
99
+ path: path
100
+ }
101
+ ]
102
+ };
103
+ }
104
+ if (typeof this.#minLength === 'number' &&
105
+ objToValidate.length < this.#minLength) {
106
+ return {
107
+ valid: false,
108
+ errors: [
109
+ {
110
+ message: `cannot contain less than ${this.#minLength} elements`,
111
+ path: path
112
+ }
113
+ ]
114
+ };
115
+ }
116
+ if (objToValidate.length > 0 &&
117
+ this.#elementSchema instanceof SchemaBuilder) {
118
+ if (prevalidationContext.doNotStopOnFirstError) {
119
+ const results = await Promise.all(objToValidate.map((o) => this.#elementSchema?.validate(o, prevalidationContext)));
120
+ let valid = true;
121
+ for (let i = 0; i < results.length; i++) {
122
+ if (!results[i]?.valid) {
123
+ valid = false;
124
+ }
125
+ }
126
+ return Object.assign({
127
+ valid
128
+ }, valid
129
+ ? {}
130
+ : {
131
+ errors: results
132
+ .map((r) => r?.errors)
133
+ .filter((r) => r)
134
+ .map((e) => e?.map((r, index) => ({
135
+ ...r,
136
+ path: `${r.path}[${index}]`
137
+ })))
138
+ .flat()
139
+ }, valid
140
+ ? {
141
+ object: results.map((r) => r?.object)
142
+ }
143
+ : {});
37
144
  }
38
- if (typeof obj.minLength !== 'undefined') {
39
- this._minLength = obj.minLength;
145
+ else {
146
+ for (let i = 0; i < objToValidate.length; i++) {
147
+ const { valid, errors, object: validatedItem } = await this.#elementSchema.validate(objToValidate[i], {
148
+ ...prevalidationContext,
149
+ path: `${path}[${i}]`
150
+ });
151
+ if (valid) {
152
+ objToValidate[i] = validatedItem;
153
+ }
154
+ else {
155
+ return {
156
+ valid: false,
157
+ errors: Array.isArray(errors) && errors.length > 0
158
+ ? [errors[0]]
159
+ : []
160
+ };
161
+ }
162
+ }
40
163
  }
41
164
  }
42
- else {
43
- const defaultSchema = defaultSchemas_js_1.defaultSchemas['array'];
44
- this.isRequired = defaultSchema.isRequired;
45
- this.isNullable = defaultSchema.isNullable;
46
- }
165
+ return {
166
+ valid: true,
167
+ object: objToValidate
168
+ };
47
169
  }
48
- type = 'array';
49
- _ofType;
50
- _maxLength;
51
- _minLength;
52
- optional() {
53
- if (this.isRequired === false) {
54
- return this;
55
- }
56
- return ArraySchemaBuilder.create({
57
- ...this._schema,
58
- isRequired: false
59
- });
170
+ /**
171
+ * @hidden
172
+ */
173
+ createFromProps(props) {
174
+ return ArraySchemaBuilder.create(props);
60
175
  }
176
+ /**
177
+ * @hidden
178
+ */
61
179
  required() {
62
- if (this.isRequired === true) {
63
- return this;
64
- }
65
- return ArraySchemaBuilder.create({
66
- ...this._schema,
67
- isRequired: true
68
- });
180
+ return super.required();
69
181
  }
70
- nullable() {
71
- if (this._isNullable === true) {
72
- return this;
73
- }
182
+ /**
183
+ * @hidden
184
+ */
185
+ optional() {
186
+ return super.optional();
187
+ }
188
+ introspect() {
189
+ return {
190
+ ...super.introspect(),
191
+ /**
192
+ * Schema of array item (if defined)
193
+ */
194
+ elementSchema: this.#elementSchema,
195
+ /**
196
+ * Min length of a valid array
197
+ */
198
+ minLength: this.#minLength,
199
+ /**
200
+ * Max length of a valid array
201
+ */
202
+ maxLength: this.#maxLength
203
+ };
204
+ }
205
+ /**
206
+ * Set a schema that every array item has to satisfy. If it is not set,
207
+ * Item of any type is allowed.
208
+ * @param schema Schema that every array item has to satisfy
209
+ */
210
+ of(schema) {
74
211
  return ArraySchemaBuilder.create({
75
- ...this._schema,
76
- isNullable: true
212
+ ...this.introspect(),
213
+ elementSchema: schema
77
214
  });
78
215
  }
79
- notNullable() {
80
- if (this.isNullable === false) {
81
- return this;
82
- }
216
+ clearOf() {
83
217
  return ArraySchemaBuilder.create({
84
- ...this._schema,
85
- isNullable: false
218
+ ...this.introspect(),
219
+ elementSchema: undefined
86
220
  });
87
221
  }
88
- ofType(schema) {
222
+ /**
223
+ * Set minimal length of the valid array value for schema.
224
+ */
225
+ minLength(length) {
226
+ if (typeof length !== 'number' || length < 0)
227
+ throw new Error('length is expected to be a number which is >= 0');
89
228
  return ArraySchemaBuilder.create({
90
- ...this._schema,
91
- ofType: schema
229
+ ...this.introspect(),
230
+ minLength: length
92
231
  });
93
232
  }
94
- clearOfType() {
95
- if (typeof this._ofType === 'undefined') {
96
- return this;
97
- }
98
- return ArraySchemaBuilder.create({
99
- ...this._schema,
100
- ofType: undefined
233
+ /**
234
+ * Clear minimal length of the valid array value for schema.
235
+ */
236
+ clearMinLength() {
237
+ const schema = this.introspect();
238
+ delete schema.minLength;
239
+ return this.createFromProps({
240
+ ...schema
101
241
  });
102
242
  }
243
+ /**
244
+ * Set max length of the valid array value for schema.
245
+ */
103
246
  maxLength(length) {
104
- if (this._maxLength === length) {
105
- return this;
106
- }
247
+ if (typeof length !== 'number' || length < 0)
248
+ throw new Error('length is expected to be a number which is >= 0');
107
249
  return ArraySchemaBuilder.create({
108
- ...this._schema,
250
+ ...this.introspect(),
109
251
  maxLength: length
110
252
  });
111
253
  }
254
+ /**
255
+ * Clear max length of the valid array value for schema.
256
+ */
112
257
  clearMaxLength() {
113
- if (typeof this._maxLength === 'undefined') {
114
- return this;
115
- }
116
- return ArraySchemaBuilder.create({
117
- ...this._schema,
118
- maxLength: undefined
119
- });
120
- }
121
- minLength(length) {
122
- if (this._minLength === length) {
123
- return this;
124
- }
125
- return ArraySchemaBuilder.create({
126
- ...this._schema,
127
- minLength: length
128
- });
129
- }
130
- clearMinLength() {
131
- if (typeof this._minLength === 'undefined') {
132
- return this;
133
- }
134
- return ArraySchemaBuilder.create({
135
- ...this._schema,
136
- minLength: undefined
258
+ const schema = this.introspect();
259
+ delete schema.maxLength;
260
+ return this.createFromProps({
261
+ ...schema
137
262
  });
138
263
  }
139
264
  }
140
- const array = () => ArraySchemaBuilder.create();
141
- exports.array = array;
265
+ /**
266
+ * Creates a `Array` schema.
267
+ *
268
+ * @example
269
+ * ```typescript
270
+ * const schema = array().minLength(2).maxLength(5).of(string());
271
+ * // [] - invalid
272
+ * // ['a', 'b'] - valid
273
+ * // ['a', 'b', 'c', 'd', 'e', 'f'] - invalid
274
+ * // ['a', 'b', 'c', 'd', 'e'] - valid
275
+ * // ['a', 'b', 'c', 'd', 1] - invalid
276
+ * // ['a', 'b', null] - invalid
277
+ * // null - invalid
278
+ * // undefined - invalid
279
+ * ```
280
+ */
281
+ export const array = (elementSchema) => ArraySchemaBuilder.create({
282
+ isRequired: true,
283
+ elementSchema
284
+ });
@@ -1,31 +1,71 @@
1
- import { Schema, Validator } from '../schema.js';
2
- import { ISchemaBuilder, SchemaBuilder } from './SchemaBuilder.js';
3
- export interface IBooleanSchemaBuilder<TRequired extends boolean = true, TNullable extends boolean = false, TEqualsTo extends boolean | undefined = undefined> extends ISchemaBuilder<TRequired, TNullable> {
4
- equals<T extends boolean>(val: T): IBooleanSchemaBuilder<TRequired, TNullable, T>;
5
- clearEqualsTo(): IBooleanSchemaBuilder<TRequired, TNullable, undefined>;
6
- optional(): IBooleanSchemaBuilder<false, TNullable, TEqualsTo>;
7
- required(): IBooleanSchemaBuilder<true, TNullable, TEqualsTo>;
8
- nullable(): IBooleanSchemaBuilder<TRequired, true, TEqualsTo>;
9
- notNullable(): IBooleanSchemaBuilder<TRequired, false, TEqualsTo>;
10
- }
11
- export declare class BooleanSchemaBuilder<TRequired extends boolean = true, TNullable extends boolean = false, TEqualsTo extends boolean | undefined = undefined> extends SchemaBuilder<TRequired, TNullable> implements IBooleanSchemaBuilder<TRequired, TNullable, TEqualsTo> {
12
- protected readonly type = "boolean";
13
- get _schema(): Schema;
14
- clone(): this;
15
- static create<TRequired extends boolean = true, TNullable extends boolean = false, TEqualsTo extends boolean | undefined = undefined>(obj?: {
16
- isRequired: TRequired;
17
- isNullable: TNullable;
18
- equals?: TEqualsTo;
19
- validators?: Validator[];
20
- preprocessor?: ((value: unknown) => unknown | Promise<unknown>) | string;
21
- }): IBooleanSchemaBuilder<TRequired, TNullable, TEqualsTo>;
1
+ import { SchemaBuilder, ValidationResult, ValidationContext } from './SchemaBuilder.js';
2
+ type BooleanSchemaBuilderCreateProps<R extends boolean = true> = Partial<ReturnType<BooleanSchemaBuilder<R>['introspect']>>;
3
+ /**
4
+ * Similar to `boolean` type in TypeScript.
5
+ * Allows to define a schema for a boolean value. It can be required or optional.
6
+ * It can be restricted to be equal to a certain value.
7
+ *
8
+ * **NOTE** this class is exported only to give opportunity to extend it
9
+ * by inheriting. It is not recommended to create an instance of this class
10
+ * directly. Use {@link boolean | boolean()} function instead.
11
+ *
12
+ * @example ```ts
13
+ * const schema = boolean().equals(true);
14
+ * const result = await schema.validate(true);
15
+ * // result.valid === true
16
+ * // result.object === true
17
+ * ```
18
+ * @example ```ts
19
+ * const schema = boolean().equals(false);
20
+ * const result = await schema.validate(true);
21
+ * // result.valid === false
22
+ * // result.errors[0].message === 'is expected to be equal to 'false''
23
+ * ```
24
+ * @example ```ts
25
+ * const schema = boolean().equals(true).optional();
26
+ * const result = await schema.validate(undefined);
27
+ * // result.valid === true
28
+ * // result.object === undefined
29
+ * ```
30
+ *
31
+ * @see {@link boolean}
32
+ */
33
+ export declare class BooleanSchemaBuilder<TResult = boolean, TRequired extends boolean = true, TExplicitType = undefined, TFinalResult = TExplicitType extends undefined ? TResult : TExplicitType> extends SchemaBuilder<TFinalResult, TRequired> {
34
+ #private;
35
+ static create(props: BooleanSchemaBuilderCreateProps<any>): BooleanSchemaBuilder<boolean, any, undefined, boolean>;
22
36
  private constructor();
23
- protected _equals?: TEqualsTo;
24
- equals<T extends boolean>(val: T): IBooleanSchemaBuilder<TRequired, TNullable, T>;
25
- clearEqualsTo(): IBooleanSchemaBuilder<TRequired, TNullable, undefined>;
26
- optional(): IBooleanSchemaBuilder<false, TNullable, TEqualsTo>;
27
- required(): IBooleanSchemaBuilder<true, TNullable, TEqualsTo>;
28
- nullable(): IBooleanSchemaBuilder<TRequired, true, TEqualsTo>;
29
- notNullable(): IBooleanSchemaBuilder<TRequired, false, TEqualsTo>;
37
+ introspect(): {
38
+ /**
39
+ * If set, restrict object to be equal to a certain value.
40
+ */
41
+ equalsTo: boolean | undefined;
42
+ type: string;
43
+ isRequired: boolean;
44
+ preprocessors: readonly import("./SchemaBuilder.js").Preprocessor<TFinalResult>[];
45
+ validators: readonly import("./SchemaBuilder.js").Validator<TFinalResult>[];
46
+ };
47
+ hasType<T>(notUsed?: T): BooleanSchemaBuilder<TResult, true, T>;
48
+ clearHasType(): BooleanSchemaBuilder<TResult, TRequired, undefined>;
49
+ /**
50
+ * Performs validion of the schema over `object`. Basically runs
51
+ * validators, preprocessors and checks for required (if schema is not optional).
52
+ * @param context Optional `ValidationContext` settings.
53
+ */
54
+ validate(object: TResult, context?: ValidationContext): Promise<ValidationResult<TResult>>;
55
+ protected createFromProps<TReq extends boolean>(props: BooleanSchemaBuilderCreateProps<TReq>): this;
56
+ required(): BooleanSchemaBuilder<TResult, true, TExplicitType>;
57
+ optional(): BooleanSchemaBuilder<TResult, false, TExplicitType>;
58
+ /**
59
+ * Restricts object to be equal to `value`.
60
+ */
61
+ equals<T extends boolean>(value: T): BooleanSchemaBuilder<T, TRequired, TExplicitType, TExplicitType extends undefined ? T : TExplicitType>;
62
+ /**
63
+ * Removes a `value` defeined by `equals()` call.
64
+ */
65
+ clearEquals(): BooleanSchemaBuilder<boolean, TRequired, TExplicitType>;
30
66
  }
31
- export declare const boolean: () => IBooleanSchemaBuilder;
67
+ /**
68
+ * Creates a `boolean` schema.
69
+ */
70
+ export declare const boolean: () => BooleanSchemaBuilder<boolean, true, undefined, boolean>;
71
+ export {};