@cleverbrush/schema 1.1.11 → 2.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 (87) hide show
  1. package/README.md +1314 -101
  2. package/dist/builders/AnySchemaBuilder.d.ts +54 -14
  3. package/dist/builders/AnySchemaBuilder.js +2 -112
  4. package/dist/builders/AnySchemaBuilder.js.map +1 -0
  5. package/dist/builders/ArraySchemaBuilder.d.ts +124 -23
  6. package/dist/builders/ArraySchemaBuilder.js +2 -284
  7. package/dist/builders/ArraySchemaBuilder.js.map +1 -0
  8. package/dist/builders/BooleanSchemaBuilder.d.ts +94 -19
  9. package/dist/builders/BooleanSchemaBuilder.js +2 -150
  10. package/dist/builders/BooleanSchemaBuilder.js.map +1 -0
  11. package/dist/builders/DateSchemaBuilder.d.ts +134 -34
  12. package/dist/builders/DateSchemaBuilder.js +2 -433
  13. package/dist/builders/DateSchemaBuilder.js.map +1 -0
  14. package/dist/builders/ExternSchemaBuilder.d.ts +200 -0
  15. package/dist/builders/ExternSchemaBuilder.js +2 -0
  16. package/dist/builders/ExternSchemaBuilder.js.map +1 -0
  17. package/dist/builders/FunctionSchemaBuilder.d.ts +57 -14
  18. package/dist/builders/FunctionSchemaBuilder.js +2 -113
  19. package/dist/builders/FunctionSchemaBuilder.js.map +1 -0
  20. package/dist/builders/LazySchemaBuilder.d.ts +167 -0
  21. package/dist/builders/NullSchemaBuilder.d.ts +162 -0
  22. package/dist/builders/NumberSchemaBuilder.d.ts +143 -31
  23. package/dist/builders/NumberSchemaBuilder.js +2 -386
  24. package/dist/builders/NumberSchemaBuilder.js.map +1 -0
  25. package/dist/builders/ObjectSchemaBuilder.d.ts +266 -61
  26. package/dist/builders/ObjectSchemaBuilder.js +2 -589
  27. package/dist/builders/ObjectSchemaBuilder.js.map +1 -0
  28. package/dist/builders/PropertyValidationResult.d.ts +68 -0
  29. package/dist/builders/RecordSchemaBuilder.d.ts +341 -0
  30. package/dist/builders/RecordSchemaBuilder.js +2 -0
  31. package/dist/builders/RecordSchemaBuilder.js.map +1 -0
  32. package/dist/builders/SchemaBuilder.d.ts +818 -30
  33. package/dist/builders/StringSchemaBuilder.d.ts +152 -37
  34. package/dist/builders/StringSchemaBuilder.js +2 -414
  35. package/dist/builders/StringSchemaBuilder.js.map +1 -0
  36. package/dist/builders/TupleSchemaBuilder.d.ts +248 -0
  37. package/dist/builders/TupleSchemaBuilder.js +2 -0
  38. package/dist/builders/TupleSchemaBuilder.js.map +1 -0
  39. package/dist/builders/UnionSchemaBuilder.d.ts +133 -39
  40. package/dist/builders/UnionSchemaBuilder.js +2 -216
  41. package/dist/builders/UnionSchemaBuilder.js.map +1 -0
  42. package/dist/chunk-BFCMDDTX.js +2 -0
  43. package/dist/chunk-BFCMDDTX.js.map +1 -0
  44. package/dist/chunk-CTP4RHDG.js +2 -0
  45. package/dist/chunk-CTP4RHDG.js.map +1 -0
  46. package/dist/chunk-EUQ5AE3H.js +2 -0
  47. package/dist/chunk-EUQ5AE3H.js.map +1 -0
  48. package/dist/chunk-FWUEUW2N.js +2 -0
  49. package/dist/chunk-FWUEUW2N.js.map +1 -0
  50. package/dist/chunk-IJ6FO37G.js +2 -0
  51. package/dist/chunk-IJ6FO37G.js.map +1 -0
  52. package/dist/chunk-KESLT5EE.js +2 -0
  53. package/dist/chunk-KESLT5EE.js.map +1 -0
  54. package/dist/chunk-KFTO7TMB.js +2 -0
  55. package/dist/chunk-KFTO7TMB.js.map +1 -0
  56. package/dist/chunk-MKAYFPAR.js +2 -0
  57. package/dist/chunk-MKAYFPAR.js.map +1 -0
  58. package/dist/chunk-NXPH3ZUW.js +2 -0
  59. package/dist/chunk-NXPH3ZUW.js.map +1 -0
  60. package/dist/chunk-S5TC6NSU.js +2 -0
  61. package/dist/chunk-S5TC6NSU.js.map +1 -0
  62. package/dist/chunk-YWBNVHR6.js +2 -0
  63. package/dist/chunk-YWBNVHR6.js.map +1 -0
  64. package/dist/chunk-Z7QZ7IXT.js +2 -0
  65. package/dist/chunk-Z7QZ7IXT.js.map +1 -0
  66. package/dist/chunk-ZAN4ZHCJ.js +2 -0
  67. package/dist/chunk-ZAN4ZHCJ.js.map +1 -0
  68. package/dist/chunk-ZUPYV5TI.js +2 -0
  69. package/dist/chunk-ZUPYV5TI.js.map +1 -0
  70. package/dist/core.d.ts +23 -0
  71. package/dist/core.js +2 -0
  72. package/dist/core.js.map +1 -0
  73. package/dist/extension.d.ts +413 -0
  74. package/dist/extensions/array.d.ts +112 -0
  75. package/dist/extensions/enum.d.ts +190 -0
  76. package/dist/extensions/index.d.ts +108 -0
  77. package/dist/extensions/nullable.d.ts +26 -0
  78. package/dist/extensions/number.d.ts +228 -0
  79. package/dist/extensions/string.d.ts +332 -0
  80. package/dist/extensions/util.d.ts +45 -0
  81. package/dist/index.d.ts +7 -20
  82. package/dist/index.js +2 -19
  83. package/dist/index.js.map +1 -0
  84. package/dist/utils/transaction.d.ts +27 -4
  85. package/package.json +74 -6
  86. package/dist/builders/SchemaBuilder.js +0 -275
  87. package/dist/utils/transaction.js +0 -178
