structure-verifier 0.0.15 → 0.0.17

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 (43) hide show
  1. package/README.md +474 -326
  2. package/dist/index.d.ts +50 -26
  3. package/dist/index.js +20 -15
  4. package/dist/index.js.map +1 -1
  5. package/dist/src/error/v_error.d.ts +9 -4
  6. package/dist/src/error/v_error.js +15 -7
  7. package/dist/src/error/v_error.js.map +1 -1
  8. package/dist/src/interfaces/types.d.ts +3 -3
  9. package/dist/src/languages/message.d.ts +1 -1
  10. package/dist/src/languages/message.js +7 -4
  11. package/dist/src/languages/message.js.map +1 -1
  12. package/dist/src/verifiers/any/v_any.d.ts +1 -2
  13. package/dist/src/verifiers/any/v_any.js +8 -4
  14. package/dist/src/verifiers/any/v_any.js.map +1 -1
  15. package/dist/src/verifiers/array/v_array.d.ts +28 -9
  16. package/dist/src/verifiers/array/v_array.js +65 -35
  17. package/dist/src/verifiers/array/v_array.js.map +1 -1
  18. package/dist/src/verifiers/boolean/v_boolean.d.ts +5 -2
  19. package/dist/src/verifiers/boolean/v_boolean.js +34 -24
  20. package/dist/src/verifiers/boolean/v_boolean.js.map +1 -1
  21. package/dist/src/verifiers/date/v_date.d.ts +27 -2
  22. package/dist/src/verifiers/date/v_date.js +88 -60
  23. package/dist/src/verifiers/date/v_date.js.map +1 -1
  24. package/dist/src/verifiers/helpers/conditionMessage.d.ts +3 -0
  25. package/dist/src/verifiers/helpers/conditionMessage.js +19 -0
  26. package/dist/src/verifiers/helpers/conditionMessage.js.map +1 -0
  27. package/dist/src/verifiers/number/v_number.d.ts +39 -2
  28. package/dist/src/verifiers/number/v_number.js +70 -53
  29. package/dist/src/verifiers/number/v_number.js.map +1 -1
  30. package/dist/src/verifiers/object/v_object.d.ts +21 -15
  31. package/dist/src/verifiers/object/v_object.js +118 -67
  32. package/dist/src/verifiers/object/v_object.js.map +1 -1
  33. package/dist/src/verifiers/string/v_string.d.ts +59 -2
  34. package/dist/src/verifiers/string/v_string.js +165 -105
  35. package/dist/src/verifiers/string/v_string.js.map +1 -1
  36. package/dist/src/verifiers/type.d.ts +1 -0
  37. package/dist/src/verifiers/uuid/v_uuid.d.ts +9 -2
  38. package/dist/src/verifiers/uuid/v_uuid.js +99 -41
  39. package/dist/src/verifiers/uuid/v_uuid.js.map +1 -1
  40. package/dist/src/verifiers/verifier.d.ts +1 -0
  41. package/dist/src/verifiers/verifier.js +9 -1
  42. package/dist/src/verifiers/verifier.js.map +1 -1
  43. package/package.json +1 -1
package/README.md CHANGED
@@ -1,422 +1,570 @@
1
- # structure-verifier 0.0.9
1
+ # structure-verifier
2
2
 
3
- structure-verifier is a typescript library to validate data of "any" type and to ensure that it corresponds to a data type.
3
+ Libreria de validacion para TypeScript orientada a esquemas declarativos, tipado inferido y errores detallados por ruta.
4
4
 
5
- ## Installation
5
+ Ideal para validar payloads de API, formularios, configuraciones y estructuras anidadas complejas.
6
+
7
+ Version actual: 0.0.17
8
+
9
+ ## Contenido
10
+
11
+ - Caracteristicas
12
+ - Instalacion
13
+ - Inicio rapido
14
+ - Conceptos base
15
+ - API publica
16
+ - Referencia completa de validadores
17
+ - Transformaciones de valores
18
+ - Tipado inferido
19
+ - Manejo de errores
20
+ - Ejemplos avanzados
21
+ - Scripts de desarrollo
22
+
23
+ ## Caracteristicas
24
+
25
+ - Validadores para number, string, boolean, uuid, date, array, object y any.
26
+ - Soporte para estructuras anidadas con errores por ruta.
27
+ - API fluida por clases y API de fabrica mediante Verifiers.
28
+ - Tipado inferido en compile-time para mantener consistencia del dominio.
29
+ - Personalizacion de mensajes por regla y por validador.
30
+ - Integracion con dayjs (exportado como datetime) para manejo de fechas.
31
+
32
+ ## Instalacion
6
33
 
