@oxog/vld 2.1.0 → 2.2.7

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 (228) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/README.md +413 -1235
  3. package/dist/chunks/errors-core-CerMg2rq.js +1 -0
  4. package/dist/chunks/index-CkbfQQ4n.js +1 -0
  5. package/dist/chunks/index-yjpbvFgw.js +1 -0
  6. package/dist/chunks/ip-validation-g5LWgy9t.js +1 -0
  7. package/dist/chunks/security-Dy24T8N7.js +1 -0
  8. package/dist/cjs/chunks/errors-core-DrydF46s.cjs +1 -0
  9. package/dist/cjs/chunks/index-BEV9nG0N.cjs +1 -0
  10. package/dist/cjs/chunks/index-ZjHAxYdA.cjs +1 -0
  11. package/dist/cjs/chunks/ip-validation-BZqPamPC.cjs +1 -0
  12. package/dist/cjs/chunks/security-aXZVI7qW.cjs +1 -0
  13. package/dist/cjs/cli/bin.cjs +1 -505
  14. package/dist/cjs/cli/index.cjs +1 -209
  15. package/dist/cjs/codecs/index.cjs +1 -45
  16. package/dist/cjs/coercion/index.cjs +1 -588
  17. package/dist/cjs/compat/emitter.cjs +1 -184
  18. package/dist/cjs/compat/result.cjs +1 -189
  19. package/dist/cjs/errors.cjs +1 -180
  20. package/dist/cjs/index.cjs +1 -1894
  21. package/dist/cjs/kernel.cjs +1 -415
  22. package/dist/cjs/locales/af.cjs +1 -108
  23. package/dist/cjs/locales/ar.cjs +1 -108
  24. package/dist/cjs/locales/bn.cjs +1 -108
  25. package/dist/cjs/locales/da.cjs +1 -108
  26. package/dist/cjs/locales/de.cjs +1 -108
  27. package/dist/cjs/locales/en.cjs +1 -108
  28. package/dist/cjs/locales/es-MX.cjs +1 -107
  29. package/dist/cjs/locales/es.cjs +1 -96
  30. package/dist/cjs/locales/fi.cjs +1 -108
  31. package/dist/cjs/locales/fr.cjs +1 -96
  32. package/dist/cjs/locales/hi.cjs +1 -108
  33. package/dist/cjs/locales/id.cjs +1 -108
  34. package/dist/cjs/locales/index.cjs +1 -43
  35. package/dist/cjs/locales/it.cjs +1 -108
  36. package/dist/cjs/locales/ja.cjs +1 -108
  37. package/dist/cjs/locales/ko.cjs +1 -108
  38. package/dist/cjs/locales/lazy.cjs +1 -188
  39. package/dist/cjs/locales/nl.cjs +1 -108
  40. package/dist/cjs/locales/no.cjs +1 -108
  41. package/dist/cjs/locales/pl.cjs +1 -108
  42. package/dist/cjs/locales/pt-BR.cjs +1 -108
  43. package/dist/cjs/locales/pt.cjs +1 -108
  44. package/dist/cjs/locales/ru.cjs +1 -108
  45. package/dist/cjs/locales/runtime.cjs +1 -51
  46. package/dist/cjs/locales/sv.cjs +1 -108
  47. package/dist/cjs/locales/sw.cjs +1 -108
  48. package/dist/cjs/locales/th.cjs +1 -108
  49. package/dist/cjs/locales/tr.cjs +1 -108
  50. package/dist/cjs/locales/vi.cjs +1 -108
  51. package/dist/cjs/locales/zh.cjs +1 -108
  52. package/dist/cjs/mini.cjs +1 -242
  53. package/dist/cjs/pigment.cjs +1 -207
  54. package/dist/cjs/plugins/index.cjs +1 -12
  55. package/dist/cjs/registry.cjs +1 -37
  56. package/dist/cjs/v3/index.cjs +1 -425
  57. package/dist/cjs/v4/core/index.cjs +1 -894
  58. package/dist/cjs/v4/index.cjs +1 -425
  59. package/dist/cjs/v4/locales/index.cjs +1 -130
  60. package/dist/cjs/v4/mini/index.cjs +1 -509
  61. package/dist/cjs/v4-mini/index.cjs +1 -532
  62. package/dist/cjs/validators/any.cjs +1 -40
  63. package/dist/cjs/validators/array.cjs +1 -283
  64. package/dist/cjs/validators/base.cjs +1 -887
  65. package/dist/cjs/validators/base64.cjs +1 -73
  66. package/dist/cjs/validators/bigint.cjs +1 -232
  67. package/dist/cjs/validators/boolean.cjs +1 -146
  68. package/dist/cjs/validators/codec.cjs +1 -205
  69. package/dist/cjs/validators/custom.cjs +1 -71
  70. package/dist/cjs/validators/date.cjs +1 -278
  71. package/dist/cjs/validators/discriminated-union.cjs +1 -130
  72. package/dist/cjs/validators/enum.cjs +1 -154
  73. package/dist/cjs/validators/file.cjs +1 -130
  74. package/dist/cjs/validators/function.cjs +1 -63
  75. package/dist/cjs/validators/hex.cjs +1 -70
  76. package/dist/cjs/validators/index.cjs +1 -123
  77. package/dist/cjs/validators/intersection.cjs +1 -120
  78. package/dist/cjs/validators/json.cjs +1 -70
  79. package/dist/cjs/validators/lazy.cjs +1 -53
  80. package/dist/cjs/validators/literal.cjs +1 -64
  81. package/dist/cjs/validators/map.cjs +1 -218
  82. package/dist/cjs/validators/nan.cjs +1 -41
  83. package/dist/cjs/validators/never.cjs +1 -36
  84. package/dist/cjs/validators/null.cjs +1 -43
  85. package/dist/cjs/validators/number.cjs +1 -427
  86. package/dist/cjs/validators/object.cjs +1 -868
  87. package/dist/cjs/validators/promise.cjs +1 -115
  88. package/dist/cjs/validators/record.cjs +1 -262
  89. package/dist/cjs/validators/set.cjs +1 -203
  90. package/dist/cjs/validators/string-bool.cjs +1 -124
  91. package/dist/cjs/validators/string-formats.cjs +1 -168
  92. package/dist/cjs/validators/string.cjs +1 -12
  93. package/dist/cjs/validators/symbol.cjs +1 -62
  94. package/dist/cjs/validators/template-literal.cjs +1 -108
  95. package/dist/cjs/validators/tuple.cjs +1 -187
  96. package/dist/cjs/validators/uint8array.cjs +1 -106
  97. package/dist/cjs/validators/undefined.cjs +1 -43
  98. package/dist/cjs/validators/union.cjs +1 -191
  99. package/dist/cjs/validators/unknown.cjs +1 -40
  100. package/dist/cjs/validators/void.cjs +1 -48
  101. package/dist/cjs/validators/xor.cjs +1 -69
  102. package/dist/cli/bin.js +1 -406
  103. package/dist/cli/index.js +1 -205
  104. package/dist/codecs/index.js +1 -11
  105. package/dist/coercion/index.js +1 -579
  106. package/dist/compat/emitter.js +1 -180
  107. package/dist/compat/result.js +1 -170
  108. package/dist/errors-core.d.ts +32 -2
  109. package/dist/errors.js +1 -171
  110. package/dist/index.d.ts +315 -361
  111. package/dist/index.js +1 -1534
  112. package/dist/kernel.js +1 -409
  113. package/dist/locales/af.js +1 -106
  114. package/dist/locales/ar.js +1 -106
  115. package/dist/locales/bn.js +1 -106
  116. package/dist/locales/da.js +1 -106
  117. package/dist/locales/de.js +1 -106
  118. package/dist/locales/en.js +1 -106
  119. package/dist/locales/es-MX.js +1 -105
  120. package/dist/locales/es.js +1 -94
  121. package/dist/locales/fi.js +1 -106
  122. package/dist/locales/fr.js +1 -94
  123. package/dist/locales/hi.js +1 -106
  124. package/dist/locales/id.js +1 -106
  125. package/dist/locales/index.js +1 -29
  126. package/dist/locales/it.js +1 -106
  127. package/dist/locales/ja.js +1 -106
  128. package/dist/locales/ko.js +1 -106
  129. package/dist/locales/lazy.js +1 -177
  130. package/dist/locales/nl.js +1 -106
  131. package/dist/locales/no.js +1 -106
  132. package/dist/locales/pl.js +1 -106
  133. package/dist/locales/pt-BR.js +1 -106
  134. package/dist/locales/pt.js +1 -106
  135. package/dist/locales/ru.js +1 -106
  136. package/dist/locales/runtime.js +1 -41
  137. package/dist/locales/sv.js +1 -106
  138. package/dist/locales/sw.js +1 -106
  139. package/dist/locales/th.js +1 -106
  140. package/dist/locales/tr.js +1 -106
  141. package/dist/locales/vi.js +1 -106
  142. package/dist/locales/zh.js +1 -106
  143. package/dist/mini.d.ts +3 -3
  144. package/dist/mini.js +1 -156
  145. package/dist/pigment.js +1 -180
  146. package/dist/plugins/index.js +1 -1
  147. package/dist/registry.js +1 -34
  148. package/dist/utils/json-schema.d.ts +10 -1
  149. package/dist/v3/index.js +1 -46
  150. package/dist/v4/core/index.d.ts +28 -16
  151. package/dist/v4/core/index.js +1 -277
  152. package/dist/v4/index.js +1 -50
  153. package/dist/v4/locales/index.d.ts +4 -0
  154. package/dist/v4/locales/index.js +1 -77
  155. package/dist/v4/mini/index.js +1 -47
  156. package/dist/v4-mini/index.d.ts +1 -1
  157. package/dist/v4-mini/index.js +1 -75
  158. package/dist/validators/any.js +1 -37
  159. package/dist/validators/array.d.ts +7 -0
  160. package/dist/validators/array.js +1 -279
  161. package/dist/validators/base.d.ts +210 -17
  162. package/dist/validators/base.js +1 -868
  163. package/dist/validators/base64.js +1 -68
  164. package/dist/validators/bigint.d.ts +7 -0
  165. package/dist/validators/bigint.js +1 -228
  166. package/dist/validators/boolean.js +1 -142
  167. package/dist/validators/codec.js +1 -200
  168. package/dist/validators/custom.d.ts +20 -10
  169. package/dist/validators/custom.js +1 -67
  170. package/dist/validators/date.d.ts +2 -0
  171. package/dist/validators/date.js +1 -274
  172. package/dist/validators/discriminated-union.d.ts +4 -2
  173. package/dist/validators/discriminated-union.js +1 -123
  174. package/dist/validators/enum.d.ts +8 -2
  175. package/dist/validators/enum.js +1 -150
  176. package/dist/validators/file.js +1 -125
  177. package/dist/validators/function.js +1 -58
  178. package/dist/validators/hex.js +1 -65
  179. package/dist/validators/index.d.ts +1 -1
  180. package/dist/validators/index.js +1 -35
  181. package/dist/validators/intersection.js +1 -116
  182. package/dist/validators/json.js +1 -66
  183. package/dist/validators/lazy.js +1 -50
  184. package/dist/validators/literal.d.ts +8 -3
  185. package/dist/validators/literal.js +1 -60
  186. package/dist/validators/map.d.ts +7 -0
  187. package/dist/validators/map.js +1 -214
  188. package/dist/validators/nan.js +1 -38
  189. package/dist/validators/never.js +1 -32
  190. package/dist/validators/null.js +1 -40
  191. package/dist/validators/number.d.ts +25 -1
  192. package/dist/validators/number.js +1 -423
  193. package/dist/validators/object.d.ts +18 -2
  194. package/dist/validators/object.js +1 -864
  195. package/dist/validators/promise.d.ts +6 -7
  196. package/dist/validators/promise.js +1 -111
  197. package/dist/validators/record.d.ts +13 -8
  198. package/dist/validators/record.js +1 -258
  199. package/dist/validators/set.d.ts +5 -0
  200. package/dist/validators/set.js +1 -199
  201. package/dist/validators/string-bool.js +1 -120
  202. package/dist/validators/string-formats.d.ts +58 -62
  203. package/dist/validators/string-formats.js +1 -135
  204. package/dist/validators/string.d.ts +49 -10
  205. package/dist/validators/string.js +1 -4
  206. package/dist/validators/symbol.js +1 -58
  207. package/dist/validators/template-literal.js +1 -103
  208. package/dist/validators/tuple.d.ts +17 -13
  209. package/dist/validators/tuple.js +1 -183
  210. package/dist/validators/uint8array.js +1 -101
  211. package/dist/validators/undefined.js +1 -40
  212. package/dist/validators/union.d.ts +1 -0
  213. package/dist/validators/union.js +1 -187
  214. package/dist/validators/unknown.js +1 -37
  215. package/dist/validators/void.js +1 -44
  216. package/dist/validators/xor.d.ts +2 -2
  217. package/dist/validators/xor.js +1 -66
  218. package/package.json +240 -238
  219. package/dist/chunks/errors-core-BeiFUtZM.js +0 -81
  220. package/dist/chunks/index-0R2ntSud.js +0 -508
  221. package/dist/chunks/index-BvH403Yy.js +0 -88
  222. package/dist/chunks/security-B0Pd_vSY.js +0 -35
  223. package/dist/chunks/string-BJRQod3t.js +0 -530
  224. package/dist/cjs/chunks/errors-core-DWxLFs2f.cjs +0 -83
  225. package/dist/cjs/chunks/index-BkI37108.cjs +0 -538
  226. package/dist/cjs/chunks/index-Cc3bjUMX.cjs +0 -91
  227. package/dist/cjs/chunks/security-Dc3Jh13T.cjs +0 -37
  228. package/dist/cjs/chunks/string-BKZrc4hs.cjs +0 -533