@@ -1,284 +1,2 @@
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
- });
32
- }
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
- });
54
- }
55
- /**
56
- * @hidden
57
- */
58
- clearHasType() {
59
- return this.createFromProps({
60
- ...this.introspect()
61
- });
62
- }
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
- : {});
144
- }
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
- }
163
- }
164
- }
165
- return {
166
- valid: true,
167
- object: objToValidate
168
- };
169
- }
170
- /**
171
- * @hidden
172
- */
173
- createFromProps(props) {
174
- return ArraySchemaBuilder.create(props);
175
- }
176
- /**
177
- * @hidden
178
- */
179
- required() {
180
- return super.required();
181
- }
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) {
211
- return ArraySchemaBuilder.create({
212
- ...this.introspect(),
213
- elementSchema: schema
214
- });
215
- }
216
- clearOf() {
217
- return ArraySchemaBuilder.create({
218
- ...this.introspect(),
219
- elementSchema: undefined
220
- });
221
- }
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');
228
- return ArraySchemaBuilder.create({
229
- ...this.introspect(),
230
- minLength: length
231
- });
232
- }
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
241
- });
242
- }
243
- /**
244
- * Set max length of the valid array value for schema.
245
- */
246
- maxLength(length) {
247
- if (typeof length !== 'number' || length < 0)
248
- throw new Error('length is expected to be a number which is >= 0');
249
- return ArraySchemaBuilder.create({
250
- ...this.introspect(),
251
- maxLength: length
252
- });
253
- }
254
- /**
255
- * Clear max length of the valid array value for schema.
256
- */
257
- clearMaxLength() {
258
- const schema = this.introspect();
259
- delete schema.maxLength;
260
- return this.createFromProps({
261
- ...schema
262
- });
263
- }
264
- }
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
+ import{a,b}from"../chunk-Z7QZ7IXT.js";import"../chunk-CTP4RHDG.js";export{a as ArraySchemaBuilder,b as array};
2
+ //# sourceMappingURL=ArraySchemaBuilder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,4 +1,4 @@
1
- import { SchemaBuilder, ValidationResult, ValidationContext } from './SchemaBuilder.js';
1
+ import { type BRAND, SchemaBuilder, type ValidationContext, type ValidationErrorMessageProvider, type ValidationResult } from './SchemaBuilder.js';
2
2
  type BooleanSchemaBuilderCreateProps<R extends boolean = true> = Partial<ReturnType<BooleanSchemaBuilder<R>['introspect']>>;