7
34
  ```bash
8
- npm install structure-verifier
35
+ npm install structure-verifier
9
36
  ```
10
37
 
11
- ## Example use
38
+ ## Inicio rapido
12
39
 
13
- ```typescript
40
+ ```ts
14
41
  import { Verifiers as V, VerificationError } from "structure-verifier";
15
- //////////Verificator object creation
16
- const v = new V.Number();
17
- /////////Running validations
18
42
 
19
- try {
20
- let value = v.check(10);
21
- /////////Will get the value without error
22
- } catch (error:any) {
23
- console.log(error as VerificationError);
24
- }
43
+ const userVerifier = V.ObjectNotNull(
44
+ {
45
+ id: V.UUIDNotNull({ version: 4 }),
46
+ name: V.StringNotNull({ minLength: 2 }),
47
+ age: V.Number({ min: 0 }),
48
+ active: V.BooleanNotNull(),
49
+ tags: V.ArrayNotNull(V.StringNotNull()).minLength(1),
50
+ },
51
+ {
52
+ strictMode: true,
53
+ },
54
+ );
25
55
 
26
56
  try {
27
- let value = v.check('TEST');
28
- } catch (error:any) {
29
- ///////////Will get the error, because the value is not a number
30
- console.log(error as VerificationError);
57
+ const user = userVerifier.check({
58
+ id: "550e8400-e29b-41d4-a716-446655440000",
59
+ name: "Ana",
60
+ age: "31",
61
+ active: "true",
62
+ tags: ["admin"],
63
+ });
64
+
65
+ console.log(user);
66
+ } catch (error) {
67
+ if (error instanceof VerificationError) {
68
+ console.log(error.message);
69
+ console.log(error.errors);
70
+ console.log(error.errorsObj);
71
+ }
31
72
  }
32
73
  ```
33
74
 
34
- ### Alternative Import with Verifiers Object
35
-
36
- You can also import the `Verifiers` object which contains all available validators:
37
-
38
- ```typescript
39
- import { Verifiers, VerificationError } from "structure-verifier";
40
-
41
- // Available verifiers:
42
- const numberVal = new Verifiers.Number(); // VNumber
43
- const numberNotNullVal = new Verifiers.NumberNotNull(); // VNumberNotNull
44
- const stringVal = new Verifiers.String(); // VString
45
- const stringNotNullVal = new Verifiers.StringNotNull(); // VStringNotNull
46
- const booleanVal = new Verifiers.Boolean(); // VBoolean
47
- const booleanNotNullVal = new Verifiers.BooleanNotNull(); // VBooleanNotNull
48
- const objectVal = new Verifiers.Object({ properties: {} }); // VObject
49
- const objectNotNullVal = new Verifiers.ObjectNotNull({ properties: {} }); // VObjectNotNull
50
- const arrayVal = new Verifiers.Array({ verifier: new Verifiers.Number() }); // VArray
51
- const arrayNotNullVal = new Verifiers.ArrayNotNull({ verifier: new Verifiers.Number() }); // VArrayNotNull
52
- const anyVal = new Verifiers.Any(); // VAny
53
- const dateVal = new Verifiers.Date(); // VDate
54
- const dateNotNullVal = new Verifiers.DateNotNull(); // VDateNotNull
55
- const uuidVal = new Verifiers.UUID(); // VUUID
56
- const uuidNotNullVal = new Verifiers.UUIDNotNull(); // VUUIDNotNull
57
- ```
58
- ## Types
59
- In case it is necessary to infer the type of the response, it is achieved by using InferType
60
-
61
- ```typescript
62
- import { InferType, Verifiers as V } from "structure-verifier";
63
-
64
- const val = new V.Number();
65
- type valType = InferType<typeof val>;
66
-
67
- function action(data:valType){
68
- ...
69
- }
70
- ```
71
- ## Validations
75
+ ## Conceptos base
76
+
77
+ ### 1) Nullable vs NotNull
78
+
79
+ - VNumber, VString, VBoolean, VDate, VUUID, VArray y VObject retornan tipo nullable.
80
+ - Sus versiones NotNull retornan el tipo requerido.
81
+ - Tambien puedes promover un validador nullable a requerido con required().
82
+
83
+ ### 2) Reglas comunes
72
84
 
73
- ### Numbers
74
- Validations to numerical data
75
- ```typescript
76
- const numberVal = new V.Number();////return number|null
77
- const notNullNumberVal = new V.NumberNotNull() ////return number
85
+ Muchos validadores comparten estas opciones:
86
+
87
+ - isRequired: fuerza que el valor exista.
88
+ - emptyAsNull: transforma string vacio a null antes de validar.
89
+ - defaultValue: valor por defecto para undefined y, en algunos casos, null.
90
+ - badTypeMessage: reemplaza el mensaje de tipo invalido.
91
+
92
+ ### 3) Mensajes personalizados
93
+
94
+ Las reglas aceptan mensajes de estas formas:
95
+
96
+ - String fijo.
97
+ - Funcion callback con el objeto de valores de la regla.
98
+ - Objeto con estructura val + message.
99
+
100
+ Ejemplo:
101
+
102
+ ```ts
103
+ const age = V.NumberNotNull().min(18, (v) => `Edad minima: ${v.min}`);
78
104
  ```
