validator-fns 2.0.5 → 3.0.0-next.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.
package/dist/index.d.ts CHANGED
@@ -1,51 +1,52 @@
1
+ //#region src/shared.d.ts
1
2
  type ValidResult<T> = {
2
- /**
3
- * True if the original value is valid according to all validation tests
4
- * @deprecated Use `state` instead.
5
- */
6
- isValid: true;
7
- /** This is preferred to use over `isValid` as it works better for type guards. */
8
- state: 'valid';
9
- /** The parsed value. Note that may be different than the original value. */
10
- value: T | null | undefined;
11
- /** Field name if provided. Automatically provided if using object validation. */
12
- field?: string | undefined;
3
+ /**
4
+ * True if the original value is valid according to all validation tests
5
+ * @deprecated Use `state` instead.
6
+ */
7
+ isValid: true;
8
+ /** This is preferred to use over `isValid` as it works better for type guards. */
9
+ state: 'valid';
10
+ /** The parsed value. Note that may be different than the original value. */
11
+ value: T | null | undefined;
12
+ /** Field name if provided. Automatically provided if using object validation. */
13
+ field?: string | undefined;
13
14
  };
14
15
  type InvalidResult<E> = {
15
- /**
16
- * True if the original value is valid according to all validation tests.
17
- * @deprecated Use `state` instead.
18
- */
19
- isValid: false;
20
- /** This is preferred to use over `isValid` as it works better for type guards. */
21
- state: 'invalid';
22
- /** The parsed value. Note that may be different than the original value. */
23
- value: unknown;
24
- /** Error message if `state` is invalid. */
25
- message: string;
26
- /** Field name if provided. Automatically provided if using object validation. */
27
- field?: string | undefined;
28
- /** Extra error details */
29
- errors?: E | undefined;
16
+ /**
17
+ * True if the original value is valid according to all validation tests.
18
+ * @deprecated Use `state` instead.
19
+ */
20
+ isValid: false;
21
+ /** This is preferred to use over `isValid` as it works better for type guards. */
22
+ state: 'invalid';
23
+ /** The parsed value. Note that may be different than the original value. */
24
+ value: unknown;
25
+ /** Error message if `state` is invalid. */
26
+ message: string;
27
+ /** Field name if provided. Automatically provided if using object validation. */
28
+ field?: string | undefined;
29
+ /** Extra error details */
30
+ errors?: E | undefined;
30
31
  };
31
32
  /**
32
33
  * The result of a validation.
33
34
  * @typeParam T The value type
34
35
  * @category Types
35
36
  */
36
- type ValidatorResult<T = any, E = any> = ValidResult<T> | InvalidResult<E>;
37
+ type ValidatorResult<T = unknown, E = unknown> = ValidResult<T> | InvalidResult<E>;
37
38
  /**
38
39
  * Validation test function.
39
40
  * @typeParam T The value type
40
41
  * @category Types
41
42
  */
42
- type ValidatorTest<T = any, E = any> = (value?: unknown, field?: string) => Promise<ValidatorResult<T, E>>;
43
+ type ValidatorTest<T = unknown, E = unknown> = (value?: unknown, field?: string) => Promise<ValidatorResult<T, E>>;
43
44
  /**
44
45
  * Extracts the generic error type from a ValidatorTest.
45
46
  * @typeParam T a ValidatorTest
46
47
  * @category Types
47
48
  */
48
- type ExtractError<T extends ValidatorTest> = T extends ValidatorTest<any, infer E> ? E : unknown;
49
+ type ExtractError<T extends ValidatorTest> = T extends ValidatorTest<unknown, infer E> ? E : unknown;
49
50
  /**
50
51
  * Extracts the generic value type from a ValidatorTest.
51
52
  * @typeParam T a ValidatorTest
@@ -57,29 +58,27 @@ type ExtractValue<T extends ValidatorTest> = T extends ValidatorTest<infer V> ?
57
58
  * @typeParam T any object type
58
59
  * @category Types
59
60
  */
60
- type DeepPartial<T> = {
61
- [P in keyof T]?: DeepPartial<T[P]>;
62
- };
61
+ type DeepPartial<T> = { [P in keyof T]?: DeepPartial<T[P]>; };
63
62
  /**
64
63
  * Validation factory function.
65
64
  * @typeParam C The configuration type
66
65
  * @category Types
67
66
  */
68
- type ValidatorFactory<C, T, E> = (config?: Partial<C> | ValidatorTest, ...tests: ValidatorTest[]) => ValidatorTest<T, E>;
67
+ type ValidatorFactory<C, T, E> = (config?: Partial<C> | ValidatorTest<unknown, E>, ...tests: ValidatorTest<unknown, E>[]) => ValidatorTest<T, E>;
69
68
  /**
70
69
  * Base configuration type.
71
70
  * @typeParam T The target type.
72
71
  * @category Types
73
72
  */
74
73
  interface ConfigBase<T> {
75
- /** Parser to convert value into the designated type. */
76
- parser: (value: unknown) => T | null | undefined;
77
- /** Provide a fallback value in case the original value is undefined. */
78
- default?: T;
74
+ /** Parser to convert value into the designated type. */
75
+ parser: (value: unknown) => T | null | undefined;
76
+ /** Provide a fallback value in case the original value is undefined. */
77
+ default?: T;
79
78
  }
80
79
  interface ValidatorMessageParameters<T> {
81
- value: T | null | undefined;
82
- field: string | undefined;
80
+ value: T | null | undefined;
81
+ field: string | undefined;
83
82
  }
84
83
  /**
85
84
  * Validation message. May be a plain string or a function that accepts arguments.
@@ -91,20 +90,20 @@ type ValidatorMessage<T, P extends ValidatorMessageParameters<T> = ValidatorMess
91
90
  * Simple check for objects.
92
91
  * @param value Value to test
93
92
  */
94
- declare function isObject(value: unknown): boolean;
93
+ export declare function isObject(value: unknown): boolean;
95
94
  /**
96
95
  * Safe hasOwnProperty check
97
96
  * @param object Object to check
98
97
  * @param property Property to look for
99
98
  */