@@ -1,4 +1,4 @@
1
- import { VldBase, ParseResult } from './base.js';
1
+ import { VldBase, ParseResult, type ErrorParam } from './base.js';
2
2
  /**
3
3
  * Type-safe custom validator options
4
4
  */
@@ -16,12 +16,24 @@ export interface CustomValidatorOptions<TOutput> {
16
16
  * Optional safeParse implementation
17
17
  * If not provided, will use try-catch around parse()
18
18
  */
19
- safeParse?: (value: unknown) => ParseResult<TOutput>;
19
+ safeParse?: (value: unknown) => ParseResult<TOutput> | {
20
+ success: true;
21
+ data: TOutput;
22
+ } | {
23
+ success: false;
24
+ error: Error;
25
+ };
20
26
  /**
21
27
  * Optional async safeParse implementation
22
28
  * If not provided, will use try-catch around parseAsync()
23
29
  */
24
- safeParseAsync?: (value: unknown) => Promise<ParseResult<TOutput>>;
30
+ safeParseAsync?: (value: unknown) => Promise<ParseResult<TOutput> | {
31
+ success: true;
32
+ data: TOutput;
33
+ } | {
34
+ success: false;
35
+ error: Error;
36
+ }>;
25
37
  }
26
38
  /**
27
39
  * Immutable custom validator for user-defined validation logic
@@ -50,11 +62,9 @@ export declare class VldCustom<TOutput = unknown> extends VldBase<unknown, TOutp
50
62
  }
51
63
  /**
52
64
  * Helper function to create custom validators
53
- * Usage: v.custom<number>({
54
- * parse: (value) => {
55
- * if (typeof value !== 'string') throw new Error('Expected string');
56
- * return parseInt(value, 10);
57
- * }
58
- * })
65
+ * Supports:
66
+ * - v.custom() -> accepts any
67
+ * - v.custom((val) => boolean, "error message")
68
+ * - v.custom({ parse: (val) => ... })
59
69
  */