79
- Number exclusive conditions
80
-
81
- - **min:** - Used to denote the smallest valid number.
82
- - **max:** - Used to denote the biggest valid number.
83
- - **in:** - Used to denote an array of valid numbers that the value must be one of.
84
- - **notIn:** - Used to denote an array of numbers that the value must not be one of.
85
- - **maxDecimalPlaces:** - Used to denote the maximum number of decimal places allowed.
86
- - **minDecimalPlaces:** - Used to denote the minimum number of decimal places required.
87
-
88
- #### Example
89
- ```typescript
90
- const numberVal = new V.Number({
91
- min:10,
92
- max:20,
93
- in: [15,16,17],
94
- notIn: [18,19,20],
95
- maxDecimalPlaces: 0,
96
- minDecimalPlaces: 0
97
- });
98
- /////Validate a number or null that meets all conditions otherwise error (VerificationError)
105
+
106
+ ## API publica
107
+
108
+ Import principal:
109
+
110
+ ```ts
111
+ import {
112
+ Verifiers,
113
+ VerificationError,
114
+ Verifier,
115
+ InferType,
116
+ InferFactoryType,
117
+ VAny,
118
+ VArray,
119
+ VArrayNotNull,
120
+ VBoolean,
121
+ VBooleanNotNull,
122
+ VDate,
123
+ VDateNotNull,
124
+ VNumber,
125
+ VNumberNotNull,
126
+ VObject,
127
+ VObjectNotNull,
128
+ VString,
129
+ VStringNotNull,
130
+ VUUID,
131
+ VUUIDNotNull,
132
+ datetime,
133
+ } from "structure-verifier";
99
134
  ```
100
- ***
101
- ### Strings
102
- Validations for string data.
103
135
 
104
- ```typescript
105
- const stringVal = new V.String(); // Returns string | null
106
- const notNullStringVal = new V.StringNotNull(); // Returns string
136
+ Tambien se exportan los tipos de condiciones:
137
+
138
+ - VAnyConditions
139
+ - VArrayConditions
140
+ - VBooleanConditions
141
+ - VDateConditions
142
+ - VNumberConditions
143
+ - VObjectConditions
144
+ - VObjectConditionsNotNull
145
+ - VStringConditions
146
+ - VUUIDConditions
147
+
148
+ ## Estilos de uso
149
+
150
+ ### API de fabrica (recomendada)
151
+
152
+ ```ts
153
+ import { Verifiers as V } from "structure-verifier";
154
+
155
+ const nameV = V.StringNotNull({ minLength: 3 });
107
156
  ```
108
- String Exclusive Conditions
109
- - **minLength:** - Specifies the minimum length the string must have.
110
- - **maxLength:** - Specifies the maximum length the string can have.
111
- - **regex:** - Specifies a regular expression pattern the string must match.
112
- - **notRegex:** - Specifies a regular expression pattern the string must not match.
113
- - **in:** - Specifies an array of valid string values; the string must be one of these values.
114
- - **notIn:** - Specifies an array of string values that the string must not be one of.
115
- - **strictMode:** - When true, ensures the value is strictly a string (not coerced from another type).
116
- - **ignoreCase:** - When true, makes the in condition case-insensitive.
117
-
118
- #### Example
119
- ```typescript
120
- const stringVal = new V.String({
121
- minLength: 5,
122
- maxLength: 10,
123
- regex: /^[a-zA-Z]+$/,
124
- notRegex: /[^a-zA-Z]/,
125
- in: ['apple', 'banana', 'cherry'],
126
- notIn: ['date', 'fig', 'grape'],
127
- strictMode: true,
128
- ignoreCase: true
129
- });
130
- ///// Validate a string or null that meets all conditions otherwise error (VerificationError)
157
+
158
+ ### Clases directas
159
+
160
+ ```ts
161
+ import { VStringNotNull } from "structure-verifier";
162
+
163
+ const nameV = new VStringNotNull({ minLength: 3 });
131
164
  ```
132
- ***
133
- ### Booleans
134
- Validations for boolean data.
135
165
 
136
- ```typescript
137
- const booleanVal = new V.Boolean(); // Returns boolean | null
138
- const notNullBooleanVal = new V.BooleanNotNull(); // Returns boolean
166
+ ### Callable constructors
167
+
168
+ En Verifiers puedes usar los miembros como funcion o con new.
169
+
170
+ ```ts
171
+ const a = V.NumberNotNull({ min: 1 });
172
+ const b = new V.NumberNotNull({ min: 1 });
139
173
  ```