100
- declare function hasOwnProperty(object: unknown, property: string | number | symbol): boolean;
99
+ export declare function hasOwnProperty(object: unknown, property: string | number | symbol): boolean;
101
100
  /**
102
101
  * Formats a message using a squiggly bracket `{}` template.
103
102
  * @param template Message template as string or function
104
103
  * @param parameters Params to inject into template
105
104
  * @category Helpers
106
105
  */
107
- declare function formatMessage<T, P extends ValidatorMessageParameters<T>>(template: ValidatorMessage<T, P>, parameters: P): string;
106
+ export declare function formatMessage<T, P extends ValidatorMessageParameters<T>>(template: ValidatorMessage<T, P>, parameters: P): string;
108
107
  /**
109
108
  * Creates a valid result
110
109
  * @param result Result fields
@@ -112,9 +111,9 @@ declare function formatMessage<T, P extends ValidatorMessageParameters<T>>(templ
112
111
  * @param result.field Field name
113
112
  * @category Helpers
114
113
  */
115
- declare function valid<T, E = never>({ value, field, }: {
116
- value: T | null | undefined;
117
- field: string | undefined;
114
+ export declare function valid<T, E = never>({ value, field }: {
115
+ value: T | null | undefined;
116
+ field: string | undefined;
118
117
  }): Promise<ValidatorResult<T, E>>;
119
118
  /**
120
119
  * Creates an invalid result.
@@ -126,88 +125,15 @@ declare function valid<T, E = never>({ value, field, }: {
126
125
  * @param result.extras Extra message params
127
126
  * @category Helpers
128
127
  */
129
- declare function invalid<T, E, P extends ValidatorMessageParameters<T> = ValidatorMessageParameters<T>>({ errors, field, message, value, extras, }: {
130
- message: ValidatorMessage<T, P>;
131
- value: unknown;
132
- field: string | undefined;
133
- errors?: E | undefined;
134
- extras?: Omit<P, 'field' | 'value'> | undefined;
128
+ export declare function invalid<T, E = never, P extends ValidatorMessageParameters<T> = ValidatorMessageParameters<T>>({ errors, field, message, value, extras }: {
129
+ message: ValidatorMessage<T, P>;
130
+ value: unknown;
131
+ field: string | undefined;
132
+ errors?: E | undefined;
133
+ extras?: Omit<P, 'field' | 'value'> | undefined;
135
134
  }): Promise<ValidatorResult<T, E>>;
136
- /**
137
- * Creates a type validator.
138
- * @typeParam T The basic type for the final value to be validated.
139
- * @typeParam C The configuration type.
140
- * @param defaultParser Parser to convert value into type.
141
- * @param applyConfig Function that applies configuration to value.
142
- * @category Helpers
143
- */
144
- declare function createTypeValidatorTest<T, C extends ConfigBase<T>>(defaultConfig: C, applyConfig: (value: unknown, config: C) => T | null | undefined): ValidatorFactory<C, T, string>;
145
- /**
146
- * Captures basic validator test pattern
147
- * @param test Test function
148
- * @param message Error message
149
- * @param getExtras Optional extra fields for error message
150
- */
151
- declare function createValidatorTest<T = any, E = any, P extends ValidatorMessageParameters<T> = ValidatorMessageParameters<T>>(test: (value: unknown, field?: string) => boolean, message: ValidatorMessage<T, P>, getExtras?: (value: T | null | undefined) => Omit<P, 'value' | 'field'>): ValidatorTest<T, E>;
152
- /**
153
- * Ensures a value is not undefined, null, empty string, NaN, nor invalid date.
154
- * @param message Error message
155
- * @param nullable Allow null values
156
- * @category Validation Tests
157
- */
158
- declare function required<T, P extends ValidatorMessageParameters<T>>(message: ValidatorMessage<T, P>, nullable?: boolean): ValidatorTest<T>;
159
- type SharedValueType = string | number | unknown[];
160
- interface MaxValidatorMessageParameters extends ValidatorMessageParameters<SharedValueType> {
161
- max: number;
162
- amount: number | null | undefined;
163
- limit: number;
164
- exclusive?: boolean | undefined;
165
- }
166
- /**
167
- * Ensures a string, number, or array value is at most a certain amount.
168
- * @param limit Size or value limit
169
- * @param message Error message
170
- * @param exclusive Use exclusive comparison instead of inclusive
171
- * @category Validation Tests
172
- */
173
- declare function max(limit: number, message: ValidatorMessage<SharedValueType, MaxValidatorMessageParameters>, exclusive?: boolean): ValidatorTest<SharedValueType>;
174
- interface MinValidatorMessageParameters extends ValidatorMessageParameters<SharedValueType> {
175
- min: number;
176
- limit: number;
177
- amount: number | null | undefined;
178
- exclusive?: boolean | undefined;
179
- }
180
- /**
181
- * Ensures a string, number, or array value is at most a certain amount.
182
- * @param limit Size or value limit
183
- * @param message Error message
184
- * @param exclusive Use exclusive comparison instead of inclusive
185
- * @category Validation Tests
186
- */
187
- declare function min(limit: number, message: ValidatorMessage<SharedValueType, MinValidatorMessageParameters>, exclusive?: boolean): ValidatorTest<SharedValueType>;
188
- interface ExactValidatorMessageParameters extends ValidatorMessageParameters<SharedValueType> {
189
- limit: number;
190
- amount: number | null | undefined;
191
- exact: number;
192
- }
193
- /**
194
- * Ensures a string, number, or array value is exactly a certain amount.
195
- * @param limit Size or value limit
196
- * @param message Error message
197
- * @category Validation Tests
198
- */
199
- declare function exact(limit: number, message: ValidatorMessage<SharedValueType, ExactValidatorMessageParameters>): ValidatorTest<SharedValueType>;
200
- interface OneOfValidatorMessageParameters<T> extends ValidatorMessageParameters<T> {
201
- values: readonly T[];
202
- }
203
- /**
204
- * Ensures a value is one in a predefined list.
205
- * @param values List of allowed values.
206
- * @param message Error message
207
- * @category Validation Tests
208
- */
209
- declare function oneOf<T extends string | number | boolean | Date>(values: readonly T[], message: ValidatorMessage<T, OneOfValidatorMessageParameters<T>>): ValidatorTest<T>;
210
-
135
+ //#endregion
136
+ //#region src/arrays.d.ts
211
137
  /**
212
138
  * Invalid validation result for an item in the array
213
139
  * @category Types
@@ -223,34 +149,35 @@ type ArrayConfig = ConfigBase<unknown[]>;
223
149
  * @param value Value to parse
224
150
  * @category Parsers
225
151
  */
226
- declare function parseArray(value: unknown): unknown[] | null | undefined;
152
+ export declare function parseArray(value: unknown): unknown[] | null | undefined;
227
153
  /**
228
154
  * Applies a configuration to the array value.
229
155
  * @param value Value to modify
230
156
  * @param config Configuration to apply
231
157
  * @category Helpers
232
158
  */
233
- declare function applyArrayConfig<T>(config: ArrayConfig, value: unknown): T[] | null | undefined;
159
+ export declare function applyArrayConfig<T>(config: ArrayConfig, value: unknown): T[] | null | undefined;
234
160
  /**
235
161
  * Validates an array. The first passed validator is used to validate individual
236
162
  * items. The remaining validators target the array itself.
237
163
  * @category Type Validators
238
164
  */
239
- declare function array<T, E>(config?: Partial<ArrayConfig> | ValidatorTest<T, E>, ...tests: ValidatorTest[]): ValidatorTest<T[], string | ArrayItemValidatorResult<E>[]>;
240
-
165
+ export declare function array<T, E>(config?: Partial<ArrayConfig> | ValidatorTest<T, E>, ...tests: ValidatorTest[]): ValidatorTest<T[], string | ArrayItemValidatorResult<E>[]>;
166
+ //#endregion
167
+ //#region src/booleans.d.ts
241
168
  /**
242
169
  * Parses a value into a boolean.
243
170
  * @param value Value to parse
244
171
  * @category Parsers
245
172
  */
246
- declare function parseBoolean(value: unknown): boolean | null | undefined;
173
+ export declare function parseBoolean(value: unknown): boolean | null | undefined;
247
174
  /**
248
175
  * Applies a configuration to the boolean value.
249
176
  * @param value Value to modify
250
177
  * @param config Configuration to apply
251
178
  * @category Helpers
252
179
  */
253
- declare function applyBooleanConfig(value: unknown, config: BooleanConfig): boolean | null | undefined;
180
+ export declare function applyBooleanConfig(value: unknown, config: BooleanConfig): boolean | null | undefined;
254
181
  /**
255
182
  * Configuration for boolean validation.
256
183
  * @category Types
@@ -260,28 +187,21 @@ type BooleanConfig = ConfigBase<boolean>;
260
187
  * Validates a boolean value.
261
188
  * @category Type Validators
262
189
  */
263
- declare const boolean: ValidatorFactory<BooleanConfig, boolean, string>;
264
-
265
- /** Badly formatted date for internal use. */
266
- declare const invalidDate: Date;
267
- /**
268
- * Parses a value into a date.
269
- * @param value Value to parse
270
- * @category Parsers
271
- */
272
- declare function parseDate(value: unknown): Date | null | undefined;
190
+ export declare const boolean: ValidatorFactory<BooleanConfig, boolean, string>;
191
+ //#endregion
192
+ //#region src/dates.d.ts
273
193
  /**
274
194
  * Applies a configuration to the date value.
275
195
  * @param value Value to modify
276
196
  * @param config Configuration to apply
277
197
  * @category Helpers
278
198
  */
279
- declare function applyDateConfig(value: unknown, config: DateConfig): Date | null | undefined;
199
+ export declare function applyDateConfig(value: unknown, config: DateConfig): Date | null | undefined;
280
200
  type SharedDateValueType = Date | string | number;
281
201
  interface MinDateValidatorMessageParameters extends ValidatorMessageParameters<Date> {
282
- min: Date | null | undefined;
283
- limit: Date | null | undefined;
284
- exclusive?: boolean | undefined;
202
+ min: Date | null | undefined;
203
+ limit: Date | null | undefined;
204
+ exclusive?: boolean | undefined;
285
205
  }
286
206
  /**
287
207
  * Ensures a date value is on or after a date.
@@ -290,11 +210,11 @@ interface MinDateValidatorMessageParameters extends ValidatorMessageParameters<D
290
210
  * @param exclusive Makes comparison exclusive instead of inclusive
291
211
  * @category Validation Tests
292
212
  */
293
- declare function minDate(limit: SharedDateValueType, message: ValidatorMessage<Date, MinDateValidatorMessageParameters>, exclusive?: boolean): ValidatorTest<Date, null>;
213
+ export declare function minDate(limit: SharedDateValueType, message: ValidatorMessage<Date, MinDateValidatorMessageParameters>, exclusive?: boolean): ValidatorTest<Date, never>;
294
214
  interface MaxDateValidatorMessageParameters extends ValidatorMessageParameters<Date> {
295
- max: Date | null | undefined;
296
- limit: Date | null | undefined;
297
- exclusive?: boolean | undefined;
215
+ max: Date | null | undefined;
216
+ limit: Date | null | undefined;
217
+ exclusive?: boolean | undefined;
298
218
  }
299
219
  /**
300
220
  * Ensures a date value is on or before a date.
@@ -303,7 +223,7 @@ interface MaxDateValidatorMessageParameters extends ValidatorMessageParameters<D
303
223
  * @param exclusive Makes comparison exclusive instead of inclusive
304
224
  * @category Validation Tests
305
225
  */
306
- declare function maxDate(limit: SharedDateValueType, message: ValidatorMessage<Date, MaxDateValidatorMessageParameters>, exclusive?: boolean): ValidatorTest<Date>;
226
+ export declare function maxDate(limit: SharedDateValueType, message: ValidatorMessage<Date, MaxDateValidatorMessageParameters>, exclusive?: boolean): ValidatorTest<Date, never>;
307
227
  /**
308
228
  * Configuration for date validation.
309
229
  * @category Types
@@ -313,75 +233,164 @@ type DateConfig = ConfigBase<Date>;
313
233
  * Validates a date value.
314
234
  * @category Type Validators
315
235
  */
316
- declare const date: ValidatorFactory<DateConfig, Date, string>;
317
-
236
+ export declare const date: ValidatorFactory<DateConfig, Date, string>;
237
+ //#endregion
238
+ //#region src/numbers.d.ts
318
239
  /**
319
240
  * Parses a value into a number.
320
241
  * @param value Value to parse
321
242
  * @category Parsers
322
243
  */
323
- declare function parseNumber(value: unknown): number | null | undefined;
244
+ export declare function parseNumber(value: unknown): number | null | undefined;
324
245
  /**
325
246
  * Applies a configuration to the number value.
326
247
  * @param value Value to modify
327
248
  * @param config Configuration to apply
328
249
  * @category Helpers
329
250
  */
330
- declare function applyNumberConfig(value: unknown, config: NumberConfig): number | null | undefined;
251
+ export declare function applyNumberConfig(value: unknown, config: NumberConfig): number | null | undefined;
331
252
  /**
332
253
  * Ensures a number value is an integer.
333
254
  * @param message Error message
334
255
  * @category Validation Tests
335
256
  */
336
- declare function integer(message: ValidatorMessage<number>): ValidatorTest<number>;
257
+ export declare function integer(message: ValidatorMessage<number>): ValidatorTest<number, never>;
337
258
  /**
338
259
  * Configuration for number validation.
339
260
  * @category Types
340
261
  */
341
262
  interface NumberConfig extends ConfigBase<number> {
342
- /** Apply rounding mechanism before validation. */
343
- round?: 'nearest' | 'floor' | 'ceil';
263
+ /** Apply rounding mechanism before validation. */
264
+ round?: 'nearest' | 'floor' | 'ceil';
344
265
  }
345
266
  /**
346
267
  * Validates a number value.
347
268
  * @category Type Validators
348
269
  */
349
- declare const number: ValidatorFactory<NumberConfig, number, string>;
350
-
351
- type ObjectParameter = Record<string, ValidatorTest<unknown, unknown>>;
270
+ export declare const number: ValidatorFactory<NumberConfig, number, string>;
271
+ //#endregion
272
+ //#region src/parse-date.d.ts
273
+ /** Badly formatted date for internal use. */
274
+ export declare const invalidDate: Date;
275
+ /**
276
+ * Parses a value into a date.
277
+ * @param value Value to parse
278
+ * @category Parsers
279
+ */
280
+ export declare function parseDate(value: unknown): Date | null | undefined;
281
+ //#endregion
282
+ //#region src/objects.d.ts
283
+ type ObjectParameter = Record<string, ValidatorTest>;
352
284
  /**
353
285
  * Validates an object.
354
286
  * @category Type Validators
355
287
  */
356
- declare function object<P extends ObjectParameter, V extends {
357
- [K in keyof P]?: ExtractValue<P[K]>;
358
- }, E extends {
359
- [K in keyof P]?: ExtractError<P[K]>;
360
- }>(properties: P): ValidatorTest<V, E>;
361
-
288
+ export declare function object<P extends ObjectParameter, V extends { [K in keyof P]?: ExtractValue<P[K]>; }, E extends { [K in keyof P]?: ExtractError<P[K]>; }>(properties: P): ValidatorTest<V, E>;
289
+ //#endregion
290
+ //#region src/common.d.ts
291
+ /**
292
+ * Ensures a value is not undefined, null, empty string, NaN, nor invalid date.
293
+ * @param message Error message
294
+ * @param nullable Allow null values
295
+ * @category Validation Tests
296
+ */
297
+ export declare function required<T, P extends ValidatorMessageParameters<T>>(message: ValidatorMessage<T, P>, nullable?: boolean): ValidatorTest<T, never>;
298
+ interface OneOfValidatorMessageParameters<T> extends ValidatorMessageParameters<T> {
299
+ values: readonly T[];
300
+ }
301
+ /**
302
+ * Ensures a value is one in a predefined list.
303
+ * @param values List of allowed values.
304
+ * @param message Error message
305
+ * @category Validation Tests
306
+ */
307
+ export declare function oneOf<T extends string | number | boolean | Date>(values: readonly T[], message: ValidatorMessage<T, OneOfValidatorMessageParameters<T>>): ValidatorTest<T, never>;
308
+ //#endregion
309
+ //#region src/factories.d.ts
310
+ /**
311
+ * Creates a type validator.
312
+ * @typeParam T The basic type for the final value to be validated.
313
+ * @typeParam C The configuration type.
314
+ * @param defaultParser Parser to convert value into type.
315
+ * @param applyConfig Function that applies configuration to value.
316
+ * @category Helpers
317
+ */
318
+ export declare function createTypeValidatorTest<T, C extends ConfigBase<T>>(defaultConfig: C, applyConfig: (value: unknown, config: C) => T | null | undefined): ValidatorFactory<C, T, string>;
319
+ /**
320
+ * Captures basic validator test pattern
321
+ * @param test Test function
322
+ * @param message Error message
323
+ * @param getExtras Optional extra fields for error message
324
+ */
325
+ export declare function createValidatorTest<T = unknown, E = never, P extends ValidatorMessageParameters<T> = ValidatorMessageParameters<T>>(test: (value: unknown, field?: string) => boolean, message: ValidatorMessage<T, P>, getExtras?: (value: T | null | undefined) => Omit<P, 'value' | 'field'>): ValidatorTest<T, E>;
326
+ //#endregion
327
+ //#region src/limits.d.ts
328
+ type SharedValueType = string | number | unknown[];
329
+ interface MaxValidatorMessageParameters extends ValidatorMessageParameters<SharedValueType> {
330
+ max: number;
331
+ amount: number | null | undefined;
332
+ limit: number;
333
+ exclusive?: boolean | undefined;
334
+ }
335
+ /**
336
+ * Ensures a string, number, or array value is at most a certain amount.
337
+ * @param limit Size or value limit
338
+ * @param message Error message
339
+ * @param exclusive Use exclusive comparison instead of inclusive
340
+ * @category Validation Tests
341
+ */
342
+ export declare function max(limit: number, message: ValidatorMessage<SharedValueType, MaxValidatorMessageParameters>, exclusive?: boolean): ValidatorTest<SharedValueType, never>;
343
+ interface MinValidatorMessageParameters extends ValidatorMessageParameters<SharedValueType> {
344
+ min: number;
345
+ limit: number;
346
+ amount: number | null | undefined;
347
+ exclusive?: boolean | undefined;
348
+ }
349
+ /**
350
+ * Ensures a string, number, or array value is at most a certain amount.
351
+ * @param limit Size or value limit
352
+ * @param message Error message
353
+ * @param exclusive Use exclusive comparison instead of inclusive
354
+ * @category Validation Tests
355
+ */
356
+ export declare function min(limit: number, message: ValidatorMessage<SharedValueType, MinValidatorMessageParameters>, exclusive?: boolean): ValidatorTest<SharedValueType, never>;
357
+ interface ExactValidatorMessageParameters extends ValidatorMessageParameters<SharedValueType> {
358
+ limit: number;
359
+ amount: number | null | undefined;
360
+ exact: number;
361
+ }
362
+ /**
363
+ * Ensures a string, number, or array value is exactly a certain amount.
364
+ * @param limit Size or value limit
365
+ * @param message Error message
366
+ * @category Validation Tests
367
+ */
368
+ export declare function exact(limit: number, message: ValidatorMessage<SharedValueType, ExactValidatorMessageParameters>): ValidatorTest<SharedValueType, never>;
369
+ //#endregion
370
+ //#region src/strings.d.ts
362
371
  /**
363
372
  * Configuration for string validation.
364
373
  * @category Types
365
374
  */
366
375
  interface StringConfig extends ConfigBase<string> {
367
- /** Apply trim to string before validation. */
368
- trim?: boolean;
376
+ /** Apply trim to string before validation. */
377
+ trim?: boolean;
369
378
  }
370
379
  /**
371
380
  * Parses a value into a string.
372
381
  * @param value Value to parse
373
382
  * @category Parsers
374
383
  */
375
- declare function parseString(value: unknown): string | null | undefined;
384
+ export declare function parseString(value: unknown): string | null | undefined;
376
385
  /**
377
386
  * Applies a configuration to the string value.
378
387
  * @param value Value to modify
379
388
  * @param config Configuration to apply
380
389
  * @category Helpers
381
390
  */
382
- declare function applyStringConfig(value: unknown, config: StringConfig): string | null | undefined;
391
+ export declare function applyStringConfig(value: unknown, config: StringConfig): string | null | undefined;
383
392
  interface MatchesValidatorMessageParameters extends ValidatorMessageParameters<string> {
384
- pattern: RegExp;
393
+ pattern: RegExp;
385
394
  }
386
395
  /**
387
396
  * Ensures a string value matches a pattern
@@ -389,13 +398,20 @@ interface MatchesValidatorMessageParameters extends ValidatorMessageParameters<s
389
398
  * @param message Error message
390
399
  * @category Validation Tests
391
400
  */
392
- declare function matches(pattern: RegExp, message: ValidatorMessage<string, MatchesValidatorMessageParameters>): ValidatorTest<string>;
401
+ export declare function matches(pattern: RegExp, message: ValidatorMessage<string, MatchesValidatorMessageParameters>): ValidatorTest<string, never>;
393
402
  /**
394
403
  * Ensures a string value matches an email pattern
395
404
  * @param message Error message
396
405
  * @category Validation Tests
397
406
  */
398
- declare function email(message: ValidatorMessage<string>): ValidatorTest<string>;
407
+ export declare function email(message: ValidatorMessage<string>): ValidatorTest<string, never>;
408
+ /**
409
+ * Ensures a string value is an RFC 9562 UUID, any version from 1 to 8, or the
410
+ * nil or max UUID. Case-insensitive, without braces or a `urn:uuid:` prefix.
411
+ * @param message Error message
412
+ * @category Validation Tests
413
+ */
414
+ export declare function uuid(message: ValidatorMessage<string>): ValidatorTest<string, never>;
399
415
  /**
400
416
  * Ensures a string value is a valid URL
401
417
  * @param message Error message
@@ -403,11 +419,11 @@ declare function email(message: ValidatorMessage<string>): ValidatorTest<string>
403
419
  * and `data:` URLs are valid; use `['http:', 'https:']` for values rendered as links.
404
420
  * @category Validation Tests
405
421
  */
406
- declare function url(message: ValidatorMessage<string>, protocols?: string[]): ValidatorTest<string>;
422
+ export declare function url(message: ValidatorMessage<string>, protocols?: string[]): ValidatorTest<string, never>;
407
423
  /**
408
424
  * Validates a string value.
409
425
  * @category Type Validators
410
426
  */
411
- declare const string: ValidatorFactory<StringConfig, string, string>;
412
-
413
- export { type ArrayConfig, type ArrayItemValidatorResult, type BooleanConfig, type ConfigBase, type DateConfig, type DeepPartial, type ExactValidatorMessageParameters, type ExtractError, type ExtractValue, type InvalidResult, type MatchesValidatorMessageParameters, type MaxDateValidatorMessageParameters, type MaxValidatorMessageParameters, type MinDateValidatorMessageParameters, type MinValidatorMessageParameters, type NumberConfig, type ObjectParameter as ObjectParam, type OneOfValidatorMessageParameters, type SharedDateValueType, type SharedValueType, type StringConfig, type ValidResult, type ValidatorFactory, type ValidatorMessage, type ValidatorMessageParameters, type ValidatorResult, type ValidatorTest, applyArrayConfig, applyBooleanConfig, applyDateConfig, applyNumberConfig, applyStringConfig, array, boolean, createTypeValidatorTest, createValidatorTest, date, email, exact, formatMessage, hasOwnProperty, integer, invalid, invalidDate, isObject, matches, max, maxDate, min, minDate, number, object, oneOf, parseArray, parseBoolean, parseDate, parseNumber, parseString, required, string, url, valid };
427
+ export declare const string: ValidatorFactory<StringConfig, string, string>;
428
+ //#endregion
429
+ export type { ArrayConfig, ArrayItemValidatorResult, BooleanConfig, ConfigBase, DateConfig, DeepPartial, ExactValidatorMessageParameters, ExtractError, ExtractValue, InvalidResult, MatchesValidatorMessageParameters, MaxDateValidatorMessageParameters, MaxValidatorMessageParameters, MinDateValidatorMessageParameters, MinValidatorMessageParameters, NumberConfig, ObjectParameter as ObjectParam, OneOfValidatorMessageParameters, SharedDateValueType, SharedValueType, StringConfig, ValidResult, ValidatorFactory, ValidatorMessage, ValidatorMessageParameters, ValidatorResult, ValidatorTest };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- function T(e){return Object.prototype.toString.call(e)==="[object Object]"}function x(e,r){return Object.prototype.hasOwnProperty.call(e,r)}var I=/{(\w+)}/g;function P(e,r){return typeof e=="string"?e.replaceAll(I,(t,a)=>String(r[a])):e(r)}async function m({value:e,field:r}){return{isValid:!0,state:"valid",value:e,field:r}}async function p({errors:e,field:r,message:t,value:a,extras:n}){return{isValid:!1,state:"invalid",message:P(t,{...n,value:a,field:r}),value:a,field:r,errors:e}}function g(e,r){return(t,...a)=>{let n=e,o=a;return t!==void 0&&(typeof t=="function"?o=[t,...a]:n={...e,...t}),async(i,s)=>{try{let d=r(i,n);for(let f of o){let l=await f(d,s);if(l.state==="invalid")return l}return await m({value:d,field:s})}catch(d){return p({message:d instanceof Error?d.message:String(d),value:i,field:s})}}}}function u(e,r,t){return async(a,n)=>e(a,n)?m({value:a,field:n}):p({message:r,value:a,field:n,extras:t?t(a):void 0})}function R(e,r){return u(t=>r&&t===null||t!=null&&!(typeof t=="string"&&t==="")&&!(typeof t=="number"&&Number.isNaN(t))&&!(t instanceof Date&&Number.isNaN(t.valueOf())),e)}function c(e){return typeof e=="string"||Array.isArray(e)?e.length:e}function B(e,r,t){return u(a=>{let n=c(a);return n==null||a===""||(t?n<e:n<=e)},r,a=>({max:e,limit:e,amount:c(a),exclusive:t}))}function j(e,r,t){return u(a=>{let n=c(a);return n==null||a===""||(t?n>e:n>=e)},r,a=>({min:e,limit:e,amount:c(a),exclusive:t}))}function z(e,r){return u(t=>{let a=c(t);return a==null||t===""||a===e},r,t=>({amount:c(t),limit:e,exact:e}))}function F(e,r){return u(t=>t==null||e.includes(t)||t instanceof Date&&e.some(a=>a.valueOf()===t.valueOf()),r,()=>({values:e}))}function M(e){if(Array.isArray(e)||e==null)return e;let r=e;return r[Symbol.iterator]?[...r]:[]}function w(e,r){let t=e.parser(r);return e.default!==void 0&&(t==null||t.length===0)&&(t=e.default),t}async function Z(e,r,t){for(let a of e){let n=await a(r,t);if(n.state==="invalid")return n}}async function $(e,r,t){let a=!0,n=[];if(!r||!e)return{isValid:a,errors:n};for(let[o,i]of r.entries()){let s=await e(i,t?`${t}[${o}]`:`[${o}]`);s.state==="invalid"?(a=!1,n.push(s.message||s.errors)):n.push(null)}return{isValid:a,errors:n}}function K(e,...r){let t=r,a={parser:M};return e!==void 0&&(typeof e=="function"?t=[e,...r]:a={...a,...e}),async(n,o)=>{let i=w(a,n),[s,...d]=t,f=await Z(d,i,o),l=await $(s,i,o);return!f&&l.isValid?m({value:i,field:o}):p({message:f?f.message:"",value:n,field:o,errors:l.errors})}}function D(e){return e==null||typeof e=="boolean"?e:!!e}function E(e,r){let t=r.parser(e);return r.default!==void 0&&t==null&&(t=r.default),t}var U=g({parser:D},E);var b=new Date(""),q=/^(\d{4})(?:-([0-2]\d)(?:-([0-3]\d)(?:[ T]([0-2]\d):([0-5]\d)(?::([0-5]\d)(\.\d+)?(Z|[+-][0-2]\d:?[0-5]\d)?)?)?)?)?$/,L=/^([+-])([0-2]\d):?([0-5]\d)$/;function _(e){let r=L.exec(e);if(e==="Z"||!r)return 0;let[,t,a="0",n="0"]=r,o=t==="-"?-1:1,s=Number.parseInt(a,10)*60+Number.parseInt(n,10);return o*s}var V=10,G=[()=>0,(e="0")=>Number.parseInt(e,V),(e="1")=>Number.parseInt(e,V)-1,(e="1")=>Number.parseInt(e,V),(e="0")=>Number.parseInt(e,V),(e="0")=>Number.parseInt(e,V),(e="0")=>Number.parseInt(e,V),(e="0")=>Number.parseFloat(e)*1e3];function y(e){return e==null||e instanceof Date?e:typeof e=="number"?new Date(e):typeof e=="string"?H(e):b}function H(e){let r=q.exec(e);if(r===null)return b;let[,t=0,a=0,n=0,o=0,i=0,s=0,d=0]=G.map((l,O)=>l(r[O])),f=r[8];return f?new Date(Date.UTC(t,a,n,o,i+_(f),s,d)):new Date(t,a,n,o,i,s,d)}function h(e,r){let t=r.parser(e);return r.default!==void 0&&(t==null||Number.isNaN(t.getTime()))&&(t=r.default),t}function J(e,r,t){let a=y(e);return u(n=>a!=null&&(n==null||n instanceof Date&&(t?n>a:n>=a)),r,()=>({min:a,limit:a,exclusive:t}))}function Q(e,r,t){let a=y(e);return u(n=>a!=null&&(n==null||n instanceof Date&&(t?n<a:n<=a)),r,()=>({max:a,limit:a,exclusive:t}))}var W=g({parser:y},h);function C(e){return e==null||typeof e=="number"?e:e instanceof Date?e.getTime():typeof e=="string"?Number.parseFloat(e):Number.parseFloat(String(e))}function k(e,r){let t=r.parser(e);if(r.default!==void 0&&(t==null||Number.isNaN(t))&&(t=r.default),r.round&&typeof t=="number")switch(r.round){case"nearest":{t=Math.round(t);break}case"ceil":{t=Math.ceil(t);break}case"floor":{t=Math.floor(t);break}default:throw new Error(`Unknown round type: ${String(r.round)}`)}return t}function X(e){return async(r,t)=>r==null||typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r?m({value:r,field:t}):p({message:e,value:r,field:t})}var Y=g({parser:C},k);function v(e){if(typeof e!="object"||e===null)throw new TypeError("`properties` must be a configuration object");return async(r,t)=>{let a=r??{},n={},o={},i=!0;for(let s in e)if(x(e,s)){let d=e[s],f=a[s],l=typeof d=="function"?await d(f,s):await p({field:s,message:"No validator set",value:f});o[s]=l.value,l.state==="invalid"&&(i=!1,n[s]=l.message||l.errors)}return i?m({value:o,field:t}):p({message:"",value:r,field:t,errors:n})}}var ee=/^[\w!#$%&'*+./=?^`{|}~-]+@[\dA-Za-z](?:[\dA-Za-z-]{0,61}[\dA-Za-z])?(?:\.[\dA-Za-z](?:[\dA-Za-z-]{0,61}[\dA-Za-z])?)*$/;function S(e){if(e==null||typeof e=="string")return e;if(e instanceof Date)return e.toISOString();if(T(e))throw new TypeError("Failed to parse value to string.");return String(e)}function N(e,r){let t=r.parser(e);return r.default!==void 0&&(t==null||t==="")&&(t=r.default),r.trim&&typeof t=="string"&&(t=t.trim()),t}function A(e,r){let t=new RegExp(e);return u(a=>(t.lastIndex=0,a==null||a===""||typeof a=="string"&&t.test(a)),r,()=>({pattern:e}))}function te(e){return A(ee,e)}function re(e,r){return u(t=>{try{let a;if(t==null||t===""||typeof t=="string"&&(a=new URL(t)))return!(a&&r&&!r.includes(a.protocol))}catch{}return!1},e,()=>({protocols:r}))}var ae=g({parser:S},N);export{w as applyArrayConfig,E as applyBooleanConfig,h as applyDateConfig,k as applyNumberConfig,N as applyStringConfig,K as array,U as boolean,g as createTypeValidatorTest,u as createValidatorTest,W as date,te as email,z as exact,P as formatMessage,x as hasOwnProperty,X as integer,p as invalid,b as invalidDate,T as isObject,A as matches,B as max,Q as maxDate,j as min,J as minDate,Y as number,v as object,F as oneOf,M as parseArray,D as parseBoolean,y as parseDate,C as parseNumber,S as parseString,R as required,ae as string,re as url,m as valid};
1
+ function e(e){return Object.prototype.toString.call(e)===`[object Object]`}function t(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function n(e){return!!Reflect.get(Object(e),Symbol.iterator)}const r=/{(\w+)}/g;function i(e,t){return typeof e==`string`?e.replaceAll(r,(e,n)=>String(Reflect.get(t,n))):e(t)}async function a({value:e,field:t}){return{isValid:!0,state:`valid`,value:e,field:t}}async function o({errors:e,field:t,message:n,value:r,extras:a}){return{isValid:!1,state:`invalid`,message:i(n,{...a,value:r,field:t}),value:r,field:t,errors:e}}function s(e){return Array.isArray(e)||e==null?e:n(e)?[...e]:[]}function c(e,t){let n=e.parser(t);return e.default!==void 0&&(n==null||n.length===0)&&(n=e.default),n}async function l(e,t,n){for(let r of e){let e=await r(t,n);if(e.state===`invalid`)return e}}async function u(e,t,n){let r=!0,i=[];if(!t||!e)return{isValid:r,errors:i};for(let[a,o]of t.entries()){let t=await e(o,n?`${n}[${a}]`:`[${a}]`);t.state===`invalid`?(r=!1,i.push(t.message||t.errors)):i.push(null)}return{isValid:r,errors:i}}function d(e,...t){let n=t,r={parser:s};return e!==void 0&&(typeof e==`function`?n=[e,...t]:r={...r,...e}),async(e,t)=>{let i=c(r,e),[s,...d]=n,f=await l(d,i,t),p=await u(s,i,t);return!f&&p.isValid?a({value:i,field:t}):o({message:f?f.message:``,value:e,field:t,errors:p.errors})}}function f(e,t){return(n,...r)=>{let i=e,s=r;return n!==void 0&&(typeof n==`function`?s=[n,...r]:i={...e,...n}),async(e,n)=>{try{let r=t(e,i);for(let e of s){let t=await e(r,n);if(t.state===`invalid`)return t}return await a({value:r,field:n})}catch(t){return o({message:t instanceof Error?t.message:String(t),value:e,field:n})}}}}function p(e,t,n){return async(r,i)=>e(r,i)?a({value:r,field:i}):o({message:t,value:r,field:i,extras:n?n(r):void 0})}function m(e){return e==null||typeof e==`boolean`?e:!!e}function h(e,t){let n=t.parser(e);return t.default!==void 0&&n==null&&(n=t.default),n}const g=f({parser:m},h),_=/* @__PURE__ */ new Date(``),v=/^(\d{4})(?:-([0-2]\d)(?:-([0-3]\d)(?:[ T]([0-2]\d):([0-5]\d)(?::([0-5]\d)(\.\d+)?(Z|[+-][0-2]\d:?[0-5]\d)?)?)?)?)?$/,y=/^([+-])([0-2]\d):?([0-5]\d)$/;function b(e){let t=y.exec(e);if(e===`Z`||!t)return 0;let[,n,r=`0`,i=`0`]=t;return(n===`-`?-1:1)*(Number.parseInt(r,10)*60+Number.parseInt(i,10))}const x=[()=>0,(e=`0`)=>Number.parseInt(e,10),(e=`1`)=>Number.parseInt(e,10)-1,(e=`1`)=>Number.parseInt(e,10),(e=`0`)=>Number.parseInt(e,10),(e=`0`)=>Number.parseInt(e,10),(e=`0`)=>Number.parseInt(e,10),(e=`0`)=>Number.parseFloat(e)*1e3];function S(e){return e==null||e instanceof Date?e:typeof e==`number`?new Date(e):typeof e==`string`?C(e):_}function C(e){let t=v.exec(e);if(t===null)return _;let[,n=0,r=0,i=0,a=0,o=0,s=0,c=0]=x.map((e,n)=>e(t[n])),l=t[8];return l?new Date(Date.UTC(n,r,i,a,o+b(l),s,c)):new Date(n,r,i,a,o,s,c)}function w(e,t){let n=t.parser(e);return t.default!==void 0&&(n==null||Number.isNaN(n.getTime()))&&(n=t.default),n}function T(e,t,n){let r=S(e);return p(e=>r!=null&&(e==null||e instanceof Date&&(n?e>r:e>=r)),t,()=>({min:r,limit:r,exclusive:n}))}function E(e,t,n){let r=S(e);return p(e=>r!=null&&(e==null||e instanceof Date&&(n?e<r:e<=r)),t,()=>({max:r,limit:r,exclusive:n}))}const D=f({parser:S},w);function O(e){return e==null||typeof e==`number`?e:e instanceof Date?e.getTime():typeof e==`string`?Number.parseFloat(e):Number.parseFloat(String(e))}function k(e,t){let n=t.parser(e);if(t.default!==void 0&&(n==null||Number.isNaN(n))&&(n=t.default),t.round&&typeof n==`number`)switch(t.round){case`nearest`:n=Math.round(n);break;case`ceil`:n=Math.ceil(n);break;case`floor`:n=Math.floor(n);break;default:throw Error(`Unknown round type: ${String(t.round)}`)}return n}function A(e){return async(t,n)=>t==null||typeof t==`number`&&Number.isFinite(t)&&Math.floor(t)===t?a({value:t,field:n}):o({message:e,value:t,field:n})}const j=f({parser:O},k);function M(e){if(typeof e!=`object`||!e)throw TypeError("`properties` must be a configuration object");return async(n,r)=>{let i={},s={},c=!0;for(let r in e)if(t(e,r)){let t=e[r],a=Reflect.get(Object(n),r),l=await(typeof t==`function`?t(a,r):o({field:r,message:`No validator set`,value:a}));s[r]=l.value,l.state===`invalid`&&(c=!1,i[r]=l.message||l.errors)}return c?a({value:s,field:r}):o({message:``,value:n,field:r,errors:i})}}function N(e,t){return p(e=>t&&e===null||e!=null&&(typeof e!=`string`||e!==``)&&!(typeof e==`number`&&Number.isNaN(e))&&!(e instanceof Date&&Number.isNaN(e.valueOf())),e)}function P(e,t){let n=e;return p(t=>t==null||n.includes(t)||t instanceof Date&&e.some(e=>e.valueOf()===t.valueOf()),t,()=>({values:e}))}function F(e){return typeof e==`string`||Array.isArray(e)?e.length:e}function I(e,t,n){return p(t=>{let r=F(t);return r==null||t===``||(n?r<e:r<=e)},t,t=>({max:e,limit:e,amount:F(t),exclusive:n}))}function L(e,t,n){return p(t=>{let r=F(t);return r==null||t===``||(n?r>e:r>=e)},t,t=>({min:e,limit:e,amount:F(t),exclusive:n}))}function R(e,t){return p(t=>{let n=F(t);return n==null||t===``||n===e},t,t=>({amount:F(t),limit:e,exact:e}))}const z=/^[\w!#$%&'*+./=?^`{|}~-]+@[\dA-Za-z](?:[\dA-Za-z-]{0,61}[\dA-Za-z])?(?:\.[\dA-Za-z](?:[\dA-Za-z-]{0,61}[\dA-Za-z])?)*$/,B=/^(?:[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}|0{8}-0{4}-0{4}-0{4}-0{12}|f{8}-f{4}-f{4}-f{4}-f{12})$/i;function V(t){if(t==null||typeof t==`string`)return t;if(t instanceof Date)return t.toISOString();if(e(t))throw TypeError(`Failed to parse value to string.`);return String(t)}function H(e,t){let n=t.parser(e);return t.default!==void 0&&(n==null||n===``)&&(n=t.default),t.trim&&typeof n==`string`&&(n=n.trim()),n}function U(e,t){let n=new RegExp(e);return p(e=>(n.lastIndex=0,e==null||e===``||typeof e==`string`&&n.test(e)),t,()=>({pattern:e}))}function W(e){return U(z,e)}function G(e){return U(B,e)}function K(e,t){return p(e=>{try{let n;if(e==null||e===``||typeof e==`string`&&(n=new URL(e)))return!(n&&t&&!t.includes(n.protocol))}catch{}return!1},e,()=>({protocols:t}))}const q=f({parser:V},H);export{c as applyArrayConfig,h as applyBooleanConfig,w as applyDateConfig,k as applyNumberConfig,H as applyStringConfig,d as array,g as boolean,f as createTypeValidatorTest,p as createValidatorTest,D as date,W as email,R as exact,i as formatMessage,t as hasOwnProperty,A as integer,o as invalid,_ as invalidDate,e as isObject,U as matches,I as max,E as maxDate,L as min,T as minDate,j as number,M as object,P as oneOf,s as parseArray,m as parseBoolean,S as parseDate,O as parseNumber,V as parseString,N as required,q as string,K as url,G as uuid,a as valid};
2
2
  //# sourceMappingURL=index.js.map