60
- export declare function custom<TOutput = unknown>(options: CustomValidatorOptions<TOutput>): VldCustom<TOutput>;
70
+ export declare function custom<TOutput = unknown>(optionsOrPredicate?: CustomValidatorOptions<TOutput> | ((data: unknown) => boolean | Promise<boolean>), errorParam?: ErrorParam): VldCustom<TOutput>;
@@ -1,67 +1 @@
1
- import { VldBase, VLD_VALIDATOR_TYPES } from './base.js';
2
-
3
- /**
4
- * Immutable custom validator for user-defined validation logic
5
- * Provides type safety while allowing complete control over validation
6
- */
7
- class VldCustom extends VldBase {
8
- constructor(options) {
9
- super(VLD_VALIDATOR_TYPES.CUSTOM);
10
- this._parseFn = options.parse;
11
- this._parseAsyncFn = options.parseAsync || ((value) => Promise.resolve(this._parseFn(value)));
12
- this._safeParseFn = options.safeParse || ((value) => {
13
- try {
14
- return { success: true, data: this._parseFn(value) };
15
- }
16
- catch (error) {
17
- return { success: false, error: error };
18
- }
19
- });
20
- this._safeParseAsyncFn = options.safeParseAsync || (async (value) => {
21
- try {
22
- return { success: true, data: await this._parseAsyncFn(value) };
23
- }
24
- catch (error) {
25
- return { success: false, error: error };
26
- }
27
- });
28
- }
29
- /**
30
- * Create a new custom validator
31
- */
32
- static create(options) {
33
- return new VldCustom(options);
34
- }
35
- /**
36
- * Parse and validate using the custom parse function
37
- */
38
- parse(value) {
39
- return this._parseFn(value);
40
- }
41
- /**
42
- * Safely parse using the custom safeParse function or default implementation
43
- */
44
- safeParse(value) {
45
- return this._safeParseFn(value);
46
- }
47
- async parseAsync(value) {
48
- return this._parseAsyncFn(value);
49
- }
50
- async safeParseAsync(value) {
51
- return this._safeParseAsyncFn(value);
52
- }
53
- }
54
- /**
55
- * Helper function to create custom validators
56
- * Usage: v.custom<number>({
57
- * parse: (value) => {
58
- * if (typeof value !== 'string') throw new Error('Expected string');
59
- * return parseInt(value, 10);
60
- * }
61
- * })
62
- */
63
- function custom(options) {
64
- return VldCustom.create(options);
65
- }
66
-
67
- export { VldCustom, custom };
1
+ import{ensureVldError as s,resolveErrorMessage as r,VldBase as e,VLD_VALIDATOR_TYPES as a}from"./base.js";class VldCustom extends e{constructor(r){super(a.CUSTOM),this._parseFn=r.parse,this._parseAsyncFn=r.parseAsync||(s=>Promise.resolve(this._parseFn(s))),this._safeParseFn=r.safeParse?e=>{const a=r.safeParse(e);return a.success?{success:!0,data:a.data}:{success:!1,error:s(a.error)}}:r=>{try{return{success:!0,data:this._parseFn(r)}}catch(r){return{success:!1,error:s(r)}}},this._safeParseAsyncFn=r.safeParseAsync?async e=>{const a=await r.safeParseAsync(e);return a.success?{success:!0,data:a.data}:{success:!1,error:s(a.error)}}:async r=>{try{return{success:!0,data:await this._parseAsyncFn(r)}}catch(r){return{success:!1,error:s(r)}}}}static create(s){return new VldCustom(s)}parse(s){return this._parseFn(s)}safeParse(s){return this._safeParseFn(s)}async parseAsync(s){return this._parseAsyncFn(s)}async safeParseAsync(s){return this._safeParseAsyncFn(s)}}function t(e,a){if("function"==typeof e){const t=e;return VldCustom.create({parse:e=>{if(!t(e))throw s(r(a,"Custom validation failed"));return e}})}return e?VldCustom.create(e):VldCustom.create({parse:s=>s})}export{VldCustom,t as custom};
@@ -34,6 +34,8 @@ export declare class VldDate extends VldBase<Date, Date> {
34
34
  */
35
35
  protected constructor(config?: Partial<DateValidatorConfig>);
36
36
  get jsonSchema(): DateJSONSchemaHints | undefined;
37
+ get minDate(): Date | null;
38
+ get maxDate(): Date | null;
37
39
  /**
38
40
  * Create a new date validator
39
41
  */
@@ -1,274 +1 @@
1
- import { VldBase, VLD_VALIDATOR_TYPES } from './base.js';
2
- import { getMessages } from '../locales/runtime.js';
3
- import { V as VldError } from '../chunks/errors-core-BeiFUtZM.js';
4
-
5
- function createDateError(message) {
6
- return new VldError([{ code: 'invalid_date', path: [], message }]);
7
- }
8
- /**
9
- * Immutable date validator with chainable methods
10
- */
11
- class VldDate extends VldBase {
12
- /**
13
- * Protected constructor to allow extension while maintaining immutability
14
- */
15
- constructor(config) {
16
- super(config?.validatorType || VLD_VALIDATOR_TYPES.DATE);
17
- this.config = {
18
- checks: config?.checks || [],
19
- errorMessage: config?.errorMessage,
20
- jsonSchema: config?.jsonSchema
21
- };
22
- this._checks = this.config.checks;
23
- this._isSimple = this._checks.length === 0;
24
- }
25
- get jsonSchema() {
26
- return this.config.jsonSchema;
27
- }
28
- /**
29
- * Create a new date validator
30
- */
31
- static create() {
32
- return new VldDate();
33
- }
34
- /**
35
- * Parse and validate a date value
36
- */
37
- parse(value) {
38
- let date;
39
- if (value instanceof Date) {
40
- date = value;
41
- }
42
- else if (typeof value === 'string' || typeof value === 'number') {
43
- date = new Date(value);
44
- }
45
- else {
46
- throw new Error(this.config.errorMessage || getMessages().invalidDate);
47
- }
48
- // Check if the date is valid
49
- if (isNaN(date.getTime())) {
50
- throw new Error(this.config.errorMessage || getMessages().invalidDate);
51
- }
52
- return this.parseValidDate(date);
53
- }
54
- /**
55
- * Parse a Date instance that has already passed the Date validity check.
56
- * @internal Used by object validators to avoid duplicate hot-path checks.
57
- */
58
- parseKnownDate(value) {
59
- if (isNaN(value.getTime())) {
60
- throw new Error(this.config.errorMessage || getMessages().invalidDate);
61
- }
62
- return this.parseValidDate(value);
63
- }
64
- parseValidDate(date) {
65
- if (this._isSimple) {
66
- return date;
67
- }
68
- // Apply all checks
69
- for (const check of this._checks) {
70
- if (!check.fn(date)) {
71
- throw new Error(check.message);
72
- }
73
- }
74
- return date;
75
- }
76
- /**
77
- * Safely parse and validate a date value
78
- */
79
- safeParse(value) {
80
- if (value instanceof Date) {
81
- try {
82
- return { success: true, data: this.parseKnownDate(value) };
83
- }
84
- catch (error) {
85
- return { success: false, error: createDateError(error.message) };
86
- }
87
- }
88
- try {
89
- return { success: true, data: this.parse(value) };
90
- }
91
- catch (error) {
92
- return { success: false, error: createDateError(error.message) };
93
- }
94
- }
95
- /**
96
- * Create a new validator with minimum date constraint
97
- * BUG-NEW-009 FIX: Validate that min date is valid before creating validator
98
- */
99
- min(date, message) {
100
- const minDate = date instanceof Date ? date : new Date(date);
101
- // Validate that minDate is valid
102
- if (isNaN(minDate.getTime())) {
103
- throw new Error(`Invalid date provided to min(): ${date}`);
104
- }
105
- return new VldDate({
106
- ...this.config,
107
- checks: [...this.config.checks, {
108
- fn: (v) => v >= minDate,
109
- message: message || getMessages().dateMin(minDate)
110
- }],
111
- jsonSchema: { ...this.config.jsonSchema, formatMinimum: minDate.toISOString() }
112
- });
113
- }
114
- /**
115
- * Create a new validator with maximum date constraint
116
- * BUG-NEW-009 FIX: Validate that max date is valid before creating validator
117
- */
118
- max(date, message) {
119
- const maxDate = date instanceof Date ? date : new Date(date);
120
- // Validate that maxDate is valid
121
- if (isNaN(maxDate.getTime())) {
122
- throw new Error(`Invalid date provided to max(): ${date}`);
123
- }
124
- return new VldDate({
125
- ...this.config,
126
- checks: [...this.config.checks, {
127
- fn: (v) => v <= maxDate,
128
- message: message || getMessages().dateMax(maxDate)
129
- }],
130
- jsonSchema: { ...this.config.jsonSchema, formatMaximum: maxDate.toISOString() }
131
- });
132
- }
133
- /**
134
- * Create a new validator with a range constraint
135
- * BUG-NEW-019 FIX: Validate that min/max dates are valid before creating validator
136
- */
137
- between(min, max, message) {
138
- const minDate = min instanceof Date ? min : new Date(min);
139
- const maxDate = max instanceof Date ? max : new Date(max);
140
- // Validate that both dates are valid
141
- if (isNaN(minDate.getTime())) {
142
- throw new Error(`Invalid min date provided to between(): ${min}`);
143
- }
144
- if (isNaN(maxDate.getTime())) {
145
- throw new Error(`Invalid max date provided to between(): ${max}`);
146
- }
147
- return new VldDate({
148
- ...this.config,
149
- checks: [...this.config.checks, {
150
- fn: (v) => v >= minDate && v <= maxDate,
151
- message: message || `Date must be between ${minDate.toISOString()} and ${maxDate.toISOString()}`
152
- }],
153
- jsonSchema: {
154
- ...this.config.jsonSchema,
155
- formatMinimum: minDate.toISOString(),
156
- formatMaximum: maxDate.toISOString()
157
- }
158
- });
159
- }
160
- /**
161
- * Create a new validator that checks if date is in the past
162
- * BUG-NEW-006 FIX: Capture reference date at validator creation time for deterministic behavior
163
- */
164
- past(message) {
165
- const referenceDate = new Date(); // Capture NOW at validator creation time
166
- return new VldDate({
167
- ...this.config,
168
- checks: [...this.config.checks, {
169
- fn: (v) => v < referenceDate,
170
- message: message || 'Date must be in the past'
171
- }],
172
- jsonSchema: { ...this.config.jsonSchema, formatExclusiveMaximum: referenceDate.toISOString() }
173
- });
174
- }
175
- /**
176
- * Create a new validator that checks if date is in the future
177
- * BUG-NEW-006 FIX: Capture reference date at validator creation time for deterministic behavior
178
- */
179
- future(message) {
180
- const referenceDate = new Date(); // Capture NOW at validator creation time
181
- return new VldDate({
182
- ...this.config,
183
- checks: [...this.config.checks, {
184
- fn: (v) => v > referenceDate,
185
- message: message || 'Date must be in the future'
186
- }],
187
- jsonSchema: { ...this.config.jsonSchema, formatExclusiveMinimum: referenceDate.toISOString() }
188
- });
189
- }
190
- /**
191
- * Create a new validator that checks if date is today
192
- * BUG-NEW-008 FIX: Capture reference date at validator creation time for deterministic behavior
193
- */
194
- today(message) {
195
- // Capture the reference date (today) at validator creation time
196
- const referenceDate = new Date();
197
- const refYear = referenceDate.getFullYear();
198
- const refMonth = referenceDate.getMonth();
199
- const refDate = referenceDate.getDate();
200
- return new VldDate({
201
- ...this.config,
202
- checks: [...this.config.checks, {
203
- fn: (v) => {
204
- return v.getFullYear() === refYear &&
205
- v.getMonth() === refMonth &&
206
- v.getDate() === refDate;
207
- },
208
- message: message || 'Date must be today'
209
- }]
210
- });
211
- }
212
- /**
213
- * Create a new validator that checks if date is a weekday
214
- */
215
- weekday(message) {
216
- return new VldDate({
217
- ...this.config,
218
- checks: [...this.config.checks, {
219
- fn: (v) => {
220
- const day = v.getDay();
221
- return day >= 1 && day <= 5;
222
- },
223
- message: message || 'Date must be a weekday'
224
- }]
225
- });
226
- }
227
- /**
228
- * Create a new validator that checks if date is a weekend
229
- */
230
- weekend(message) {
231
- return new VldDate({
232
- ...this.config,
233
- checks: [...this.config.checks, {
234
- fn: (v) => {
235
- const day = v.getDay();
236
- return day === 0 || day === 6;
237
- },
238
- message: message || 'Date must be a weekend'
239
- }]
240
- });
241
- }
242
- /**
243
- * Create a new validator with strict greater than constraint
244
- * Zod 4 API parity - strictly greater than (not equal to)
245
- */
246
- gt(value, message) {
247
- const compareDate = value instanceof Date ? value : new Date(value);
248
- return new VldDate({
249
- ...this.config,
250
- checks: [...this.config.checks, {
251
- fn: (v) => v.getTime() > compareDate.getTime(),
252
- message: message || `Date must be greater than ${compareDate.toISOString()}`
253
- }],
254
- jsonSchema: { ...this.config.jsonSchema, formatExclusiveMinimum: compareDate.toISOString() }
255
- });
256
- }
257
- /**
258
- * Create a new validator with strict less than constraint
259
- * Zod 4 API parity - strictly less than (not equal to)
260
- */
261
- lt(value, message) {
262
- const compareDate = value instanceof Date ? value : new Date(value);
263
- return new VldDate({
264
- ...this.config,
265
- checks: [...this.config.checks, {
266
- fn: (v) => v.getTime() < compareDate.getTime(),
267
- message: message || `Date must be less than ${compareDate.toISOString()}`
268
- }],
269
- jsonSchema: { ...this.config.jsonSchema, formatExclusiveMaximum: compareDate.toISOString() }
270
- });
271
- }
272
- }
273
-
274
- export { VldDate };
1
+ import{VldBase as e,VLD_VALIDATOR_TYPES as t}from"./base.js";import{getMessages as n}from"../locales/runtime.js";import{V as s}from"../chunks/errors-core-CerMg2rq.js";function i(e){return new s([{code:"invalid_date",path:[],message:e}])}class VldDate extends e{constructor(e){super(e?.validatorType||t.DATE),this.config={checks:e?.checks||[],errorMessage:e?.errorMessage,jsonSchema:e?.jsonSchema},this._checks=this.config.checks,this._isSimple=0===this._checks.length}get jsonSchema(){return this.config.jsonSchema}get minDate(){const e=this.config.jsonSchema?.formatMinimum??this.config.jsonSchema?.minimum;return e?new Date(e):null}get maxDate(){const e=this.config.jsonSchema?.formatMaximum??this.config.jsonSchema?.maximum;return e?new Date(e):null}static create(){return new VldDate}parse(e){let t;if(e instanceof Date)t=e;else{if("string"!=typeof e&&"number"!=typeof e)throw new Error(this.config.errorMessage||n().invalidDate);t=new Date(e)}if(isNaN(t.getTime()))throw new Error(this.config.errorMessage||n().invalidDate);return this.parseValidDate(t)}parseKnownDate(e){if(isNaN(e.getTime()))throw new Error(this.config.errorMessage||n().invalidDate);return this.parseValidDate(e)}parseValidDate(e){if(this._isSimple)return e;for(const t of this._checks)if(!t.fn(e))throw new Error(t.message);return e}safeParse(e){if(e instanceof Date)try{return{success:!0,data:this.parseKnownDate(e)}}catch(e){return{success:!1,error:i(e.message)}}try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:i(e.message)}}}min(e,t){const s=e instanceof Date?e:new Date(e);if(isNaN(s.getTime()))throw new Error(`Invalid date provided to min(): ${e}`);return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>e>=s,message:t||n().dateMin(s)}],jsonSchema:{...this.config.jsonSchema,formatMinimum:s.toISOString()}})}max(e,t){const s=e instanceof Date?e:new Date(e);if(isNaN(s.getTime()))throw new Error(`Invalid date provided to max(): ${e}`);return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>e<=s,message:t||n().dateMax(s)}],jsonSchema:{...this.config.jsonSchema,formatMaximum:s.toISOString()}})}between(e,t,n){const s=e instanceof Date?e:new Date(e),i=t instanceof Date?t:new Date(t);if(isNaN(s.getTime()))throw new Error(`Invalid min date provided to between(): ${e}`);if(isNaN(i.getTime()))throw new Error(`Invalid max date provided to between(): ${t}`);return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>e>=s&&e<=i,message:n||`Date must be between ${s.toISOString()} and ${i.toISOString()}`}],jsonSchema:{...this.config.jsonSchema,formatMinimum:s.toISOString(),formatMaximum:i.toISOString()}})}past(e){const t=new Date;return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>e<t,message:e||"Date must be in the past"}],jsonSchema:{...this.config.jsonSchema,formatExclusiveMaximum:t.toISOString()}})}future(e){const t=new Date;return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>e>t,message:e||"Date must be in the future"}],jsonSchema:{...this.config.jsonSchema,formatExclusiveMinimum:t.toISOString()}})}today(e){const t=new Date,n=t.getFullYear(),s=t.getMonth(),i=t.getDate();return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>e.getFullYear()===n&&e.getMonth()===s&&e.getDate()===i,message:e||"Date must be today"}]})}weekday(e){return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>{const t=e.getDay();return t>=1&&t<=5},message:e||"Date must be a weekday"}]})}weekend(e){return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>{const t=e.getDay();return 0===t||6===t},message:e||"Date must be a weekend"}]})}gt(e,t){const n=e instanceof Date?e:new Date(e);return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>e.getTime()>n.getTime(),message:t||`Date must be greater than ${n.toISOString()}`}],jsonSchema:{...this.config.jsonSchema,formatExclusiveMinimum:n.toISOString()}})}lt(e,t){const n=e instanceof Date?e:new Date(e);return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>e.getTime()<n.getTime(),message:t||`Date must be less than ${n.toISOString()}`}],jsonSchema:{...this.config.jsonSchema,formatExclusiveMaximum:n.toISOString()}})}}export{VldDate};
@@ -9,14 +9,16 @@ import type { ParseResult } from './base.js';
9
9
  * Discriminated union validator - validates union based on discriminator key