140
174
 
141
- Boolean Exclusive Conditions
175
+ ## Referencia completa de validadores
142
176
 
143
- *No exclusive conditions for boolean validation*
177
+ ### Number y NumberNotNull
144
178
 
145
- #### Example
146
- ```typescript
147
- const booleanVal = new V.Boolean();
148
- const notNullBooleanVal = new V.BooleanNotNull();
179
+ Retorno:
149
180
 
150
- try {
151
- console.log(booleanVal.check('true')); // Output: true
152
- console.log(booleanVal.check('FALSE')); // Output: false
153
- console.log(booleanVal.check(null)); // Output: null
154
- console.log(notNullBooleanVal.check('1')); // Output: true
155
- console.log(notNullBooleanVal.check(0)); // Output: false
156
- } catch (error) {
157
- console.error(error);
158
- }
159
- ```
160
- ***
161
- ### Objects
162
- Validations for object data.
181
+ - VNumber: number | null
182
+ - VNumberNotNull: number
163
183
 
164
- ```typescript
165
- const objectVal = new V.Object({ properties: { name: new V.String({ minLength: 3 })/* properties with validations */ } }); // Returns object {name:""} | null
166
- const notNullObjectVal = new V.ObjectNotNull({ properties: { name: new V.String({ minLength: 3 })/* properties with validations */ } }); // Returns object {name:""}
167
- ```
184
+ Condiciones:
168
185
 
169
- Object Exclusive Conditions
186
+ - min
187
+ - max
188
+ - in
189
+ - notIn
190
+ - maxDecimalPlaces
191
+ - minDecimalPlaces
192
+ - isRequired
193
+ - emptyAsNull
194
+ - defaultValue
195
+ - badTypeMessage
170
196
 
171
- - **invalidPropertyMessage:** - Custom message for invalid properties.
172
- - **strictMode:** - When `true`, ensures the object has exactly the same properties as defined.
173
- - **ignoreCase:** - When `true`, makes the property names case-insensitive.
174
- - **takeAllValues:** - When `true`, allows taking all values from the input object, not just those defined in the properties.
197
+ Comportamiento clave:
175
198
 
176
- #### Example
177
- ```typescript
178
- const objectVal = new V.Object({
179
- properties: {
180
- name: new V.String({ minLength: 3 }),
181
- age: new V.Number({ min: 18, max: 99 }),
182
- },
183
- strictMode: true,
184
- ignoreCase: true,
185
- invalidPropertyMessage: {
186
- message: () => "no es una propiedad valida",
187
- val: undefined
188
- }
189
- });
199
+ - Convierte el valor usando Number(data).
200
+ - Rechaza string vacio y NaN.
190
201
 
191
- const notNullObjectVal = new V.ObjectNotNull({
192
- properties: {
193
- name: new V.StringNotNull({ minLength: 3 }),
194
- age: new V.NumberNotNull({ min: 18, max: 99 }),
195
- },
196
- strictMode: true,
197
- ignoreCase: true,
198
- invalidPropertyMessage: {
199
- message: () => "no es una propiedad valida",
200
- val: undefined
201
- }
202
- });
202
+ Ejemplo:
203
203
 
204
- try {
205
- console.log(objectVal.check({ name: 'John', age: 25 })); // Output: { name: 'John', age: 25 }
206
- console.log(objectVal.check(null)); // Output: null
207
- console.log(notNullObjectVal.check({ name: 'Jane', age: 30 })); // Output: { name: 'Jane', age: 30 }
208
- } catch (error) {
209
- console.error(error);
210
- }
204
+ ```ts
205
+ const priceV = V.NumberNotNull().min(0).maxDecimalPlaces(2);
206
+ const price = priceV.check("25.99");
211
207
  ```
212
- ***
213
- ### Arrays
214
- Validations for array data.
215
208
 
216
- ```typescript
217
- const arrayVal = new V.Array({verifier: new V.Number()}); // Returns Array | null
218
- const notNullArrayVal = new V.ArrayNotNull({verifier: new V.Number()}); // Returns Array
219
- ```
209
+ ### String y StringNotNull
220
210
 
221
- Array Exclusive Conditions
211
+ Retorno:
222
212
 
223
- - **minLength**: Minimum length of the array.
224
- - **maxLength**: Maximum length of the array.
213
+ - VString: string | null
214
+ - VStringNotNull: string
225
215
 
226
- #### Example
227
- ```typescript
228
- const arrayVal = new V.Array({ verifier: new V.Number(), minLength: 1, maxLength: 5 });
229
- const notNullArrayVal = new V.ArrayNotNull({ verifier: new V.Number(), minLength: 2 });
216
+ Condiciones:
230
217
 