3
3
  /**
4
4
  * Similar to `boolean` type in TypeScript.
@@ -11,58 +11,133 @@ type BooleanSchemaBuilderCreateProps<R extends boolean = true> = Partial<ReturnT
11
11
  *
12
12
  * @example ```ts
13
13
  * const schema = boolean().equals(true);
14
- * const result = await schema.validate(true);
14
+ * const result = schema.validate(true);
15
15
  * // result.valid === true
16
16
  * // result.object === true
17
17
  * ```
18
18
  * @example ```ts
19
19
  * const schema = boolean().equals(false);
20
- * const result = await schema.validate(true);
20
+ * const result = schema.validate(true);
21
21
  * // result.valid === false
22
22
  * // result.errors[0].message === 'is expected to be equal to 'false''
23
23
  * ```
24
24
  * @example ```ts
25
25
  * const schema = boolean().equals(true).optional();
26
- * const result = await schema.validate(undefined);
26
+ * const result = schema.validate(undefined);
27
27
  * // result.valid === true
28
28
  * // result.object === undefined
29
29
  * ```
30
30
  *
31
31
  * @see {@link boolean}
32
32
  */
33
- export declare class BooleanSchemaBuilder<TResult = boolean, TRequired extends boolean = true, TExplicitType = undefined, TFinalResult = TExplicitType extends undefined ? TResult : TExplicitType> extends SchemaBuilder<TFinalResult, TRequired> {
33
+ export declare class BooleanSchemaBuilder<TResult = boolean, TRequired extends boolean = true, TNullable extends boolean = false, TExplicitType = undefined, THasDefault extends boolean = false, TExtensions = {}, TFinalResult = TExplicitType extends undefined ? TResult : TExplicitType> extends SchemaBuilder<TFinalResult, TRequired, TNullable, THasDefault, TExtensions> {
34
34
  #private;
35
- static create(props: BooleanSchemaBuilderCreateProps<any>): BooleanSchemaBuilder<boolean, any, undefined, boolean>;
36
- private constructor();
35
+ /**
36
+ * @hidden
37
+ */
38
+ static create(props: BooleanSchemaBuilderCreateProps<any>): BooleanSchemaBuilder<boolean, any, false, undefined, false, {}, boolean>;
39
+ protected constructor(props: BooleanSchemaBuilderCreateProps<TRequired>);
37
40
  introspect(): {
38
41
  /**
39
42
  * If set, restrict object to be equal to a certain value.
40
43
  */
41
44
  equalsTo: boolean | undefined;
45
+ /**
46
+ * Equals to validation error message provider.
47
+ * If not provided, default error message will be used.
48
+ */
49
+ equalsToValidationErrorMessageProvider: ValidationErrorMessageProvider<BooleanSchemaBuilder<TResult, TRequired, false, undefined, false, {}, TResult>>;
42
50
  type: string;
43
51
  isRequired: boolean;
44
- preprocessors: readonly import("./SchemaBuilder.js").Preprocessor<TFinalResult>[];
45
- validators: readonly import("./SchemaBuilder.js").Validator<TFinalResult>[];
52
+ isNullable: boolean;
53
+ isReadonly: boolean;
54
+ preprocessors: readonly import("./SchemaBuilder.js").PreprocessorEntry<TFinalResult>[];
55
+ validators: readonly import("./SchemaBuilder.js").ValidatorEntry<TFinalResult>[];
56
+ requiredValidationErrorMessageProvider: ValidationErrorMessageProvider<SchemaBuilder<any, any, any, any, any>>;
57
+ extensions: {
58
+ [x: string]: unknown;
59
+ };
60
+ hasDefault: boolean;
61
+ defaultValue: TFinalResult | (() => TFinalResult) | undefined;
62
+ description: string | undefined;
63
+ hasCatch: boolean;
64
+ catchValue: TFinalResult | (() => TFinalResult) | undefined;
46
65
  };
47
- hasType<T>(notUsed?: T): BooleanSchemaBuilder<TResult, true, T>;
48
- clearHasType(): BooleanSchemaBuilder<TResult, TRequired, undefined>;
49
66
  /**
50
- * Performs validion of the schema over `object`. Basically runs
51
- * validators, preprocessors and checks for required (if schema is not optional).
67
+ * @inheritdoc
68
+ */
69
+ hasType<T>(_notUsed?: T): BooleanSchemaBuilder<TResult, true, TNullable, T, THasDefault, TExtensions> & TExtensions;
70
+ /**
71
+ * @inheritdoc
72
+ */
73
+ clearHasType(): BooleanSchemaBuilder<TResult, TRequired, TNullable, undefined, THasDefault, TExtensions> & TExtensions;
74
+ /** {@inheritDoc SchemaBuilder.validate} */
75
+ validate(object: TResult, context?: ValidationContext): ValidationResult<TResult>;
76
+ /** {@inheritDoc SchemaBuilder.validateAsync} */
77
+ validateAsync(object: TResult, context?: ValidationContext): Promise<ValidationResult<TResult>>;
78
+ /**
79
+ * Performs synchronous validation of the schema over `object`.
80
+ * Throws if any preprocessor, validator, or error message provider returns a Promise.
52
81
  * @param context Optional `ValidationContext` settings.
53
82
  */
54
- validate(object: TResult, context?: ValidationContext): Promise<ValidationResult<TResult>>;
83
+ protected _validate(object: TResult, context?: ValidationContext): ValidationResult<TResult>;
84
+ /**
85
+ * Performs async validation of the schema over `object`.
86
+ * Supports async preprocessors, validators, and error message providers.
87
+ * @param context Optional `ValidationContext` settings.
88
+ */
89
+ protected _validateAsync(object: TResult, context?: ValidationContext): Promise<ValidationResult<TResult>>;
55
90
  protected createFromProps<TReq extends boolean>(props: BooleanSchemaBuilderCreateProps<TReq>): this;
56
- required(): BooleanSchemaBuilder<TResult, true, TExplicitType>;
57
- optional(): BooleanSchemaBuilder<TResult, false, TExplicitType>;
91
+ /**
92
+ * @hidden
93
+ */
94
+ required(errorMessage?: ValidationErrorMessageProvider): BooleanSchemaBuilder<TResult, true, TNullable, TExplicitType, THasDefault, TExtensions> & TExtensions;
95
+ /**
96
+ * @hidden
97
+ */
98
+ optional(): BooleanSchemaBuilder<TResult, false, TNullable, TExplicitType, THasDefault, TExtensions> & TExtensions;
99
+ /**
100
+ * @hidden
101
+ */
102
+ default(value: TFinalResult | (() => TFinalResult)): BooleanSchemaBuilder<TResult, true, TNullable, TExplicitType, true, TExtensions> & TExtensions;
103
+ /**
104
+ * @hidden
105
+ */
106
+ clearDefault(): BooleanSchemaBuilder<TResult, TRequired, TNullable, TExplicitType, false, TExtensions> & TExtensions;
107
+ /**
108
+ * @hidden
109
+ */
110
+ brand<TBrand extends string | symbol>(_name?: TBrand): BooleanSchemaBuilder<TResult, TRequired, TNullable, TFinalResult & {
111
+ readonly [K in BRAND]: TBrand;
112
+ }, THasDefault, TExtensions> & TExtensions;
113
+ /**
114
+ * Marks the inferred type as `Readonly<boolean>`. Since booleans are
115
+ * already immutable this is an identity operation, but it sets the
116
+ * `isReadonly` introspection flag for tooling consistency.
117
+ *
118
+ * @see {@link SchemaBuilder.readonly}
119
+ */
120
+ readonly(): BooleanSchemaBuilder<TResult, TRequired, TNullable, Readonly<TFinalResult>, THasDefault, TExtensions> & TExtensions;
58
121
  /**
59
122
  * Restricts object to be equal to `value`.
60
123
  */
61
- equals<T extends boolean>(value: T): BooleanSchemaBuilder<T, TRequired, TExplicitType>;
124
+ equals<T extends boolean>(value: T,
125
+ /**
126
+ * Custom error message provider.
127
+ */
128
+ errorMessage?: ValidationErrorMessageProvider<BooleanSchemaBuilder<TResult, TRequired>>): BooleanSchemaBuilder<T, TRequired, TNullable, TExplicitType, THasDefault, TExtensions> & TExtensions;
129
+ /**
130
+ * Removes a `value` defined by `equals()` call.
131
+ */
132
+ clearEquals(): BooleanSchemaBuilder<boolean, TRequired, TNullable, TExplicitType, THasDefault, TExtensions> & TExtensions;
133
+ /**
134
+ * @hidden
135
+ */
136
+ nullable(): BooleanSchemaBuilder<TResult, TRequired, true, TExplicitType, THasDefault, TExtensions> & TExtensions;
62
137
  /**
63
- * Removes a `value` defeined by `equals()` call.
138
+ * @hidden
64
139
  */
65
- clearEquals(): BooleanSchemaBuilder<boolean, TRequired, TExplicitType>;
140
+ notNullable(): BooleanSchemaBuilder<TResult, TRequired, false, TExplicitType, THasDefault, TExtensions> & TExtensions;
66
141
  }
67
142
  /**
68
143
  * Creates a `boolean` schema.
@@ -1,150 +1,2 @@
1
- import { SchemaBuilder } from './SchemaBuilder.js';
2
- /**
3
- * Similar to `boolean` type in TypeScript.
4
- * Allows to define a schema for a boolean value. It can be required or optional.
5
- * It can be restricted to be equal to a certain value.
6
- *
7
- * **NOTE** this class is exported only to give opportunity to extend it
8
- * by inheriting. It is not recommended to create an instance of this class
9
- * directly. Use {@link boolean | boolean()} function instead.
10
- *
11
- * @example ```ts
12
- * const schema = boolean().equals(true);
13
- * const result = await schema.validate(true);
14
- * // result.valid === true
15
- * // result.object === true
16
- * ```
17
- * @example ```ts
18
- * const schema = boolean().equals(false);
19
- * const result = await schema.validate(true);
20
- * // result.valid === false
21
- * // result.errors[0].message === 'is expected to be equal to 'false''
22
- * ```
23
- * @example ```ts
24
- * const schema = boolean().equals(true).optional();
25
- * const result = await schema.validate(undefined);
26
- * // result.valid === true
27
- * // result.object === undefined
28
- * ```
29
- *
30
- * @see {@link boolean}
31
- */
32
- export class BooleanSchemaBuilder extends SchemaBuilder {
33
- #equalsTo;
34
- static create(props) {
35
- return new BooleanSchemaBuilder({
36
- type: 'boolean',
37
- ...props
38
- });
39
- }
40
- constructor(props) {
41
- super(props);
42
- if (typeof props.equalsTo === 'boolean' ||
43
- typeof props.equalsTo === 'undefined') {
44
- this.#equalsTo = props.equalsTo;
45
- }
46
- }
47
- introspect() {
48
- return {
49
- ...super.introspect(),
50
- /**
51
- * If set, restrict object to be equal to a certain value.
52
- */
53
- equalsTo: this.#equalsTo
54
- };
55
- }
56
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
57
- hasType(notUsed) {
58
- return this.createFromProps({
59
- ...this.introspect()
60
- });
61
- }
62
- clearHasType() {
63
- return this.createFromProps({
64
- ...this.introspect()
65
- });
66
- }
67
- /**
68
- * Performs validion of the schema over `object`. Basically runs
69
- * validators, preprocessors and checks for required (if schema is not optional).
70
- * @param context Optional `ValidationContext` settings.
71
- */
72
- async validate(object, context) {
73
- const superResult = await super.preValidate(object, context);
74
- const { valid, context: prevalidationContext, transaction: preValidationTransaction, errors } = superResult;
75
- const { path } = prevalidationContext;
76
- if (!valid) {
77
- return { valid, errors };
78
- }
79
- const { object: { validatedObject: objToValidate } } = preValidationTransaction;
80
- if ((typeof objToValidate === 'undefined' || objToValidate === null) &&
81
- this.isRequired === false) {
82
- return {
83
- valid: true,
84
- object: objToValidate
85
- };
86
- }
87
- if (typeof objToValidate !== 'boolean') {
88
- return {
89
- valid: false,
90
- errors: [
91
- {
92
- message: 'expected to be boolean',
93
- path: path
94
- }
95
- ]
96
- };
97
- }
98
- if (typeof this.#equalsTo !== 'undefined' &&
99
- objToValidate !== this.#equalsTo) {
100
- return {
101
- valid: false,
102
- errors: [
103
- {
104
- message: `is expected to be equal to '${this.#equalsTo}'`,
105
- path: path
106
- }
107
- ]
108
- };
109
- }
110
- return {
111
- valid: true,
112
- object: objToValidate
113
- };
114
- }
115
- createFromProps(props) {
116
- return BooleanSchemaBuilder.create(props);
117
- }
118
- required() {
119
- return super.required();
120
- }
121
- optional() {
122
- return super.optional();
123
- }
124
- /**
125
- * Restricts object to be equal to `value`.
126
- */
127
- equals(value) {
128
- if (typeof value !== 'boolean')
129
- throw new Error('boolean expected');
130
- return this.createFromProps({
131
- ...this.introspect(),
132
- equalsTo: value
133
- });
134
- }
135
- /**
136
- * Removes a `value` defeined by `equals()` call.
137
- */
138
- clearEquals() {
139
- return this.createFromProps({
140
- ...this.introspect(),
141
- equalsTo: undefined
142
- });
143
- }
144
- }
145
- /**
146
- * Creates a `boolean` schema.
147
- */
148
- export const boolean = () => BooleanSchemaBuilder.create({
149
- isRequired: true
150
- });
1
+ import{a,b}from"../chunk-KFTO7TMB.js";import"../chunk-CTP4RHDG.js";export{a as BooleanSchemaBuilder,b as boolean};
2
+ //# sourceMappingURL=BooleanSchemaBuilder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}