10
10
  * Much faster than regular union when you have a discriminator field
11
11
  */
12
- export declare class VldDiscriminatedUnion<K extends string, Options extends VldBase<any, any>[]> extends VldBase<unknown, Options[number] extends VldBase<any, infer T> ? T : never> {
12
+ export declare class VldDiscriminatedUnion<K extends string, Options extends readonly VldBase<any, any>[]> extends VldBase<unknown, Options[number] extends VldBase<any, infer T> ? T : never> {
13
13
  private readonly _discriminator;
14
14
  private readonly _options;
15
15
  private readonly _discriminatorMap;
16
16
  private readonly _stringDiscriminatorMap;
17
17
  private readonly _validValues;
18
18
  constructor(_discriminator: K, _options: Options);
19
- static create<K extends string, Options extends VldBase<any, any>[]>(discriminator: K, options: Options): VldDiscriminatedUnion<K, Options>;
19
+ get options(): Options;
20
+ get discriminator(): K;
21
+ static create<K extends string, Options extends readonly VldBase<any, any>[]>(discriminator: K, options: Options): VldDiscriminatedUnion<K, Options>;
20
22
  parse(value: unknown): Options[number] extends VldBase<any, infer T> ? T : never;
21
23
  safeParse(value: unknown): ParseResult<Options[number] extends VldBase<any, infer T> ? T : never>;
22
24
  /**
@@ -1,123 +1 @@
1
- import { VldBase, VLD_VALIDATOR_TYPES } from './base.js';
2
- import { VldObject } from './object.js';
3
- import { VldLiteral } from './literal.js';
4
- import { VldEnum } from './enum.js';
5
-
6
- /**
7
- * VldDiscriminatedUnion - Fast union validation using discriminator field
8
- * Part of Zod 4 API parity implementation
9
- * Provides O(1) lookup performance by using a discriminator key
10
- */
11
- /**
12
- * Extract literal values from a schema
13
- */
14
- function extractLiteralValues(schema) {
15
- if (schema instanceof VldLiteral) {
16
- return [schema.literal];
17
- }
18
- if (schema instanceof VldEnum) {
19
- return [...schema.values];
20
- }
21
- throw new Error('Discriminator must be a literal or enum schema');
22
- }
23
- /**
24
- * Discriminated union validator - validates union based on discriminator key
25
- * Much faster than regular union when you have a discriminator field
26
- */
27
- class VldDiscriminatedUnion extends VldBase {
28
- constructor(_discriminator, _options) {
29
- super(VLD_VALIDATOR_TYPES.DISCRIMINATED_UNION);
30
- this._discriminator = _discriminator;
31
- this._options = _options;
32
- // Build discriminator map for O(1) lookup
33
- this._discriminatorMap = new Map();
34
- this._stringDiscriminatorMap = Object.create(null);
35
- for (const option of _options) {
36
- if (!(option instanceof VldObject)) {
37
- throw new Error('All options in a discriminated union must be objects');
38
- }
39
- const discriminatorSchema = option.config?.shape?.[this._discriminator];
40
- if (!discriminatorSchema) {
41
- throw new Error(`Missing discriminator key "${this._discriminator}" in one of the options`);
42
- }
43
- const values = extractLiteralValues(discriminatorSchema);
44
- for (const value of values) {
45
- if (this._discriminatorMap.has(value)) {
46
- throw new Error(`Duplicate discriminator value "${String(value)}" found in discriminated union`);
47
- }
48
- this._discriminatorMap.set(value, option);
49
- if (typeof value === 'string') {
50
- this._stringDiscriminatorMap[value] = option;
51
- }
52
- }
53
- }
54
- this._validValues = Array.from(this._discriminatorMap.keys());
55
- }
56
- static create(discriminator, options) {
57
- return new VldDiscriminatedUnion(discriminator, options);
58
- }
59
- parse(value) {
60
- if (typeof value !== 'object' || value === null) {
61
- throw new Error(`Expected object, received ${value === null ? 'null' : typeof value}`);
62
- }
63
- const discriminatorValue = value[this._discriminator];
64
- const matchedSchema = typeof discriminatorValue === 'string'
65
- ? this._stringDiscriminatorMap[discriminatorValue]
66
- : this._discriminatorMap.get(discriminatorValue);
67
- if (!matchedSchema) {
68
- throw new Error(`Invalid discriminator value for "${this._discriminator}". ` +
69
- `Expected one of: ${JSON.stringify(this._validValues)}, ` +
70
- `received: ${JSON.stringify(discriminatorValue)}`);
71
- }
72
- return matchedSchema.parseTrustedKnownObject(value, this._discriminator);
73
- }
74
- safeParse(value) {
75
- // Check if input is an object
76
- if (typeof value !== 'object' || value === null) {
77
- return {
78
- success: false,
79
- error: new Error(`Expected object, received ${value === null ? 'null' : typeof value}`)
80
- };
81
- }
82
- // Get discriminator value
83
- const discriminatorValue = value[this._discriminator];
84
- // Look up matching schema
85
- const matchedSchema = typeof discriminatorValue === 'string'
86
- ? this._stringDiscriminatorMap[discriminatorValue]
87
- : this._discriminatorMap.get(discriminatorValue);
88
- if (!matchedSchema) {
89
- return {
90
- success: false,
91
- error: new Error(`Invalid discriminator value for "${this._discriminator}". ` +
92
- `Expected one of: ${JSON.stringify(this._validValues)}, ` +
93
- `received: ${JSON.stringify(discriminatorValue)}`)
94
- };
95
- }
96
- try {
97
- return {
98
- success: true,
99
- data: matchedSchema.parseTrustedKnownObject(value, this._discriminator)
100
- };
101
- }
102
- catch (error) {
103
- return {
104
- success: false,
105
- error: error
106
- };
107
- }
108
- }
109
- /**
110
- * Get the discriminator key
111
- */
112
- getDiscriminator() {
113
- return this._discriminator;
114
- }
115
- /**
116
- * Get all options
117
- */
118
- getOptions() {
119
- return this._options;
120
- }
121
- }
122
-
123
- export { VldDiscriminatedUnion };
1
+ import{VldBase as i,VLD_VALIDATOR_TYPES as r,ensureVldError as t}from"./base.js";import{VldObject as s}from"./object.js";import{VldLiteral as n}from"./literal.js";import{VldEnum as e}from"./enum.js";function o(i){if(i instanceof n)return[...i.values];if(i instanceof e)return[...i.values];throw new Error("Discriminator must be a literal or enum schema")}class VldDiscriminatedUnion extends i{constructor(i,t){super(r.DISCRIMINATED_UNION),this._discriminator=i,this._options=t,this._discriminatorMap=new Map,this._stringDiscriminatorMap=Object.create(null);for(const i of t){if(!(i instanceof s))throw new Error("All options in a discriminated union must be objects");const r=i.config?.shape?.[this._discriminator];if(!r)throw new Error(`Missing discriminator key "${this._discriminator}" in one of the options`);const t=o(r);for(const r of t){if(this._discriminatorMap.has(r))throw new Error(`Duplicate discriminator value "${String(r)}" found in discriminated union`);this._discriminatorMap.set(r,i),"string"==typeof r&&(this._stringDiscriminatorMap[r]=i)}}this._validValues=Array.from(this._discriminatorMap.keys())}get options(){return this._options}get discriminator(){return this._discriminator}static create(i,r){return new VldDiscriminatedUnion(i,r)}parse(i){if("object"!=typeof i||null===i)throw new Error("Expected object, received "+(null===i?"null":typeof i));const r=i[this._discriminator],t="string"==typeof r?this._stringDiscriminatorMap[r]:this._discriminatorMap.get(r);if(!t)throw new Error(`Invalid discriminator value for "${this._discriminator}". Expected one of: ${JSON.stringify(this._validValues)}, received: ${JSON.stringify(r)}`);return t.parseTrustedKnownObject(i,this._discriminator)}safeParse(i){if("object"!=typeof i||null===i)return{success:!1,error:t("Expected object, received "+(null===i?"null":typeof i))};const r=i[this._discriminator],s="string"==typeof r?this._stringDiscriminatorMap[r]:this._discriminatorMap.get(r);if(!s)return{success:!1,error:t(`Invalid discriminator value for "${this._discriminator}". Expected one of: ${JSON.stringify(this._validValues)}, received: ${JSON.stringify(r)}`)};try{return{success:!0,data:s.parseTrustedKnownObject(i,this._discriminator)}}catch(i){return{success:!1,error:t(i)}}}getDiscriminator(){return this._discriminator}getOptions(){return this._options}}export{VldDiscriminatedUnion};
@@ -16,6 +16,10 @@ export declare class VldEnum<T extends readonly [EnumValue, ...EnumValue[]]> ext
16
16
  * Get the enum values
17
17
  */
18
18
  get values(): T;
19
+ get options(): T;
20
+ get enum(): {
21
+ [K in T[number]]: K;
22
+ };
19
23
  /**
20
24
  * Create a new enum validator
21
25
  */
@@ -32,11 +36,13 @@ export declare class VldEnum<T extends readonly [EnumValue, ...EnumValue[]]> ext
32
36
  * Exclude specific values from the enum
33
37
  * Creates a new enum validator without the specified values
34
38
  */
35
- exclude<const E extends readonly EnumValue[]>(...excludeValues: E): VldEnum<T[number] extends E[number] ? never : T[number] extends Exclude<T[number], E[number]> ? T : Exclude<T, E>>;
39
+ exclude<const E extends readonly EnumValue[]>(values: E): VldEnum<any>;
40
+ exclude<const E extends readonly EnumValue[]>(...values: E): VldEnum<any>;
36
41
  /**
37
42
  * Extract specific values from the enum
38
43
  * Creates a new enum validator with only the specified values
39
44
  */
40
- extract<const E extends readonly EnumValue[]>(...extractValues: E): VldEnum<[E[number], ...E[number][]]>;
45
+ extract<const E extends readonly EnumValue[]>(values: E): VldEnum<any>;
46
+ extract<const E extends readonly EnumValue[]>(...values: E): VldEnum<any>;
41
47
  }
42
48
  export {};