231
- try {
232
- console.log(arrayVal.check([1, 2, 3])); // Output: [1, 2, 3]
233
- console.log(arrayVal.check([])); // Throws VerificationError (array too short)
234
- console.log(arrayVal.check(null)); // Output: null
235
- console.log(notNullArrayVal.check([1, 2])); // Output: [1, 2]
236
- console.log(notNullArrayVal.check([1])); // Throws VerificationError (array too short)
237
- } catch (error) {
238
- console.error(error);
239
- }
240
- ```
241
- ***
242
- ### Any
243
- Validations for any data.
218
+ - minLength
219
+ - maxLength
220
+ - regex
221
+ - notRegex
222
+ - in
223
+ - notIn
224
+ - strictMode
225
+ - ignoreCase
226
+ - isRequired
227
+ - emptyAsNull
228
+ - defaultValue
229
+ - badTypeMessage
244
230
 
245
- ```typescript
246
- const anyVal = new V.Any(); // Returns any type
247
- ```
231
+ Comportamiento clave:
248
232
 
249
- VAny Exclusive Conditions
233
+ - En modo normal convierte con String(data).
234
+ - En strictMode exige string real.
235
+ - ignoreCase afecta in y notIn.
250
236
 
251
- *No exclusive conditions for any validation*
237
+ Ejemplo:
252
238
 
253
- #### Example
254
- ```typescript
255
- const anyVal = new V.Any();
239
+ ```ts
240
+ const roleV = V.StringNotNull()
241
+ .ignoreCase()
242
+ .in(["admin", "user", "guest"])
243
+ .trim()
244
+ .toLowerCase();
256
245
 
257
- try {
258
- console.log(anyVal.check('true')); // Output: 'true'
259
- console.log(anyVal.check('FALSE')); // Output: 'FALSE'
260
- console.log(anyVal.check(null)); // Output: null
261
- console.log(anyVal.check('1')); // Output: '1'
262
- console.log(anyVal.check(0)); // Output: 0
263
- } catch (error) {
264
- console.error(error);
265
- }
246
+ const role = roleV.check(" ADMIN ");
266
247
  ```
267
- ***
268
- ### Date
269
- Validations for date data (depends Moment).
270
248
 
271
- ```typescript
272
- const vdate = new V.Date();
273
- const vdateNotNull = new V.DateNotNull();
274
- ```
249
+ ### Boolean y BooleanNotNull
275
250
 
276
- VDate Exclusive Conditions
251
+ Retorno:
277
252
 
278
- - **format**: Specifies the date format to be validated against.
279
- - **timeZone**: Specifies the expected time zone of the input date.
280
- - **maxDate**: Specifies the maximum allowed date.
281
- - **minDate**: Specifies the minimum allowed date.
253
+ - VBoolean: boolean | null
254
+ - VBooleanNotNull: boolean
282
255
 
283
- #### Example
284
- #### Basic Date Validation
256
+ Condiciones:
285
257
 
286
- ```typescript
287
- const vdate = new V.Date();
288
- console.log(vdate.check("2023-08-09")?.format("YYYY-MM-DD")); // Output: "2023-08-09"
289
- ```
258
+ - strictMode
259
+ - isRequired
260
+ - emptyAsNull
261
+ - defaultValue
262
+ - badTypeMessage
290
263
 
291
- #### Date with Specific Format
264
+ Comportamiento clave:
292
265
 
293
- ```typescript
294
- const vdate = new V.Date({ format: "DD/MM/YYYY" });
295
- console.log(vdate.check("09/08/2023")?.format("DD/MM/YYYY")); // Output: "09/08/2023"
296
- ```
266
+ - En modo normal acepta: true, false, 1, 0, "1", "0", "true", "false".
267
+ - En strictMode solo acepta boolean.
297
268
 
298
- #### Date with Time Zone
269
+ Ejemplo:
299
270
 
300
- ```typescript
301
- const vdate = new V.Date({ timeZone: "America/New_York" });
302
- const result = vdate.check("2023-08-09T10:00:00");
303
- console.log(result.tz("America/New_York").format()); // Output: "2023-08-09T10:00:00-04:00"
271
+ ```ts
272
+ const active = V.BooleanNotNull().check("true");
273
+ const strictActive = V.BooleanNotNull().strictMode().check(true);
304
274
  ```
305
275
 
306
- #### Date within Range
276
+ ### UUID y UUIDNotNull
307
277
 
308
- ```typescript
309
- const vdate = new VDate({
310
- minDate: moment("2023-01-01"),
311
- maxDate: moment("2023-12-31")
312
- });
313
- console.log(vdate.check("2023-08-09").format("YYYY-MM-DD")); // Output: "2023-08-09"
314
- ```
278
+ Retorno:
279
+
280
+ - VUUID: string | null
281
+ - VUUIDNotNull: string
282
+
283
+ Condiciones:
284
+
285
+ - version (1 | 2 | 3 | 4 | 5)
286
+ - allowNoHyphens
287
+ - strictMode
288
+ - isRequired
289
+ - emptyAsNull
290
+ - defaultValue
291
+ - badTypeMessage
315
292
 
316
- ***
317
- ### UUID
318
- Validations for UUID (Universally Unique Identifier) data.
293
+ Comportamiento clave:
319
294
 
320
- ```typescript
321
- const uuidVal = new V.UUID(); // Returns string | null
322
- const notNullUuidVal = new V.UUIDNotNull(); // Returns string
295
+ - Normaliza salida a minusculas y formato con guiones.
296
+ - Si allowNoHyphens no esta activo, exige formato 8-4-4-4-12.
297
+
298
+ Ejemplo:
299
+
300
+ ```ts
301
+ const uuidV = V.UUIDNotNull().version(4);
302
+ const id = uuidV.check("550E8400E29B41D4A716446655440000");
323
303
  ```
324
304
 
325
- UUID Exclusive Conditions
305
+ ### Date y DateNotNull
306
+
307
+ Retorno:
308
+
309
+ - VDate: datetime.Dayjs | null
310
+ - VDateNotNull: datetime.Dayjs
326
311
 
327
- - **version**: Specifies the UUID version to validate against (1, 2, 3, 4, or 5). If not specified, accepts any version.
328
- - **allowNoHyphens**: When `true`, allows UUIDs without hyphens. Default is `false`.
329
- - **strictMode**: When `true`, ensures the input value is strictly a string (not coerced from another type).
312
+ Condiciones:
330
313
 
331
- #### Example
314
+ - format
315
+ - timeZone
316
+ - maxDate
317
+ - minDate
318
+ - isRequired
319
+ - emptyAsNull
320
+ - defaultValue
321
+ - badTypeMessage
332
322
 
333
- #### Basic UUID Validation
323
+ Comportamiento clave:
334
324
 
335
- ```typescript
336
- const uuidVal = new V.UUID();
337
- console.log(uuidVal.check("550e8400-e29b-41d4-a716-446655440000")); // Output: "550e8400-e29b-41d4-a716-446655440000"
338
- console.log(uuidVal.check(null)); // Output: null
325
+ - Entradas soportadas: number, string, Date y datetime.Dayjs.
326
+ - Si no defines timeZone usa UTC por defecto.
327
+ - Si format no incluye zona horaria, se aplica la zona configurada.
328
+
329
+ Ejemplo:
330
+
331
+ ```ts
332
+ import { Verifiers as V, datetime } from "structure-verifier";
333
+
334
+ const dateV = V.DateNotNull()
335
+ .format("YYYY-MM-DD")
336
+ .timeZone("America/Mexico_City")
337
+ .minDate(datetime("2024-01-01"));
338
+
339
+ const d = dateV.check("2025-05-10");
339
340
  ```
340
341
 
341
- #### UUID with Specific Version
342
+ ### Array y ArrayNotNull
342
343
 
343
- ```typescript
344
- const uuidV4Val = new V.UUID({ version: 4 });
345
- console.log(uuidV4Val.check("550e8400-e29b-41d4-a716-446655440000")); // Output: "550e8400-e29b-41d4-a716-446655440000"
344
+ Firma:
345
+
346
+ ```ts
347
+ const tagsV = V.Array(V.StringNotNull(), { minLength: 1 });
348
+ const tagsRequiredV = V.ArrayNotNull(V.StringNotNull(), { minLength: 1 });
346
349
  ```
347
350
 
348
- #### UUID without Hyphens
351
+ Retorno:
352
+
353
+ - VArray: ReturnType<T["check"]>[] | null
354
+ - VArrayNotNull: ReturnType<T["check"]>[]
355
+
356
+ Condiciones:
349
357
 
350
- ```typescript
351
- const uuidNoHyphensVal = new V.UUID({ allowNoHyphens: true });
352
- console.log(uuidNoHyphensVal.check("550e8400e29b41d4a716446655440000")); // Output: "550e8400-e29b-41d4-a716-446655440000"
358
+ - minLength
359
+ - maxLength
360
+ - isRequired
361
+ - emptyAsNull
362
+ - defaultValue
363
+ - badTypeMessage
364
+
365
+ Comportamiento clave:
366
+
367
+ - Valida item por item con el verificador interno.
368
+ - En errores anidados agrega rutas como [0], [1].name.
369
+
370
+ ### Object y ObjectNotNull
371
+
372
+ Firma:
373
+
374
+ ```ts
375
+ const userV = V.Object(
376
+ {
377
+ name: V.StringNotNull(),
378
+ age: V.Number(),
379
+ },
380
+ {
381
+ strictMode: true,
382
+ ignoreCase: false,
383
+ takeAllValues: false,
384
+ },
385
+ );
353
386
  ```
354
387
 
355
- #### Strict Mode UUID
388
+ Retorno:
356
389
 
357
- ```typescript
358
- const strictUuidVal = new V.UUIDNotNull({ strictMode: true });
359
- try {
360
- console.log(strictUuidVal.check("550e8400-e29b-41d4-a716-446655440000")); // Output: "550e8400-e29b-41d4-a716-446655440000"
361
- console.log(strictUuidVal.check(123)); // Throws VerificationError
362
- } catch (error) {
363
- console.error(error);
364
- }
390
+ - VObject: objeto tipado | null
391
+ - VObjectNotNull: objeto tipado
392
+
393
+ Condiciones:
394
+
395
+ - invalidPropertyMessage
396
+ - strictMode
397
+ - ignoreCase
398
+ - takeAllValues
399
+ - conds
400
+ - isRequired
401
+ - emptyAsNull
402
+ - defaultValue
403
+ - badTypeMessage
404
+
405
+ Comportamiento clave:
406
+
407
+ - strictMode rechaza propiedades no declaradas.
408
+ - ignoreCase permite mapear llaves sin distinguir mayusculas.
409
+ - takeAllValues conserva propiedades extra en la salida.
410
+ - conds ejecuta una validacion final con el objeto ya validado.
411
+
412
+ ### Any
413
+
414
+ Retorno:
415
+
416
+ - VAny: any | null
417
+
418
+ Condiciones:
419
+
420
+ - isRequired
421
+ - emptyAsNull
422
+ - defaultValue
423
+ - badTypeMessage
424
+
425
+ ## Transformaciones de valores
426
+
427
+ La clase base Verifier incluye transform(mapper), que permite postprocesar la salida validada sin perder la validacion previa.
428
+
429
+ String y StringNotNull incluyen helpers listos:
430
+
431
+ - trim
432
+ - trimStart
433
+ - trimEnd
434
+ - toLowerCase
435
+ - toUpperCase
436
+ - removeAccents
437
+ - padStart
438
+ - padEnd
439
+
440
+ Ejemplo:
441
+
442
+ ```ts
443
+ const usernameV = V.StringNotNull({ minLength: 3 })
444
+ .trim()
445
+ .toLowerCase()
446
+ .removeAccents();
365
447
  ```
366
448
 
367
- ***
368
- ## VerificationError
449
+ ## Tipado inferido
369
450
 
370
- The `VerificationError` class extends the native JavaScript `Error` object to provide enhanced error handling for validation scenarios. This class is designed to collect and format multiple error messages, making it easier to understand and manage errors in your application.
451
+ ### InferType
371
452
 
372
- ### Import
453
+ ```ts
454
+ import { InferType, Verifiers as V } from "structure-verifier";
373
455
 
374
- To use the `VerificationError` class, import it as follows:
456
+ const schema = V.ObjectNotNull({
457
+ id: V.UUIDNotNull(),
458
+ profile: V.ObjectNotNull({
459
+ name: V.StringNotNull(),
460
+ age: V.Number(),
461
+ }),
462
+ });
375
463
 
376
- ```typescript
377
- import { VerificationError } from "./path/to/your/VerificationError";
464
+ type User = InferType<typeof schema>;
378
465
  ```
379
466
 
380
- ### Constructor
467
+ ### InferFactoryType
468
+
469
+ ```ts
470
+ import { InferFactoryType, Verifiers as V } from "structure-verifier";
471
+
472
+ type NumberMaybe = InferFactoryType<typeof V.Number>;
473
+ type NumberRequired = InferFactoryType<typeof V.NumberNotNull>;
474
+ ```
475
+
476
+ ## Manejo de errores
477
+
478
+ Cuando una validacion falla se lanza VerificationError.
381
479
 
382
- #### `constructor(messages: messageResp[])`
480
+ Propiedades principales:
383
481
 
384
- The constructor takes an array of `messageResp` objects as an argument. Each `messageResp` object represents an individual validation error and has the following structure:
482
+ - message: todos los errores concatenados por punto y coma.
483
+ - errors: arreglo de mensajes planos.
484
+ - errorsObj: arreglo de objetos con key, message y metadatos.
385
485
 
386
- ```typescript
387
- interface messageResp {
388
- key: string;
389
- message: string;
390
- parent?: string;
486
+ Ejemplo:
487
+
488
+ ```ts
489
+ try {
490
+ V.ObjectNotNull({
491
+ name: V.StringNotNull({ minLength: 3 }),
492
+ tags: V.ArrayNotNull(V.StringNotNull(), { minLength: 1 }),
493
+ }).check({ name: "Al", tags: [] });
494
+ } catch (error) {
495
+ if (error instanceof VerificationError) {
496
+ console.log(error.errors);
497
+ console.log(error.errorsObj);
498
+ }
391
499
  }
392
500
  ```
393
501
 
394
- The constructor will generate a formatted error message by concatenating each `messageResp` into a single string, separating them by a semicolon (`;`). Additionally, it stores the original errors in two formats:
502
+ ## datetime (dayjs)
503
+
504
+ La libreria exporta dayjs como datetime con plugins activados:
395
505
 
396
- - **`_errors`**: An array of strings, where each string is a formatted error message.
397
- - **`_errorsObj`**: An array of `messageResp` objects.
506
+ - utc
507
+ - timezone
508
+ - customParseFormat
398
509
 
399
- ### Properties
510
+ Ejemplo:
400
511
 
401
- #### `errors: string[]`
512
+ ```ts
513
+ import { datetime } from "structure-verifier";
402
514
 
403
- This getter returns the array of formatted error messages. Each message is generated based on the `parent`, `key`, and `message` properties of the `messageResp` objects.
515
+ const now = datetime();
516
+ const utc = now.tz("UTC").format();
517
+ console.log(utc);
518
+ ```
519
+
520
+ ## Ejemplos avanzados
521
+
522
+ ### Validacion de payload API
523
+
524
+ ```ts
525
+ const createOrderV = V.ObjectNotNull(
526
+ {
527
+ customerId: V.UUIDNotNull({ version: 4 }),
528
+ items: V.ArrayNotNull(
529
+ V.ObjectNotNull({
530
+ sku: V.StringNotNull({ minLength: 1 }),
531
+ quantity: V.NumberNotNull({ min: 1 }),
532
+ }),
533
+ { minLength: 1 },
534
+ ),
535
+ createdAt: V.DateNotNull().timeZone("UTC"),
536
+ },
537
+ {
538
+ strictMode: true,
539
+ },
540
+ );
541
+ ```
404
542
 
405
- #### `errorsObj: messageResp[]`
543
+ ### conds para reglas de negocio
544
+
545
+ ```ts
546
+ const personV = V.ObjectNotNull(
547
+ {
548
+ age: V.NumberNotNull({ min: 0 }),
549
+ hasParentalConsent: V.Boolean(),
550
+ },
551
+ {
552
+ conds: (value) => {
553
+ if (value.age < 18 && value.hasParentalConsent !== true) {
554
+ throw new Error("Parental consent is required for minors");
555
+ }
556
+ },
557
+ },
558
+ );
559
+ ```
406
560
 
407
- This getter returns the original array of `messageResp` objects, allowing access to the detailed structure of each validation error.
561
+ ## Scripts de desarrollo
408
562
 
409
- ### Usage Example
563
+ ```bash
564
+ npm test
565
+ npm run dev
566
+ ```
410
567
 
411
- ```typescript
412
- import { VerificationError } from "../src/error/v_error";
568
+ ## Licencia
413
569
 
414
- try {
415
- throw new VerificationError([{ key: "email", message: "is invalid", parent: "contact" }]);
416
- } catch (err) {
417
- if (err instanceof VerificationError) {
418
- console.log(err.errors); // [ 'contact.email is invalid' ]
419
- console.log(err.errorsObj); // Original messageResp objects
420
- }
421
- }
422
- ```
570
+ ISC