@railway-ts/pipelines 0.1.30 → 0.2.1
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/README.md +4 -4
- package/dist/composition/index.d.mts +367 -0
- package/dist/composition/index.mjs +37 -59
- package/dist/composition/index.mjs.map +1 -1
- package/dist/{result/index.d.cts → index-DDkNG41b.d.mts} +63 -139
- package/dist/option/index.d.mts +7 -0
- package/dist/option/index.mjs +1 -114
- package/dist/option-BQCaaEBP.mjs +909 -0
- package/dist/option-BQCaaEBP.mjs.map +1 -0
- package/dist/result/index.d.mts +7 -0
- package/dist/result/index.mjs +1 -185
- package/dist/schema/{index.d.cts → index.d.mts} +227 -259
- package/dist/schema/index.mjs +1646 -978
- package/dist/schema/index.mjs.map +1 -1
- package/docs/GETTING_STARTED.md +1 -1
- package/docs/RECIPES.md +3 -3
- package/package.json +26 -70
- package/dist/composition/index.cjs +0 -94
- package/dist/composition/index.cjs.map +0 -1
- package/dist/composition/index.d.cts +0 -373
- package/dist/composition/index.d.ts +0 -373
- package/dist/option/index.cjs +0 -137
- package/dist/option/index.cjs.map +0 -1
- package/dist/option/index.d.cts +0 -1
- package/dist/option/index.d.ts +0 -1
- package/dist/option/index.mjs.map +0 -1
- package/dist/result/index.cjs +0 -219
- package/dist/result/index.cjs.map +0 -1
- package/dist/result/index.d.ts +0 -1063
- package/dist/result/index.mjs.map +0 -1
- package/dist/schema/index.cjs +0 -1165
- package/dist/schema/index.cjs.map +0 -1
- package/dist/schema/index.d.ts +0 -1266
package/dist/schema/index.mjs
CHANGED
|
@@ -1,1088 +1,1756 @@
|
|
|
1
|
-
|
|
2
|
-
var RESULT_BRAND = /* @__PURE__ */ Symbol("RESULT_BRAND");
|
|
3
|
-
function ok(value) {
|
|
4
|
-
return {
|
|
5
|
-
ok: true,
|
|
6
|
-
value,
|
|
7
|
-
[RESULT_BRAND]: "ok"
|
|
8
|
-
};
|
|
9
|
-
}
|
|
10
|
-
function err(error) {
|
|
11
|
-
return { ok: false, error, [RESULT_BRAND]: "error" };
|
|
12
|
-
}
|
|
13
|
-
function isOk(result) {
|
|
14
|
-
return result.ok;
|
|
15
|
-
}
|
|
16
|
-
function isErr(result) {
|
|
17
|
-
return !result.ok;
|
|
18
|
-
}
|
|
19
|
-
function mapErr(result, fn) {
|
|
20
|
-
return result.ok ? result : err(fn(result.error));
|
|
21
|
-
}
|
|
22
|
-
function match(result, patterns) {
|
|
23
|
-
if (isOk(result)) {
|
|
24
|
-
const okFn = patterns.ok;
|
|
25
|
-
return okFn(result.value);
|
|
26
|
-
}
|
|
27
|
-
const errFn = patterns.err;
|
|
28
|
-
return errFn(result.error);
|
|
29
|
-
}
|
|
30
|
-
function fromTry(f) {
|
|
31
|
-
try {
|
|
32
|
-
return ok(f());
|
|
33
|
-
} catch (error) {
|
|
34
|
-
return err(error instanceof Error ? error.message : String(error));
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
1
|
+
import { D as err, I as isErr, L as isOk, P as fromTry, U as match, W as ok, z as mapErr } from "../option-BQCaaEBP.mjs";
|
|
38
2
|
// src/schema/core.ts
|
|
39
|
-
|
|
3
|
+
let _abortEarly = false;
|
|
4
|
+
/** @internal */
|
|
40
5
|
function _getAbortEarly() {
|
|
41
|
-
|
|
6
|
+
return _abortEarly;
|
|
42
7
|
}
|
|
8
|
+
/** @internal - Sets abortEarly for the duration of fn's synchronous execution */
|
|
43
9
|
function _withAbortEarly(enabled, fn) {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
10
|
+
const prev = _abortEarly;
|
|
11
|
+
_abortEarly = enabled;
|
|
12
|
+
try {
|
|
13
|
+
return fn();
|
|
14
|
+
} finally {
|
|
15
|
+
_abortEarly = prev;
|
|
16
|
+
}
|
|
51
17
|
}
|
|
52
18
|
function object(schema, { strict = true } = {}) {
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
}
|
|
102
|
-
if (pendingResults.length > 0) {
|
|
103
|
-
return Promise.all(pendingResults).then(() => {
|
|
104
|
-
if (allErrors.length > 0) return err(allErrors);
|
|
105
|
-
return ok(validatedObj);
|
|
106
|
-
});
|
|
107
|
-
}
|
|
108
|
-
if (allErrors.length > 0) return err(allErrors);
|
|
109
|
-
return ok(validatedObj);
|
|
110
|
-
};
|
|
19
|
+
return (obj, parentPath = []) => {
|
|
20
|
+
if (obj === null || typeof obj !== "object") return err([{
|
|
21
|
+
path: parentPath,
|
|
22
|
+
message: "Expected an object"
|
|
23
|
+
}]);
|
|
24
|
+
const abortEarly = _getAbortEarly();
|
|
25
|
+
const allErrors = [];
|
|
26
|
+
const validatedObj = {};
|
|
27
|
+
if (strict !== false) {
|
|
28
|
+
const extraKeys = Object.keys(obj).filter((key) => !Object.prototype.hasOwnProperty.call(schema, key));
|
|
29
|
+
if (extraKeys.length > 0) {
|
|
30
|
+
if (abortEarly) return err([{
|
|
31
|
+
path: [...parentPath, extraKeys[0]],
|
|
32
|
+
message: `Unexpected field: '${extraKeys[0]}'`
|
|
33
|
+
}]);
|
|
34
|
+
for (const key of extraKeys) allErrors.push({
|
|
35
|
+
path: [...parentPath, key],
|
|
36
|
+
message: `Unexpected field: '${key}'`
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
if (abortEarly && allErrors.length > 0) return err(allErrors);
|
|
41
|
+
const pendingResults = [];
|
|
42
|
+
for (const key in schema) {
|
|
43
|
+
if (!Object.prototype.hasOwnProperty.call(schema, key)) continue;
|
|
44
|
+
const validator = schema[key];
|
|
45
|
+
if (!validator) continue;
|
|
46
|
+
if (abortEarly && allErrors.length > 0) break;
|
|
47
|
+
const result = validator(obj[key], [...parentPath, key]);
|
|
48
|
+
if (result instanceof Promise) {
|
|
49
|
+
if (abortEarly && allErrors.length > 0) continue;
|
|
50
|
+
pendingResults.push(result.then((r) => {
|
|
51
|
+
if (isOk(r)) validatedObj[key] = r.value;
|
|
52
|
+
else allErrors.push(...r.error);
|
|
53
|
+
}));
|
|
54
|
+
} else if (isOk(result)) validatedObj[key] = result.value;
|
|
55
|
+
else {
|
|
56
|
+
allErrors.push(...result.error);
|
|
57
|
+
if (abortEarly) break;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (pendingResults.length > 0) return Promise.all(pendingResults).then(() => {
|
|
61
|
+
if (allErrors.length > 0) return err(allErrors);
|
|
62
|
+
return ok(validatedObj);
|
|
63
|
+
});
|
|
64
|
+
if (allErrors.length > 0) return err(allErrors);
|
|
65
|
+
return ok(validatedObj);
|
|
66
|
+
};
|
|
111
67
|
}
|
|
112
68
|
function required(validator, message = "Field is required") {
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
69
|
+
return (value, path = []) => {
|
|
70
|
+
if (value === void 0 || value === null) return err([{
|
|
71
|
+
path,
|
|
72
|
+
message
|
|
73
|
+
}]);
|
|
74
|
+
return validator(value, path);
|
|
75
|
+
};
|
|
119
76
|
}
|
|
120
77
|
function optional(validator) {
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
78
|
+
return (value, path = []) => {
|
|
79
|
+
if (value === void 0 || value === null) return ok(void 0);
|
|
80
|
+
return validator(value, path);
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Create a validator that only accepts null values.
|
|
85
|
+
*
|
|
86
|
+
* @example
|
|
87
|
+
* const validate = nullable();
|
|
88
|
+
* validate(null); // ok(null)
|
|
89
|
+
* validate('some value'); // err([{ path: [], message: 'Must be null' }])
|
|
90
|
+
*
|
|
91
|
+
* @param message - Custom error message
|
|
92
|
+
* @returns A validator that ensures the value is exactly null
|
|
93
|
+
*/
|
|
128
94
|
function nullable(message = "Must be null") {
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
95
|
+
return (value, path = []) => {
|
|
96
|
+
if (value !== null) return err([{
|
|
97
|
+
path,
|
|
98
|
+
message
|
|
99
|
+
}]);
|
|
100
|
+
return ok(null);
|
|
101
|
+
};
|
|
135
102
|
}
|
|
136
103
|
function emptyAsOptional(validator) {
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
104
|
+
return (value, path = []) => {
|
|
105
|
+
if (value === "" || Array.isArray(value) && value.length === 0 || typeof value === "object" && value !== null && Object.keys(value).length === 0) return ok(void 0);
|
|
106
|
+
return optional(validator)(value, path);
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Create a validator that checks if a value exactly matches the expected literal.
|
|
111
|
+
*
|
|
112
|
+
* @example
|
|
113
|
+
* const validate = literal('active');
|
|
114
|
+
* validate('active'); // ok("active")
|
|
115
|
+
* validate('completed'); // err([{ path: [], message: "Value must be 'active'" }])
|
|
116
|
+
*
|
|
117
|
+
* @param expectedValue - The exact value that should be matched
|
|
118
|
+
* @param message - Custom error message
|
|
119
|
+
* @returns A validator that checks if the value matches the literal
|
|
120
|
+
*/
|
|
144
121
|
function literal(expectedValue, message = `Value must be '${String(expectedValue)}'`) {
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
122
|
+
return (value, path = []) => {
|
|
123
|
+
if (value !== expectedValue) return err([{
|
|
124
|
+
path,
|
|
125
|
+
message
|
|
126
|
+
}]);
|
|
127
|
+
return ok(expectedValue);
|
|
128
|
+
};
|
|
151
129
|
}
|
|
152
|
-
|
|
153
130
|
// src/schema/utils.ts
|
|
154
|
-
|
|
131
|
+
/**
|
|
132
|
+
* The key used in formatted error objects for root-level validation errors (i.e. errors with an empty path).
|
|
133
|
+
*/
|
|
134
|
+
const ROOT_ERROR_KEY = "_root";
|
|
135
|
+
/**
|
|
136
|
+
* Combine multiple validators into a single validator, applying them in sequence.
|
|
137
|
+
* Each validator's output feeds into the next. Short-circuits on first error.
|
|
138
|
+
*
|
|
139
|
+
* @example
|
|
140
|
+
* const validate = chain(string(), nonEmpty(), minLength(8));
|
|
141
|
+
* validate('password123'); // ok("password123")
|
|
142
|
+
* validate('abc'); // err([{ path: [], message: 'Must be at least 8 characters' }])
|
|
143
|
+
*
|
|
144
|
+
* @param validators - A list of validators to compose
|
|
145
|
+
* @returns A combined validator that applies all validators in sequence
|
|
146
|
+
*/
|
|
155
147
|
function chain(...validators) {
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
148
|
+
return (value, path = []) => {
|
|
149
|
+
let result = ok(value);
|
|
150
|
+
for (const validator of validators) {
|
|
151
|
+
if (isErr(result)) return result;
|
|
152
|
+
const nextResult = validator(result.value, path);
|
|
153
|
+
result = isErr(nextResult) ? nextResult : ok(nextResult.value);
|
|
154
|
+
}
|
|
155
|
+
return result;
|
|
156
|
+
};
|
|
165
157
|
}
|
|
166
158
|
function chainAsync(...validators) {
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
159
|
+
return async (value, path = []) => {
|
|
160
|
+
let current = value;
|
|
161
|
+
for (const validator of validators) {
|
|
162
|
+
const result = await validator(current, path);
|
|
163
|
+
if (isErr(result)) return result;
|
|
164
|
+
current = result.value;
|
|
165
|
+
}
|
|
166
|
+
return ok(current);
|
|
167
|
+
};
|
|
176
168
|
}
|
|
177
169
|
function validate(value, validator, pathOrOptions = [], maybeOptions) {
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
return _withAbortEarly(true, () => validator(value, path));
|
|
182
|
-
}
|
|
183
|
-
return validator(value, path);
|
|
170
|
+
const path = Array.isArray(pathOrOptions) ? pathOrOptions : [];
|
|
171
|
+
if ((Array.isArray(pathOrOptions) ? maybeOptions : pathOrOptions)?.abortEarly) return _withAbortEarly(true, () => validator(value, path));
|
|
172
|
+
return validator(value, path);
|
|
184
173
|
}
|
|
185
174
|
function is(value, validator) {
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
175
|
+
const result = _withAbortEarly(true, () => validator(value));
|
|
176
|
+
if (result instanceof Promise) return result.then((r) => r.ok);
|
|
177
|
+
return result.ok;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Format validation errors into a user-friendly object.
|
|
181
|
+
* Converts array paths to dot/bracket notation strings.
|
|
182
|
+
*
|
|
183
|
+
* @example
|
|
184
|
+
* formatErrors([
|
|
185
|
+
* { path: ['name'], message: 'Required' },
|
|
186
|
+
* { path: ['items', '1'], message: 'Must be a number' },
|
|
187
|
+
* ]);
|
|
188
|
+
* // { name: 'Required', 'items[1]': 'Must be a number' }
|
|
189
|
+
*
|
|
190
|
+
* @param errors - The array of validation errors to format
|
|
191
|
+
* @returns An object mapping paths to error messages
|
|
192
|
+
*/
|
|
192
193
|
function formatErrors(errors) {
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
acc[formattedPath || ROOT_ERROR_KEY] = error.message;
|
|
202
|
-
return acc;
|
|
203
|
-
},
|
|
204
|
-
{}
|
|
205
|
-
);
|
|
194
|
+
return errors.reduce((acc, error) => {
|
|
195
|
+
const formattedPath = error.path.reduce((path, segment, index) => {
|
|
196
|
+
if (/^\d+$/.test(segment)) return `${path}[${segment}]`;
|
|
197
|
+
return index === 0 ? segment : `${path}.${segment}`;
|
|
198
|
+
}, "");
|
|
199
|
+
acc[formattedPath || "_root"] = error.message;
|
|
200
|
+
return acc;
|
|
201
|
+
}, {});
|
|
206
202
|
}
|
|
207
203
|
function validateAndFormatResult(input, schema, options) {
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
204
|
+
const run = () => {
|
|
205
|
+
const result = schema(input);
|
|
206
|
+
if (result instanceof Promise) return result.then((r) => match(r, {
|
|
207
|
+
ok: (data) => ({
|
|
208
|
+
valid: true,
|
|
209
|
+
data
|
|
210
|
+
}),
|
|
211
|
+
err: (errors) => ({
|
|
212
|
+
valid: false,
|
|
213
|
+
errors: formatErrors(errors)
|
|
214
|
+
})
|
|
215
|
+
}));
|
|
216
|
+
return match(result, {
|
|
217
|
+
ok: (data) => ({
|
|
218
|
+
valid: true,
|
|
219
|
+
data
|
|
220
|
+
}),
|
|
221
|
+
err: (errors) => ({
|
|
222
|
+
valid: false,
|
|
223
|
+
errors: formatErrors(errors)
|
|
224
|
+
})
|
|
225
|
+
});
|
|
226
|
+
};
|
|
227
|
+
if (options?.abortEarly) return _withAbortEarly(true, run);
|
|
228
|
+
return run();
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Create a validator that transforms a value during validation.
|
|
232
|
+
* The transformer function must be pure and not throw exceptions.
|
|
233
|
+
*
|
|
234
|
+
* @example
|
|
235
|
+
* const normalize = chain(string(), email(), transform(s => s.toLowerCase()));
|
|
236
|
+
* normalize('User@Example.COM'); // ok("user@example.com")
|
|
237
|
+
*
|
|
238
|
+
* @param transformer - A pure function that transforms the input value
|
|
239
|
+
* @returns A validator that applies the transformation
|
|
240
|
+
*/
|
|
228
241
|
function transform(transformer) {
|
|
229
|
-
|
|
230
|
-
}
|
|
242
|
+
return (value) => ok(transformer(value));
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Create a validator that refines a value with a custom predicate.
|
|
246
|
+
*
|
|
247
|
+
* @example
|
|
248
|
+
* const isEven = refine<number>(n => n % 2 === 0, 'Must be even');
|
|
249
|
+
* isEven(4); // ok(4)
|
|
250
|
+
* isEven(3); // err([{ path: [], message: 'Must be even' }])
|
|
251
|
+
*
|
|
252
|
+
* @param predicate - A function that returns true if the value is valid
|
|
253
|
+
* @param message - The error message if validation fails
|
|
254
|
+
* @returns A validator that checks the predicate
|
|
255
|
+
*/
|
|
231
256
|
function refine(predicate, message = "Custom validation failed") {
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
}
|
|
257
|
+
return (value, path = []) => {
|
|
258
|
+
if (!predicate(value)) return err([{
|
|
259
|
+
path,
|
|
260
|
+
message
|
|
261
|
+
}]);
|
|
262
|
+
return ok(value);
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Create an async validator that refines a value with an asynchronous predicate.
|
|
267
|
+
* This is the async counterpart of {@link refine}.
|
|
268
|
+
*
|
|
269
|
+
* @example
|
|
270
|
+
* const unique = refineAsync<string>(
|
|
271
|
+
* async (name) => !(await db.users.exists({ name })),
|
|
272
|
+
* 'Already taken'
|
|
273
|
+
* );
|
|
274
|
+
*
|
|
275
|
+
* @param predicate - An async function returning true if the value is valid
|
|
276
|
+
* @param message - The error message if validation fails
|
|
277
|
+
* @returns An async validator that checks the predicate
|
|
278
|
+
*/
|
|
239
279
|
function refineAsync(predicate, message = "Custom validation failed") {
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
}
|
|
280
|
+
return async (value, path = []) => {
|
|
281
|
+
if (!await predicate(value)) return err([{
|
|
282
|
+
path,
|
|
283
|
+
message
|
|
284
|
+
}]);
|
|
285
|
+
return ok(value);
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Create a validator that targets a specific field path with cross-field validation.
|
|
290
|
+
* Unlike `refine`, receives the entire parent object and attaches errors to a specific field.
|
|
291
|
+
*
|
|
292
|
+
* @example
|
|
293
|
+
* const validate = chain(
|
|
294
|
+
* object({ password: required(string()), confirm: required(string()) }),
|
|
295
|
+
* refineAt('confirm', (d) => d.password === d.confirm, 'Passwords must match')
|
|
296
|
+
* );
|
|
297
|
+
*
|
|
298
|
+
* @param targetPath - The field path where the error should be attached
|
|
299
|
+
* @param predicate - Validation function that receives the entire parent object
|
|
300
|
+
* @param message - Error message when validation fails
|
|
301
|
+
* @returns A validator for cross-field validation
|
|
302
|
+
*
|
|
303
|
+
* @see refine - For single-field validation without cross-field dependencies
|
|
304
|
+
*/
|
|
247
305
|
function refineAt(targetPath, predicate, message) {
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
}
|
|
306
|
+
return (value, parentPath = []) => {
|
|
307
|
+
if (!predicate(value)) {
|
|
308
|
+
const fieldPath = Array.isArray(targetPath) ? targetPath : [targetPath];
|
|
309
|
+
return err([{
|
|
310
|
+
path: [...parentPath, ...fieldPath],
|
|
311
|
+
message
|
|
312
|
+
}]);
|
|
313
|
+
}
|
|
314
|
+
return ok(value);
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Create an async validator that targets a specific field path with cross-field validation.
|
|
319
|
+
* This is the async counterpart of {@link refineAt}.
|
|
320
|
+
*
|
|
321
|
+
* @example
|
|
322
|
+
* const validate = chainAsync(
|
|
323
|
+
* object({ username: required(string()), email: required(email()) }),
|
|
324
|
+
* refineAtAsync(
|
|
325
|
+
* 'username',
|
|
326
|
+
* async (d) => !(await db.users.exists({ username: d.username })),
|
|
327
|
+
* 'Username taken'
|
|
328
|
+
* )
|
|
329
|
+
* );
|
|
330
|
+
*
|
|
331
|
+
* @param targetPath - The field path where the error should be attached
|
|
332
|
+
* @param predicate - An async function that receives the entire parent object
|
|
333
|
+
* @param message - Error message when validation fails
|
|
334
|
+
* @returns An async validator for cross-field validation
|
|
335
|
+
*
|
|
336
|
+
* @see refineAt - For synchronous cross-field validation
|
|
337
|
+
*/
|
|
256
338
|
function refineAtAsync(targetPath, predicate, message) {
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
}
|
|
339
|
+
return async (value, parentPath = []) => {
|
|
340
|
+
if (!await predicate(value)) {
|
|
341
|
+
const fieldPath = Array.isArray(targetPath) ? targetPath : [targetPath];
|
|
342
|
+
return err([{
|
|
343
|
+
path: [...parentPath, ...fieldPath],
|
|
344
|
+
message
|
|
345
|
+
}]);
|
|
346
|
+
}
|
|
347
|
+
return ok(value);
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Create a conditional validator that applies different validators based on a predicate.
|
|
352
|
+
* When the predicate returns true, `thenValidator` is applied.
|
|
353
|
+
* When false, `elseValidator` is applied (if provided), otherwise the value passes through.
|
|
354
|
+
*
|
|
355
|
+
* @example
|
|
356
|
+
* const validate = when<FormData>(
|
|
357
|
+
* (data) => data.contactMethod === 'email',
|
|
358
|
+
* refineAt('email', (d) => d.email.includes('@'), 'Valid email required'),
|
|
359
|
+
* refineAt('phone', (d) => d.phone.length > 0, 'Phone required'),
|
|
360
|
+
* );
|
|
361
|
+
*
|
|
362
|
+
* @param predicate - A function that determines which validator to apply
|
|
363
|
+
* @param thenValidator - Validator applied when predicate returns true
|
|
364
|
+
* @param elseValidator - Optional validator applied when predicate returns false
|
|
365
|
+
* @returns A validator that conditionally applies validation
|
|
366
|
+
*/
|
|
265
367
|
function when(predicate, thenValidator, elseValidator) {
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
368
|
+
return (value, path = []) => {
|
|
369
|
+
if (predicate(value)) return thenValidator(value, path);
|
|
370
|
+
return elseValidator ? elseValidator(value, path) : ok(value);
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Create a conditional async validator that applies different validators based on a predicate.
|
|
375
|
+
* This is the async counterpart of {@link when}.
|
|
376
|
+
*
|
|
377
|
+
* @example
|
|
378
|
+
* const validate = whenAsync<FormData>(
|
|
379
|
+
* (data) => data.requiresVerification,
|
|
380
|
+
* refineAtAsync('code', async (d) => await verifyCode(d.code), 'Invalid code'),
|
|
381
|
+
* );
|
|
382
|
+
*
|
|
383
|
+
* @param predicate - A function that determines which validator to apply
|
|
384
|
+
* @param thenValidator - Validator applied when predicate returns true
|
|
385
|
+
* @param elseValidator - Optional validator applied when predicate returns false
|
|
386
|
+
* @returns An async validator that conditionally applies validation
|
|
387
|
+
*/
|
|
273
388
|
function whenAsync(predicate, thenValidator, elseValidator) {
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
return elseValidator ? elseValidator(value, path) : ok(value);
|
|
279
|
-
};
|
|
389
|
+
return async (value, path = []) => {
|
|
390
|
+
if (predicate(value)) return thenValidator(value, path);
|
|
391
|
+
return elseValidator ? elseValidator(value, path) : ok(value);
|
|
392
|
+
};
|
|
280
393
|
}
|
|
281
|
-
|
|
282
394
|
// src/schema/string.ts
|
|
395
|
+
/**
|
|
396
|
+
* Create a validator that ensures a value is a string.
|
|
397
|
+
*
|
|
398
|
+
* @example
|
|
399
|
+
* const validate = string();
|
|
400
|
+
* validate('John'); // ok("John")
|
|
401
|
+
* validate(42); // err([{ path: [], message: 'Must be a string' }])
|
|
402
|
+
*
|
|
403
|
+
* @param message - Custom error message
|
|
404
|
+
* @returns A validator that checks if a value is a string
|
|
405
|
+
*/
|
|
283
406
|
function string(message = "Must be a string") {
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
407
|
+
return (value, path = []) => {
|
|
408
|
+
if (typeof value !== "string") return err([{
|
|
409
|
+
path,
|
|
410
|
+
message
|
|
411
|
+
}]);
|
|
412
|
+
return ok(value);
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Create a validator that ensures a string's length is at least a minimum value.
|
|
417
|
+
*
|
|
418
|
+
* @example
|
|
419
|
+
* const validate = minLength(3);
|
|
420
|
+
* validate('john_doe'); // ok("john_doe")
|
|
421
|
+
* validate('jo'); // err([{ path: [], message: 'Must be at least 3 characters' }])
|
|
422
|
+
*
|
|
423
|
+
* @param min - The minimum length (inclusive)
|
|
424
|
+
* @param message - Custom error message
|
|
425
|
+
* @returns A validator that checks if a string meets the minimum length
|
|
426
|
+
*/
|
|
427
|
+
function minLength(min, message = `Must be at least ${min} characters`) {
|
|
428
|
+
return (value, path = []) => {
|
|
429
|
+
if (value.length < min) return err([{
|
|
430
|
+
path,
|
|
431
|
+
message
|
|
432
|
+
}]);
|
|
433
|
+
return ok(value);
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Create a validator that ensures a string's length is at most a maximum value.
|
|
438
|
+
*
|
|
439
|
+
* @example
|
|
440
|
+
* const validate = maxLength(10);
|
|
441
|
+
* validate('short'); // ok("short")
|
|
442
|
+
* validate('this is too long!!!'); // err([{ path: [], message: 'Must be at most 10 characters' }])
|
|
443
|
+
*
|
|
444
|
+
* @param max - The maximum length (inclusive)
|
|
445
|
+
* @param message - Custom error message
|
|
446
|
+
* @returns A validator that checks if a string meets the maximum length
|
|
447
|
+
*/
|
|
448
|
+
function maxLength(max, message = `Must be at most ${max} characters`) {
|
|
449
|
+
return (value, path = []) => {
|
|
450
|
+
if (value.length > max) return err([{
|
|
451
|
+
path,
|
|
452
|
+
message
|
|
453
|
+
}]);
|
|
454
|
+
return ok(value);
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Create a validator that ensures a string matches a regular expression pattern.
|
|
459
|
+
*
|
|
460
|
+
* @example
|
|
461
|
+
* const validate = pattern(/^[a-zA-Z0-9]+$/);
|
|
462
|
+
* validate('abc123'); // ok("abc123")
|
|
463
|
+
* validate('abc!'); // err([{ path: [], message: 'Invalid format' }])
|
|
464
|
+
*
|
|
465
|
+
* @param regex - The regular expression to test against
|
|
466
|
+
* @param message - Custom error message
|
|
467
|
+
* @returns A validator that checks if a string matches the pattern
|
|
468
|
+
*/
|
|
307
469
|
function pattern(regex, message = "Invalid format") {
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
}
|
|
470
|
+
return (value, path = []) => {
|
|
471
|
+
if (!regex.test(value)) return err([{
|
|
472
|
+
path,
|
|
473
|
+
message
|
|
474
|
+
}]);
|
|
475
|
+
return ok(value);
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Create a validator that ensures a string is not empty after trimming whitespace.
|
|
480
|
+
*
|
|
481
|
+
* @example
|
|
482
|
+
* const validate = nonEmpty();
|
|
483
|
+
* validate('John'); // ok("John")
|
|
484
|
+
* validate(''); // err([{ path: [], message: 'Field must not be empty' }])
|
|
485
|
+
* validate(' '); // err([{ path: [], message: 'Field must not be empty' }])
|
|
486
|
+
*
|
|
487
|
+
* @param message - Custom error message
|
|
488
|
+
* @returns A validator that checks if a string is not empty
|
|
489
|
+
*/
|
|
315
490
|
function nonEmpty(message = "Field must not be empty") {
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
}
|
|
491
|
+
return (value, path = []) => {
|
|
492
|
+
if (value.trim().length === 0) return err([{
|
|
493
|
+
path,
|
|
494
|
+
message
|
|
495
|
+
}]);
|
|
496
|
+
return ok(value);
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* Create a validator that ensures a string is a valid email address.
|
|
501
|
+
*
|
|
502
|
+
* @example
|
|
503
|
+
* const validate = email();
|
|
504
|
+
* validate('user@example.com'); // ok("user@example.com")
|
|
505
|
+
* validate('not-an-email'); // err([{ path: [], message: 'Invalid email format' }])
|
|
506
|
+
*
|
|
507
|
+
* @param message - Custom error message
|
|
508
|
+
* @returns A validator that checks if a string is a valid email
|
|
509
|
+
*/
|
|
323
510
|
function email(message = "Invalid email format") {
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
511
|
+
return pattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/, message);
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Create a validator that ensures a string is a valid URL.
|
|
515
|
+
*
|
|
516
|
+
* @example
|
|
517
|
+
* const validate = url();
|
|
518
|
+
* validate('https://example.com'); // ok("https://example.com")
|
|
519
|
+
* validate('not-a-url'); // err([{ path: [], message: 'Invalid URL format' }])
|
|
520
|
+
*
|
|
521
|
+
* @param message - Custom error message
|
|
522
|
+
* @returns A validator that checks if a string is a valid URL
|
|
523
|
+
*/
|
|
327
524
|
function url(message = "Invalid URL format") {
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
}
|
|
525
|
+
return (value, path = []) => {
|
|
526
|
+
try {
|
|
527
|
+
new URL(value);
|
|
528
|
+
return ok(value);
|
|
529
|
+
} catch {
|
|
530
|
+
return err([{
|
|
531
|
+
path,
|
|
532
|
+
message
|
|
533
|
+
}]);
|
|
534
|
+
}
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* Create a validator that ensures a string is a valid phone number.
|
|
539
|
+
* Accepts common formats including international (+), spaces, dashes, and parentheses.
|
|
540
|
+
*
|
|
541
|
+
* @example
|
|
542
|
+
* const validate = phoneNumber();
|
|
543
|
+
* validate('+1-555-123-4567'); // ok("+1-555-123-4567")
|
|
544
|
+
* validate('not-a-phone'); // err([{ path: [], message: 'Invalid phone number format' }])
|
|
545
|
+
*
|
|
546
|
+
* @param message - Custom error message
|
|
547
|
+
* @returns A validator that checks if a string is a valid phone number
|
|
548
|
+
*/
|
|
337
549
|
function phoneNumber(message = "Invalid phone number format") {
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
}
|
|
550
|
+
const phoneRegex = /^\+?[\d\-()]{8,20}$/;
|
|
551
|
+
return (value, path = []) => {
|
|
552
|
+
const cleanedValue = value.replaceAll(/\s+/g, "");
|
|
553
|
+
if (!phoneRegex.test(cleanedValue) || cleanedValue.replaceAll(/\D/g, "").length < 7) return err([{
|
|
554
|
+
path,
|
|
555
|
+
message
|
|
556
|
+
}]);
|
|
557
|
+
return ok(value);
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Create a validator that ensures a string is a valid UUID (RFC 4122).
|
|
562
|
+
* Accepts any UUID version including NIL UUIDs (all zeros).
|
|
563
|
+
*
|
|
564
|
+
* @example
|
|
565
|
+
* const validate = uuid();
|
|
566
|
+
* validate('550e8400-e29b-41d4-a716-446655440000'); // ok(...)
|
|
567
|
+
* validate('not-a-uuid'); // err([{ path: [], message: 'Invalid UUID format' }])
|
|
568
|
+
*
|
|
569
|
+
* @param message - Custom error message
|
|
570
|
+
* @returns A validator that checks if a string is a valid UUID
|
|
571
|
+
*/
|
|
347
572
|
function uuid(message = "Invalid UUID format") {
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
573
|
+
return pattern(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i, message);
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* Create a validator that ensures a string is a valid ISO 8601 date (YYYY-MM-DD).
|
|
577
|
+
* Validates both format and calendar correctness (e.g., rejects Feb 30).
|
|
578
|
+
*
|
|
579
|
+
* @example
|
|
580
|
+
* const validate = isoDate();
|
|
581
|
+
* validate('2024-01-15'); // ok("2024-01-15")
|
|
582
|
+
* validate('2024-02-30'); // err([{ path: [], message: 'Invalid ISO date format' }])
|
|
583
|
+
*
|
|
584
|
+
* @param message - Custom error message
|
|
585
|
+
* @returns A validator that checks if a string is a valid ISO date
|
|
586
|
+
*/
|
|
351
587
|
function isoDate(message = "Invalid ISO date format") {
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
588
|
+
const isoDateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
|
589
|
+
return (value, path = []) => {
|
|
590
|
+
if (!isoDateRegex.test(value)) return err([{
|
|
591
|
+
path,
|
|
592
|
+
message
|
|
593
|
+
}]);
|
|
594
|
+
const date = /* @__PURE__ */ new Date(value + "T00:00:00Z");
|
|
595
|
+
if (Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== value) return err([{
|
|
596
|
+
path,
|
|
597
|
+
message
|
|
598
|
+
}]);
|
|
599
|
+
return ok(value);
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* Create a validator that ensures a string is a valid ISO 8601 / RFC 3339 time.
|
|
604
|
+
* Format: `HH:mm:ss[.fractional][Z|±HH:mm]`. Timezone is optional.
|
|
605
|
+
*
|
|
606
|
+
* @example
|
|
607
|
+
* const validate = isoTime();
|
|
608
|
+
* validate('14:30:00'); // ok("14:30:00")
|
|
609
|
+
* validate('14:30:00Z'); // ok("14:30:00Z")
|
|
610
|
+
* validate('14:30:00+05:30'); // ok("14:30:00+05:30")
|
|
611
|
+
* validate('25:00:00'); // err([{ path: [], message: 'Invalid ISO time format' }])
|
|
612
|
+
*
|
|
613
|
+
* @param message - Custom error message
|
|
614
|
+
* @returns A validator that checks if a string is a valid ISO time
|
|
615
|
+
*/
|
|
364
616
|
function isoTime(message = "Invalid ISO time format") {
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
}
|
|
617
|
+
const isoTimeRegex = /^(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|([+-])(\d{2}):(\d{2}))?$/;
|
|
618
|
+
return (value, path = []) => {
|
|
619
|
+
const match = isoTimeRegex.exec(value);
|
|
620
|
+
if (!match) return err([{
|
|
621
|
+
path,
|
|
622
|
+
message
|
|
623
|
+
}]);
|
|
624
|
+
const hours = Number(match[1]);
|
|
625
|
+
const minutes = Number(match[2]);
|
|
626
|
+
const seconds = Number(match[3]);
|
|
627
|
+
if (hours > 23 || minutes > 59 || seconds > 59) return err([{
|
|
628
|
+
path,
|
|
629
|
+
message
|
|
630
|
+
}]);
|
|
631
|
+
if (match[4]) {
|
|
632
|
+
const tzHours = Number(match[5]);
|
|
633
|
+
const tzMinutes = Number(match[6]);
|
|
634
|
+
if (tzHours > 23 || tzMinutes > 59) return err([{
|
|
635
|
+
path,
|
|
636
|
+
message
|
|
637
|
+
}]);
|
|
638
|
+
}
|
|
639
|
+
return ok(value);
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* Create a validator that ensures a string is a valid ISO 8601 / RFC 3339 datetime.
|
|
644
|
+
* Format: `YYYY-MM-DDTHH:mm:ss[.fractional][Z|±HH:mm]`.
|
|
645
|
+
*
|
|
646
|
+
* @example
|
|
647
|
+
* const validate = isoDateTime();
|
|
648
|
+
* validate('2024-01-15T14:30:00Z'); // ok(...)
|
|
649
|
+
* validate('2024-01-15T14:30:00+05:30'); // ok(...)
|
|
650
|
+
* validate('2024-02-30T14:30:00Z'); // err([{ path: [], message: 'Invalid ISO datetime format' }])
|
|
651
|
+
*
|
|
652
|
+
* @param message - Custom error message
|
|
653
|
+
* @returns A validator that checks if a string is a valid ISO datetime
|
|
654
|
+
*/
|
|
387
655
|
function isoDateTime(message = "Invalid ISO datetime format") {
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
}
|
|
656
|
+
const isoDateTimeRegex = /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|([+-])(\d{2}):(\d{2}))?$/;
|
|
657
|
+
return (value, path = []) => {
|
|
658
|
+
const match = isoDateTimeRegex.exec(value);
|
|
659
|
+
if (!match) return err([{
|
|
660
|
+
path,
|
|
661
|
+
message
|
|
662
|
+
}]);
|
|
663
|
+
const datePart = match[1];
|
|
664
|
+
const date = /* @__PURE__ */ new Date(datePart + "T00:00:00Z");
|
|
665
|
+
if (Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== datePart) return err([{
|
|
666
|
+
path,
|
|
667
|
+
message
|
|
668
|
+
}]);
|
|
669
|
+
const hours = Number(match[2]);
|
|
670
|
+
const minutes = Number(match[3]);
|
|
671
|
+
const seconds = Number(match[4]);
|
|
672
|
+
if (hours > 23 || minutes > 59 || seconds > 59) return err([{
|
|
673
|
+
path,
|
|
674
|
+
message
|
|
675
|
+
}]);
|
|
676
|
+
if (match[5]) {
|
|
677
|
+
const tzHours = Number(match[6]);
|
|
678
|
+
const tzMinutes = Number(match[7]);
|
|
679
|
+
if (tzHours > 23 || tzMinutes > 59) return err([{
|
|
680
|
+
path,
|
|
681
|
+
message
|
|
682
|
+
}]);
|
|
683
|
+
}
|
|
684
|
+
return ok(value);
|
|
685
|
+
};
|
|
686
|
+
}
|
|
687
|
+
/**
|
|
688
|
+
* Create a validator that ensures a string is a valid ISO 8601 duration.
|
|
689
|
+
* Format: `PnYnMnDTnHnMnS` or `PnW`.
|
|
690
|
+
*
|
|
691
|
+
* @example
|
|
692
|
+
* const validate = isoDuration();
|
|
693
|
+
* validate('P1Y2M3D'); // ok("P1Y2M3D")
|
|
694
|
+
* validate('PT1H30M'); // ok("PT1H30M")
|
|
695
|
+
* validate('P4W'); // ok("P4W")
|
|
696
|
+
* validate('P'); // err([{ path: [], message: 'Invalid ISO duration format' }])
|
|
697
|
+
*
|
|
698
|
+
* @param message - Custom error message
|
|
699
|
+
* @returns A validator that checks if a string is a valid ISO duration
|
|
700
|
+
*/
|
|
415
701
|
function isoDuration(message = "Invalid ISO duration format") {
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
702
|
+
const isoDurationRegex = /^P(?:\d+W|(?:\d+Y)?(?:\d+M)?(?:\d+D)?(?:T(?:\d+H)?(?:\d+M)?(?:\d+(?:\.\d+)?S)?)?)$/;
|
|
703
|
+
return (value, path = []) => {
|
|
704
|
+
if (!isoDurationRegex.test(value) || value === "P" || value.endsWith("T")) return err([{
|
|
705
|
+
path,
|
|
706
|
+
message
|
|
707
|
+
}]);
|
|
708
|
+
return ok(value);
|
|
709
|
+
};
|
|
423
710
|
}
|
|
424
|
-
|
|
425
711
|
// src/schema/array.ts
|
|
426
712
|
function array(itemValidator) {
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
713
|
+
return (value, parentPath = []) => {
|
|
714
|
+
if (!Array.isArray(value)) return err([{
|
|
715
|
+
path: parentPath,
|
|
716
|
+
message: "Expected an array"
|
|
717
|
+
}]);
|
|
718
|
+
const abortEarly = _getAbortEarly();
|
|
719
|
+
const allErrors = [];
|
|
720
|
+
const validatedItems = Array.from({ length: value.length });
|
|
721
|
+
const pendingResults = [];
|
|
722
|
+
for (const [i, item] of value.entries()) {
|
|
723
|
+
if (abortEarly && allErrors.length > 0) break;
|
|
724
|
+
const result = itemValidator(item, [...parentPath, i.toString()]);
|
|
725
|
+
if (result instanceof Promise) {
|
|
726
|
+
if (abortEarly && allErrors.length > 0) continue;
|
|
727
|
+
const index = i;
|
|
728
|
+
pendingResults.push(result.then((r) => {
|
|
729
|
+
if (isOk(r)) validatedItems[index] = r.value;
|
|
730
|
+
else allErrors.push(...r.error);
|
|
731
|
+
}));
|
|
732
|
+
} else if (isOk(result)) validatedItems[i] = result.value;
|
|
733
|
+
else {
|
|
734
|
+
allErrors.push(...result.error);
|
|
735
|
+
if (abortEarly) break;
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
if (pendingResults.length > 0) return Promise.all(pendingResults).then(() => {
|
|
739
|
+
if (allErrors.length > 0) return err(allErrors);
|
|
740
|
+
return ok(validatedItems);
|
|
741
|
+
});
|
|
742
|
+
if (allErrors.length > 0) return err(allErrors);
|
|
743
|
+
return ok(validatedItems);
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* Validate that an array has at least a minimum number of items.
|
|
748
|
+
*
|
|
749
|
+
* @example
|
|
750
|
+
* const validate = minItems(2);
|
|
751
|
+
* validate([1, 2, 3]); // ok([1, 2, 3])
|
|
752
|
+
* validate([1]); // err([{ path: [], message: 'Array must have at least 2 items' }])
|
|
753
|
+
*
|
|
754
|
+
* @param min - The minimum number of items required
|
|
755
|
+
* @param message - Custom error message
|
|
756
|
+
* @returns A validator that checks minimum array length
|
|
757
|
+
*/
|
|
758
|
+
function minItems(min, message = `Array must have at least ${min} items`) {
|
|
759
|
+
return (value, path = []) => {
|
|
760
|
+
if (value.length < min) return err([{
|
|
761
|
+
path,
|
|
762
|
+
message
|
|
763
|
+
}]);
|
|
764
|
+
return ok(value);
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* Validate that an array has at most a maximum number of items.
|
|
769
|
+
*
|
|
770
|
+
* @example
|
|
771
|
+
* const validate = maxItems(2);
|
|
772
|
+
* validate([1, 2]); // ok([1, 2])
|
|
773
|
+
* validate([1, 2, 3]); // err([{ path: [], message: 'Array must have at most 2 items' }])
|
|
774
|
+
*
|
|
775
|
+
* @param max - The maximum number of items allowed
|
|
776
|
+
* @param message - Custom error message
|
|
777
|
+
* @returns A validator that checks maximum array length
|
|
778
|
+
*/
|
|
779
|
+
function maxItems(max, message = `Array must have at most ${max} items`) {
|
|
780
|
+
return (value, path = []) => {
|
|
781
|
+
if (value.length > max) return err([{
|
|
782
|
+
path,
|
|
783
|
+
message
|
|
784
|
+
}]);
|
|
785
|
+
return ok(value);
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
/**
|
|
789
|
+
* Validate that an array is not empty.
|
|
790
|
+
*
|
|
791
|
+
* @example
|
|
792
|
+
* const validate = notEmpty();
|
|
793
|
+
* validate([1]); // ok([1])
|
|
794
|
+
* validate([]); // err([{ path: [], message: 'Array must not be empty' }])
|
|
795
|
+
*
|
|
796
|
+
* @param message - Custom error message
|
|
797
|
+
* @returns A validator that checks the array is not empty
|
|
798
|
+
*/
|
|
484
799
|
function notEmpty(message = "Array must not be empty") {
|
|
485
|
-
|
|
486
|
-
}
|
|
800
|
+
return minItems(1, message);
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* Validate that an array contains only unique values.
|
|
804
|
+
*
|
|
805
|
+
* @example
|
|
806
|
+
* const validate = unique();
|
|
807
|
+
* validate([1, 2, 3]); // ok([1, 2, 3])
|
|
808
|
+
* validate([1, 2, 2, 3]); // err([{ path: ['2'], message: 'Array must contain unique values' }])
|
|
809
|
+
*
|
|
810
|
+
* @example
|
|
811
|
+
* // With custom key extractor for objects
|
|
812
|
+
* const validate = unique<{ id: number }>('Duplicate ID', (item) => item.id);
|
|
813
|
+
*
|
|
814
|
+
* @param message - Custom error message
|
|
815
|
+
* @param keyExtractor - Optional function to extract a comparison key from each item
|
|
816
|
+
* @returns A validator that checks for unique array values
|
|
817
|
+
*/
|
|
487
818
|
function unique(message = "Array must contain unique values", keyExtractor) {
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
819
|
+
return (value, path = []) => {
|
|
820
|
+
const seen = /* @__PURE__ */ new Set();
|
|
821
|
+
for (const [i, item] of value.entries()) {
|
|
822
|
+
const key = keyExtractor ? keyExtractor(item) : item;
|
|
823
|
+
if (seen.has(key)) return err([{
|
|
824
|
+
path: [...path, i.toString()],
|
|
825
|
+
message
|
|
826
|
+
}]);
|
|
827
|
+
seen.add(key);
|
|
828
|
+
}
|
|
829
|
+
return ok(value);
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
/**
|
|
833
|
+
* Create a validator that ensures a value is one of the allowed values.
|
|
834
|
+
*
|
|
835
|
+
* @example
|
|
836
|
+
* const validate = oneOf(['pending', 'approved', 'rejected']);
|
|
837
|
+
* validate('approved'); // ok("approved")
|
|
838
|
+
* validate('unknown'); // err([{ path: [], message: 'Value must be one of: pending, approved, rejected' }])
|
|
839
|
+
*
|
|
840
|
+
* @param allowedValues - Array of acceptable values
|
|
841
|
+
* @param message - Custom error message
|
|
842
|
+
* @returns A validator that checks if a value is in the allowed list
|
|
843
|
+
*/
|
|
505
844
|
function oneOf(allowedValues, message = `Value must be one of: ${allowedValues.join(", ")}`) {
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
}
|
|
845
|
+
return (value, path = []) => {
|
|
846
|
+
if (!allowedValues.includes(value)) return err([{
|
|
847
|
+
path,
|
|
848
|
+
message
|
|
849
|
+
}]);
|
|
850
|
+
return ok(value);
|
|
851
|
+
};
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* Create a validator that ensures a value is a string and one of the allowed enum values.
|
|
855
|
+
*
|
|
856
|
+
* @example
|
|
857
|
+
* const validate = stringEnum(['admin', 'user']);
|
|
858
|
+
* validate('admin'); // ok("admin")
|
|
859
|
+
* validate(42); // err([{ path: [], message: 'Value must be a string' }])
|
|
860
|
+
* validate('other'); // err([{ path: [], message: 'Value must be one of: admin, user' }])
|
|
861
|
+
*
|
|
862
|
+
* @param allowedValues - Array of acceptable string enum values
|
|
863
|
+
* @param message - Custom error message
|
|
864
|
+
* @returns A validator that checks if a value is a string and in the allowed list
|
|
865
|
+
*/
|
|
513
866
|
function stringEnum(allowedValues, message = `Value must be one of: ${allowedValues.join(", ")}`) {
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
867
|
+
return chain(string("Value must be a string"), (value, path = []) => {
|
|
868
|
+
if (!allowedValues.includes(value)) return err([{
|
|
869
|
+
path,
|
|
870
|
+
message
|
|
871
|
+
}]);
|
|
872
|
+
return ok(value);
|
|
873
|
+
});
|
|
520
874
|
}
|
|
521
|
-
|
|
522
875
|
// src/schema/tuple.ts
|
|
523
876
|
function tuple(validators) {
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
if (abortEarly) break;
|
|
562
|
-
}
|
|
563
|
-
}
|
|
564
|
-
if (pendingResults.length > 0) {
|
|
565
|
-
return Promise.all(pendingResults).then(() => {
|
|
566
|
-
if (allErrors.length > 0) return err(allErrors);
|
|
567
|
-
return ok(validatedItems);
|
|
568
|
-
});
|
|
569
|
-
}
|
|
570
|
-
if (allErrors.length > 0) return err(allErrors);
|
|
571
|
-
return ok(validatedItems);
|
|
572
|
-
};
|
|
877
|
+
return (value, parentPath = []) => {
|
|
878
|
+
if (!Array.isArray(value)) return err([{
|
|
879
|
+
path: parentPath,
|
|
880
|
+
message: "Expected an array"
|
|
881
|
+
}]);
|
|
882
|
+
if (value.length !== validators.length) return err([{
|
|
883
|
+
path: parentPath,
|
|
884
|
+
message: `Expected tuple of length ${validators.length}, got ${value.length}`
|
|
885
|
+
}]);
|
|
886
|
+
const abortEarly = _getAbortEarly();
|
|
887
|
+
const allErrors = [];
|
|
888
|
+
const validatedItems = Array.from({ length: validators.length });
|
|
889
|
+
const pendingResults = [];
|
|
890
|
+
for (const [i, validator] of validators.entries()) {
|
|
891
|
+
if (abortEarly && allErrors.length > 0) break;
|
|
892
|
+
const itemPath = [...parentPath, i.toString()];
|
|
893
|
+
const result = validator(value.at(i), itemPath);
|
|
894
|
+
if (result instanceof Promise) {
|
|
895
|
+
if (abortEarly && allErrors.length > 0) continue;
|
|
896
|
+
const index = i;
|
|
897
|
+
pendingResults.push(result.then((r) => {
|
|
898
|
+
if (isOk(r)) validatedItems[index] = r.value;
|
|
899
|
+
else allErrors.push(...r.error);
|
|
900
|
+
}));
|
|
901
|
+
} else if (isOk(result)) validatedItems[i] = result.value;
|
|
902
|
+
else {
|
|
903
|
+
allErrors.push(...result.error);
|
|
904
|
+
if (abortEarly) break;
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
if (pendingResults.length > 0) return Promise.all(pendingResults).then(() => {
|
|
908
|
+
if (allErrors.length > 0) return err(allErrors);
|
|
909
|
+
return ok(validatedItems);
|
|
910
|
+
});
|
|
911
|
+
if (allErrors.length > 0) return err(allErrors);
|
|
912
|
+
return ok(validatedItems);
|
|
913
|
+
};
|
|
573
914
|
}
|
|
574
915
|
function tupleOf(elementValidator, length) {
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
if (abortEarly) break;
|
|
612
|
-
}
|
|
613
|
-
}
|
|
614
|
-
if (pendingResults.length > 0) {
|
|
615
|
-
return Promise.all(pendingResults).then(() => {
|
|
616
|
-
if (allErrors.length > 0) return err(allErrors);
|
|
617
|
-
return ok(validatedItems);
|
|
618
|
-
});
|
|
619
|
-
}
|
|
620
|
-
if (allErrors.length > 0) return err(allErrors);
|
|
621
|
-
return ok(validatedItems);
|
|
622
|
-
};
|
|
916
|
+
return (value, parentPath = []) => {
|
|
917
|
+
if (!Array.isArray(value)) return err([{
|
|
918
|
+
path: parentPath,
|
|
919
|
+
message: "Expected an array"
|
|
920
|
+
}]);
|
|
921
|
+
if (value.length !== length) return err([{
|
|
922
|
+
path: parentPath,
|
|
923
|
+
message: `Expected tuple of length ${length}, got ${value.length}`
|
|
924
|
+
}]);
|
|
925
|
+
const abortEarly = _getAbortEarly();
|
|
926
|
+
const allErrors = [];
|
|
927
|
+
const validatedItems = Array.from({ length });
|
|
928
|
+
const pendingResults = [];
|
|
929
|
+
for (const [i, item] of value.entries()) {
|
|
930
|
+
if (abortEarly && allErrors.length > 0) break;
|
|
931
|
+
const result = elementValidator(item, [...parentPath, i.toString()]);
|
|
932
|
+
if (result instanceof Promise) {
|
|
933
|
+
if (abortEarly && allErrors.length > 0) continue;
|
|
934
|
+
const index = i;
|
|
935
|
+
pendingResults.push(result.then((r) => {
|
|
936
|
+
if (isOk(r)) validatedItems[index] = r.value;
|
|
937
|
+
else allErrors.push(...r.error);
|
|
938
|
+
}));
|
|
939
|
+
} else if (isOk(result)) validatedItems[i] = result.value;
|
|
940
|
+
else {
|
|
941
|
+
allErrors.push(...result.error);
|
|
942
|
+
if (abortEarly) break;
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
if (pendingResults.length > 0) return Promise.all(pendingResults).then(() => {
|
|
946
|
+
if (allErrors.length > 0) return err(allErrors);
|
|
947
|
+
return ok(validatedItems);
|
|
948
|
+
});
|
|
949
|
+
if (allErrors.length > 0) return err(allErrors);
|
|
950
|
+
return ok(validatedItems);
|
|
951
|
+
};
|
|
623
952
|
}
|
|
624
|
-
|
|
625
953
|
// src/schema/number.ts
|
|
954
|
+
/**
|
|
955
|
+
* Create a validator that ensures a value is a number and not NaN.
|
|
956
|
+
*
|
|
957
|
+
* @example
|
|
958
|
+
* const validate = number();
|
|
959
|
+
* validate(25); // ok(25)
|
|
960
|
+
* validate('not a number'); // err([{ path: [], message: 'Must be a number' }])
|
|
961
|
+
*
|
|
962
|
+
* @param message - Custom error message
|
|
963
|
+
* @returns A validator that checks if a value is a number
|
|
964
|
+
*/
|
|
626
965
|
function number(message = "Must be a number") {
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
}
|
|
966
|
+
return (value, path = []) => {
|
|
967
|
+
if (typeof value !== "number" || Number.isNaN(value)) return err([{
|
|
968
|
+
path,
|
|
969
|
+
message
|
|
970
|
+
}]);
|
|
971
|
+
return ok(value);
|
|
972
|
+
};
|
|
973
|
+
}
|
|
974
|
+
/**
|
|
975
|
+
* Create a validator that ensures a number is at least a minimum value.
|
|
976
|
+
*
|
|
977
|
+
* @example
|
|
978
|
+
* const validate = min(18);
|
|
979
|
+
* validate(21); // ok(21)
|
|
980
|
+
* validate(16); // err([{ path: [], message: 'Must be at least 18' }])
|
|
981
|
+
*
|
|
982
|
+
* @param value - The minimum value (inclusive)
|
|
983
|
+
* @param message - Custom error message
|
|
984
|
+
* @returns A validator that checks if a number is at least the minimum
|
|
985
|
+
*/
|
|
634
986
|
function min(value, message = `Must be at least ${value}`) {
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
}
|
|
987
|
+
return (input, path = []) => {
|
|
988
|
+
if (input < value) return err([{
|
|
989
|
+
path,
|
|
990
|
+
message
|
|
991
|
+
}]);
|
|
992
|
+
return ok(input);
|
|
993
|
+
};
|
|
994
|
+
}
|
|
995
|
+
/**
|
|
996
|
+
* Create a validator that ensures a number is at most a maximum value.
|
|
997
|
+
*
|
|
998
|
+
* @example
|
|
999
|
+
* const validate = max(100);
|
|
1000
|
+
* validate(75); // ok(75)
|
|
1001
|
+
* validate(150); // err([{ path: [], message: 'Must be at most 100' }])
|
|
1002
|
+
*
|
|
1003
|
+
* @param value - The maximum value (inclusive)
|
|
1004
|
+
* @param message - Custom error message
|
|
1005
|
+
* @returns A validator that checks if a number is at most the maximum
|
|
1006
|
+
*/
|
|
642
1007
|
function max(value, message = `Must be at most ${value}`) {
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
}
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
}
|
|
1008
|
+
return (input, path = []) => {
|
|
1009
|
+
if (input > value) return err([{
|
|
1010
|
+
path,
|
|
1011
|
+
message
|
|
1012
|
+
}]);
|
|
1013
|
+
return ok(input);
|
|
1014
|
+
};
|
|
1015
|
+
}
|
|
1016
|
+
/**
|
|
1017
|
+
* Create a validator that ensures a number is between a minimum and maximum (inclusive).
|
|
1018
|
+
*
|
|
1019
|
+
* @example
|
|
1020
|
+
* const validate = between(1, 10);
|
|
1021
|
+
* validate(7); // ok(7)
|
|
1022
|
+
* validate(15); // err([{ path: [], message: 'Must be between 1 and 10' }])
|
|
1023
|
+
*
|
|
1024
|
+
* @param min - The minimum value (inclusive)
|
|
1025
|
+
* @param max - The maximum value (inclusive)
|
|
1026
|
+
* @param message - Custom error message
|
|
1027
|
+
* @returns A validator that checks if a number is between min and max
|
|
1028
|
+
*/
|
|
1029
|
+
function between(min, max, message = `Must be between ${min} and ${max}`) {
|
|
1030
|
+
return (input, path = []) => {
|
|
1031
|
+
if (input < min || input > max) return err([{
|
|
1032
|
+
path,
|
|
1033
|
+
message
|
|
1034
|
+
}]);
|
|
1035
|
+
return ok(input);
|
|
1036
|
+
};
|
|
1037
|
+
}
|
|
1038
|
+
/**
|
|
1039
|
+
* Create a validator that ensures a number is an integer.
|
|
1040
|
+
*
|
|
1041
|
+
* @example
|
|
1042
|
+
* const validate = integer();
|
|
1043
|
+
* validate(42); // ok(42)
|
|
1044
|
+
* validate(3.14); // err([{ path: [], message: 'Must be an integer' }])
|
|
1045
|
+
*
|
|
1046
|
+
* @param message - Custom error message
|
|
1047
|
+
* @returns A validator that checks if a number is an integer
|
|
1048
|
+
*/
|
|
658
1049
|
function integer(message = "Must be an integer") {
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
}
|
|
1050
|
+
return (value, path = []) => {
|
|
1051
|
+
if (!Number.isInteger(value)) return err([{
|
|
1052
|
+
path,
|
|
1053
|
+
message
|
|
1054
|
+
}]);
|
|
1055
|
+
return ok(value);
|
|
1056
|
+
};
|
|
1057
|
+
}
|
|
1058
|
+
/**
|
|
1059
|
+
* Create a validator that ensures a number is positive (greater than zero).
|
|
1060
|
+
*
|
|
1061
|
+
* @example
|
|
1062
|
+
* const validate = positive();
|
|
1063
|
+
* validate(29.99); // ok(29.99)
|
|
1064
|
+
* validate(0); // err([{ path: [], message: 'Must be a positive number' }])
|
|
1065
|
+
*
|
|
1066
|
+
* @param message - Custom error message
|
|
1067
|
+
* @returns A validator that checks if a number is positive
|
|
1068
|
+
*/
|
|
666
1069
|
function positive(message = "Must be a positive number") {
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
}
|
|
1070
|
+
return (value, path = []) => {
|
|
1071
|
+
if (value <= 0) return err([{
|
|
1072
|
+
path,
|
|
1073
|
+
message
|
|
1074
|
+
}]);
|
|
1075
|
+
return ok(value);
|
|
1076
|
+
};
|
|
1077
|
+
}
|
|
1078
|
+
/**
|
|
1079
|
+
* Create a validator that ensures a number is negative (less than zero).
|
|
1080
|
+
*
|
|
1081
|
+
* @example
|
|
1082
|
+
* const validate = negative();
|
|
1083
|
+
* validate(-5); // ok(-5)
|
|
1084
|
+
* validate(0); // err([{ path: [], message: 'Must be a negative number' }])
|
|
1085
|
+
*
|
|
1086
|
+
* @param message - Custom error message
|
|
1087
|
+
* @returns A validator that checks if a number is negative
|
|
1088
|
+
*/
|
|
674
1089
|
function negative(message = "Must be a negative number") {
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
}
|
|
1090
|
+
return (value, path = []) => {
|
|
1091
|
+
if (value >= 0) return err([{
|
|
1092
|
+
path,
|
|
1093
|
+
message
|
|
1094
|
+
}]);
|
|
1095
|
+
return ok(value);
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
/**
|
|
1099
|
+
* Create a validator that ensures a number is not zero.
|
|
1100
|
+
*
|
|
1101
|
+
* @example
|
|
1102
|
+
* const validate = nonZero();
|
|
1103
|
+
* validate(5); // ok(5)
|
|
1104
|
+
* validate(0); // err([{ path: [], message: 'Must not be zero' }])
|
|
1105
|
+
*
|
|
1106
|
+
* @param message - Custom error message
|
|
1107
|
+
* @returns A validator that checks if a number is not zero
|
|
1108
|
+
*/
|
|
682
1109
|
function nonZero(message = "Must not be zero") {
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
}
|
|
1110
|
+
return (value, path = []) => {
|
|
1111
|
+
if (value === 0) return err([{
|
|
1112
|
+
path,
|
|
1113
|
+
message
|
|
1114
|
+
}]);
|
|
1115
|
+
return ok(value);
|
|
1116
|
+
};
|
|
1117
|
+
}
|
|
1118
|
+
/**
|
|
1119
|
+
* Create a validator that ensures a number is divisible by a specific divisor.
|
|
1120
|
+
*
|
|
1121
|
+
* @example
|
|
1122
|
+
* const validate = divisibleBy(5);
|
|
1123
|
+
* validate(15); // ok(15)
|
|
1124
|
+
* validate(12); // err([{ path: [], message: 'Must be divisible by 5' }])
|
|
1125
|
+
*
|
|
1126
|
+
* @param divisor - The number that the input must be divisible by
|
|
1127
|
+
* @param message - Custom error message
|
|
1128
|
+
* @returns A validator that checks if a number is divisible by the divisor
|
|
1129
|
+
*/
|
|
690
1130
|
function divisibleBy(divisor, message = `Must be divisible by ${divisor}`) {
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
}
|
|
1131
|
+
return (value, path = []) => {
|
|
1132
|
+
if (value % divisor !== 0) return err([{
|
|
1133
|
+
path,
|
|
1134
|
+
message
|
|
1135
|
+
}]);
|
|
1136
|
+
return ok(value);
|
|
1137
|
+
};
|
|
1138
|
+
}
|
|
1139
|
+
/**
|
|
1140
|
+
* Create a validator that ensures a number has at most the specified decimal places.
|
|
1141
|
+
*
|
|
1142
|
+
* @example
|
|
1143
|
+
* const validate = precision(2);
|
|
1144
|
+
* validate(10.99); // ok(10.99)
|
|
1145
|
+
* validate(10.999); // err([{ path: [], message: 'Must have at most 2 decimal places' }])
|
|
1146
|
+
*
|
|
1147
|
+
* @param maxDecimalPlaces - The maximum number of decimal places allowed
|
|
1148
|
+
* @param message - Custom error message
|
|
1149
|
+
* @returns A validator that checks the number's decimal precision
|
|
1150
|
+
*/
|
|
698
1151
|
function precision(maxDecimalPlaces, message = `Must have at most ${maxDecimalPlaces} decimal places`) {
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
1152
|
+
return (value, path = []) => {
|
|
1153
|
+
if ((value.toString().split(".", 2)[1] || "").length > maxDecimalPlaces) return err([{
|
|
1154
|
+
path,
|
|
1155
|
+
message
|
|
1156
|
+
}]);
|
|
1157
|
+
return ok(value);
|
|
1158
|
+
};
|
|
1159
|
+
}
|
|
1160
|
+
/**
|
|
1161
|
+
* Create a validator that ensures a number is finite (not Infinity or -Infinity).
|
|
1162
|
+
*
|
|
1163
|
+
* @example
|
|
1164
|
+
* const validate = finite();
|
|
1165
|
+
* validate(42); // ok(42)
|
|
1166
|
+
* validate(Infinity); // err([{ path: [], message: 'Must be a finite number' }])
|
|
1167
|
+
*
|
|
1168
|
+
* @param message - Custom error message
|
|
1169
|
+
* @returns A validator that checks if a number is finite
|
|
1170
|
+
*/
|
|
708
1171
|
function finite(message = "Must be a finite number") {
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
1172
|
+
return (value, path = []) => {
|
|
1173
|
+
if (!Number.isFinite(value)) return err([{
|
|
1174
|
+
path,
|
|
1175
|
+
message
|
|
1176
|
+
}]);
|
|
1177
|
+
return ok(value);
|
|
1178
|
+
};
|
|
715
1179
|
}
|
|
716
|
-
|
|
717
1180
|
// src/schema/parsers.ts
|
|
1181
|
+
/**
|
|
1182
|
+
* Create a validator that parses input into a number.
|
|
1183
|
+
* Accepts both numbers and string representations of numbers.
|
|
1184
|
+
*
|
|
1185
|
+
* @example
|
|
1186
|
+
* const validate = parseNumber();
|
|
1187
|
+
* validate('25'); // ok(25)
|
|
1188
|
+
* validate(42); // ok(42)
|
|
1189
|
+
* validate('not a number'); // err([{ path: [], message: 'Must be a valid number' }])
|
|
1190
|
+
*
|
|
1191
|
+
* @param message - Custom error message
|
|
1192
|
+
* @returns A validator that parses and validates numbers
|
|
1193
|
+
*/
|
|
718
1194
|
function parseNumber(message = "Must be a valid number") {
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
}
|
|
1195
|
+
return (value, path = []) => {
|
|
1196
|
+
if (typeof value === "number") return ok(value);
|
|
1197
|
+
if (typeof value === "string") {
|
|
1198
|
+
const trimmed = value.trim();
|
|
1199
|
+
if (trimmed === "") return err([{
|
|
1200
|
+
path,
|
|
1201
|
+
message
|
|
1202
|
+
}]);
|
|
1203
|
+
const num = Number(trimmed);
|
|
1204
|
+
if (!Number.isNaN(num)) return ok(num);
|
|
1205
|
+
}
|
|
1206
|
+
return err([{
|
|
1207
|
+
path,
|
|
1208
|
+
message
|
|
1209
|
+
}]);
|
|
1210
|
+
};
|
|
1211
|
+
}
|
|
1212
|
+
/**
|
|
1213
|
+
* Create a validator that parses input into a BigInt.
|
|
1214
|
+
* Accepts BigInt values, strings, and integer numbers.
|
|
1215
|
+
*
|
|
1216
|
+
* @example
|
|
1217
|
+
* const validate = parseBigInt();
|
|
1218
|
+
* validate("9007199254740993"); // ok(9007199254740993n)
|
|
1219
|
+
* validate(123n); // ok(123n)
|
|
1220
|
+
* validate(42); // ok(42n)
|
|
1221
|
+
*
|
|
1222
|
+
* @param message - Custom error message
|
|
1223
|
+
* @returns A validator that parses and validates BigInt values
|
|
1224
|
+
*/
|
|
736
1225
|
function parseBigInt(message = "Must be a valid BigInt") {
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
1226
|
+
return (value, path = []) => {
|
|
1227
|
+
if (typeof value === "bigint") return ok(value);
|
|
1228
|
+
if (typeof value === "string" || typeof value === "number") try {
|
|
1229
|
+
if (typeof value === "number" && !Number.isInteger(value)) return err([{
|
|
1230
|
+
path,
|
|
1231
|
+
message: "Cannot convert non-integer number to BigInt"
|
|
1232
|
+
}]);
|
|
1233
|
+
const bigIntValue = BigInt(value);
|
|
1234
|
+
return ok(bigIntValue);
|
|
1235
|
+
} catch {
|
|
1236
|
+
return err([{
|
|
1237
|
+
path,
|
|
1238
|
+
message
|
|
1239
|
+
}]);
|
|
1240
|
+
}
|
|
1241
|
+
return err([{
|
|
1242
|
+
path,
|
|
1243
|
+
message
|
|
1244
|
+
}]);
|
|
1245
|
+
};
|
|
1246
|
+
}
|
|
1247
|
+
/**
|
|
1248
|
+
* Create a validator that parses input into enum values.
|
|
1249
|
+
* Handles string/number to enum conversions with flexible matching.
|
|
1250
|
+
*
|
|
1251
|
+
* @example
|
|
1252
|
+
* enum Status { Pending = "PENDING", Approved = "APPROVED" }
|
|
1253
|
+
* const validate = parseEnum(Status);
|
|
1254
|
+
* validate("PENDING"); // ok("PENDING")
|
|
1255
|
+
* validate("pending"); // ok("PENDING") — case-insensitive key match
|
|
1256
|
+
*
|
|
1257
|
+
* @param enumObject - The enum object to parse values into
|
|
1258
|
+
* @param message - Custom error message
|
|
1259
|
+
* @returns A validator that parses to enum values
|
|
1260
|
+
*/
|
|
760
1261
|
function parseEnum(enumObject, message = `Must be a valid enum value`) {
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
1262
|
+
return (value, path = []) => {
|
|
1263
|
+
const enumEntries = Object.entries(enumObject).filter(([key]) => Number.isNaN(Number(key)) || !Number.isInteger(Number(key)));
|
|
1264
|
+
const enumValues = enumEntries.map(([, val]) => val);
|
|
1265
|
+
if (enumValues.includes(value)) return ok(value);
|
|
1266
|
+
if (typeof value === "string") {
|
|
1267
|
+
const parsed = Number(value);
|
|
1268
|
+
if (!Number.isNaN(parsed) && enumValues.includes(parsed)) return ok(parsed);
|
|
1269
|
+
const exactEntry = enumEntries.find(([key]) => key === value);
|
|
1270
|
+
if (exactEntry) return ok(exactEntry[1]);
|
|
1271
|
+
const lowerValue = value.toLowerCase();
|
|
1272
|
+
const caseInsensitiveEntry = enumEntries.find(([key]) => key.toLowerCase() === lowerValue);
|
|
1273
|
+
if (caseInsensitiveEntry) return ok(caseInsensitiveEntry[1]);
|
|
1274
|
+
}
|
|
1275
|
+
return err([{
|
|
1276
|
+
path,
|
|
1277
|
+
message
|
|
1278
|
+
}]);
|
|
1279
|
+
};
|
|
1280
|
+
}
|
|
1281
|
+
/**
|
|
1282
|
+
* Create a validator that parses input into a Date object.
|
|
1283
|
+
* Accepts Date objects, date strings, and numeric timestamps.
|
|
1284
|
+
*
|
|
1285
|
+
* @example
|
|
1286
|
+
* const validate = parseDate();
|
|
1287
|
+
* validate('1990-05-15'); // ok(Date)
|
|
1288
|
+
* validate(1621036800000); // ok(Date)
|
|
1289
|
+
* validate('not a date'); // err([{ path: [], message: 'Must be a valid date' }])
|
|
1290
|
+
*
|
|
1291
|
+
* @param message - Custom error message
|
|
1292
|
+
* @returns A validator that parses and validates dates
|
|
1293
|
+
*/
|
|
792
1294
|
function parseDate(message = "Must be a valid date") {
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
1295
|
+
return (value, path = []) => {
|
|
1296
|
+
if (value instanceof Date) return ok(value);
|
|
1297
|
+
let dateValue;
|
|
1298
|
+
if (typeof value === "string" || typeof value === "number") dateValue = new Date(value);
|
|
1299
|
+
else return err([{
|
|
1300
|
+
path,
|
|
1301
|
+
message
|
|
1302
|
+
}]);
|
|
1303
|
+
if (Number.isNaN(dateValue.getTime())) return err([{
|
|
1304
|
+
path,
|
|
1305
|
+
message
|
|
1306
|
+
}]);
|
|
1307
|
+
return ok(dateValue);
|
|
1308
|
+
};
|
|
1309
|
+
}
|
|
1310
|
+
/**
|
|
1311
|
+
* Create a validator that parses input into a boolean.
|
|
1312
|
+
* Accepts booleans, 0/1, and strings like 'true'/'false', 'yes'/'no'.
|
|
1313
|
+
*
|
|
1314
|
+
* @example
|
|
1315
|
+
* const validate = parseBool();
|
|
1316
|
+
* validate('yes'); // ok(true)
|
|
1317
|
+
* validate('false'); // ok(false)
|
|
1318
|
+
* validate(1); // ok(true)
|
|
1319
|
+
* validate('maybe'); // err([{ path: [], message: 'Must be a valid boolean value' }])
|
|
1320
|
+
*
|
|
1321
|
+
* @param message - Custom error message
|
|
1322
|
+
* @returns A validator that parses and validates booleans
|
|
1323
|
+
*/
|
|
809
1324
|
function parseBool(message = "Must be a valid boolean value") {
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
1325
|
+
return (value, path = []) => {
|
|
1326
|
+
if (typeof value === "boolean") return ok(value);
|
|
1327
|
+
if (typeof value === "string") {
|
|
1328
|
+
const normalized = value.toLowerCase().trim();
|
|
1329
|
+
if ([
|
|
1330
|
+
"true",
|
|
1331
|
+
"1",
|
|
1332
|
+
"yes"
|
|
1333
|
+
].includes(normalized)) return ok(true);
|
|
1334
|
+
if ([
|
|
1335
|
+
"false",
|
|
1336
|
+
"0",
|
|
1337
|
+
"no"
|
|
1338
|
+
].includes(normalized)) return ok(false);
|
|
1339
|
+
}
|
|
1340
|
+
if (typeof value === "number") {
|
|
1341
|
+
if (value === 1) return ok(true);
|
|
1342
|
+
if (value === 0) return ok(false);
|
|
1343
|
+
}
|
|
1344
|
+
return err([{
|
|
1345
|
+
path,
|
|
1346
|
+
message
|
|
1347
|
+
}]);
|
|
1348
|
+
};
|
|
1349
|
+
}
|
|
1350
|
+
/**
|
|
1351
|
+
* Create a validator that parses input into a string.
|
|
1352
|
+
* Accepts strings and any value convertible to string, except null and undefined.
|
|
1353
|
+
*
|
|
1354
|
+
* @example
|
|
1355
|
+
* const validate = parseString();
|
|
1356
|
+
* validate(12345); // ok("12345")
|
|
1357
|
+
* validate('hello'); // ok("hello")
|
|
1358
|
+
* validate(null); // err([{ path: [], message: 'Must be convertible to string' }])
|
|
1359
|
+
*
|
|
1360
|
+
* @param message - Custom error message
|
|
1361
|
+
* @returns A validator that parses and validates strings
|
|
1362
|
+
*/
|
|
830
1363
|
function parseString(message = "Must be convertible to string") {
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
1364
|
+
return (value, path = []) => {
|
|
1365
|
+
if (typeof value === "string") return ok(value);
|
|
1366
|
+
if (value === null || value === void 0) return err([{
|
|
1367
|
+
path,
|
|
1368
|
+
message
|
|
1369
|
+
}]);
|
|
1370
|
+
return ok(String(value));
|
|
1371
|
+
};
|
|
1372
|
+
}
|
|
1373
|
+
/**
|
|
1374
|
+
* Create a validator that parses JSON strings into objects.
|
|
1375
|
+
* Accepts JSON strings or already-parsed objects.
|
|
1376
|
+
*
|
|
1377
|
+
* @example
|
|
1378
|
+
* const validate = parseJSON();
|
|
1379
|
+
* validate('{"name":"John"}'); // ok({ name: "John" })
|
|
1380
|
+
* validate({ name: 'John' }); // ok({ name: "John" })
|
|
1381
|
+
* validate('{invalid}'); // err([{ path: [], message: 'Must be valid JSON' }])
|
|
1382
|
+
*
|
|
1383
|
+
* @param message - Custom error message
|
|
1384
|
+
* @returns A validator that parses and validates JSON
|
|
1385
|
+
*/
|
|
841
1386
|
function parseJSON(message = "Must be valid JSON") {
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
1387
|
+
return (value, path = []) => {
|
|
1388
|
+
if (typeof value === "string") return mapErr(fromTry(() => JSON.parse(value)), () => [{
|
|
1389
|
+
path,
|
|
1390
|
+
message
|
|
1391
|
+
}]);
|
|
1392
|
+
if (typeof value === "object" && value !== null) return ok(value);
|
|
1393
|
+
return err([{
|
|
1394
|
+
path,
|
|
1395
|
+
message
|
|
1396
|
+
}]);
|
|
1397
|
+
};
|
|
1398
|
+
}
|
|
1399
|
+
/**
|
|
1400
|
+
* Create a validator that parses ISO date strings (YYYY-MM-DD) into Date objects.
|
|
1401
|
+
* Performs strict validation of the date format and validity.
|
|
1402
|
+
*
|
|
1403
|
+
* @example
|
|
1404
|
+
* const validate = parseISODate();
|
|
1405
|
+
* validate('2021-05-15'); // ok(Date)
|
|
1406
|
+
* validate('15/05/2021'); // err([{ path: [], message: 'Must be a valid ISO date string' }])
|
|
1407
|
+
* validate('2021-02-30'); // err(...) — invalid calendar date
|
|
1408
|
+
*
|
|
1409
|
+
* @param message - Custom error message
|
|
1410
|
+
* @returns A validator that parses and validates ISO date strings
|
|
1411
|
+
*/
|
|
855
1412
|
function parseISODate(message = "Must be a valid ISO date string") {
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
1413
|
+
return (value, path = []) => {
|
|
1414
|
+
if (typeof value !== "string") return err([{
|
|
1415
|
+
path,
|
|
1416
|
+
message
|
|
1417
|
+
}]);
|
|
1418
|
+
if (!/^\d{4}-\d{2}-\d{2}/.test(value)) return err([{
|
|
1419
|
+
path,
|
|
1420
|
+
message
|
|
1421
|
+
}]);
|
|
1422
|
+
const date = new Date(value);
|
|
1423
|
+
if (Number.isNaN(date.getTime())) return err([{
|
|
1424
|
+
path,
|
|
1425
|
+
message
|
|
1426
|
+
}]);
|
|
1427
|
+
const originalMonth = value.slice(5, 7);
|
|
1428
|
+
const originalDay = value.slice(8, 10);
|
|
1429
|
+
const parsedMonth = String(date.getUTCMonth() + 1).padStart(2, "0");
|
|
1430
|
+
const parsedDay = String(date.getUTCDate()).padStart(2, "0");
|
|
1431
|
+
if (originalMonth !== parsedMonth || originalDay !== parsedDay) return err([{
|
|
1432
|
+
path,
|
|
1433
|
+
message
|
|
1434
|
+
}]);
|
|
1435
|
+
return ok(date);
|
|
1436
|
+
};
|
|
1437
|
+
}
|
|
1438
|
+
/**
|
|
1439
|
+
* Create a validator that parses string URLs into URL objects.
|
|
1440
|
+
*
|
|
1441
|
+
* @example
|
|
1442
|
+
* const validate = parseURL();
|
|
1443
|
+
* validate('https://example.com'); // ok(URL)
|
|
1444
|
+
* validate('not-a-url'); // err([{ path: [], message: 'Must be a valid URL' }])
|
|
1445
|
+
*
|
|
1446
|
+
* @param message - Custom error message
|
|
1447
|
+
* @returns A validator that parses and validates URLs
|
|
1448
|
+
*/
|
|
877
1449
|
function parseURL(message = "Must be a valid URL") {
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
1450
|
+
return (value, path = []) => {
|
|
1451
|
+
if (typeof value !== "string") return err([{
|
|
1452
|
+
path,
|
|
1453
|
+
message
|
|
1454
|
+
}]);
|
|
1455
|
+
try {
|
|
1456
|
+
return ok(new URL(value));
|
|
1457
|
+
} catch {
|
|
1458
|
+
return err([{
|
|
1459
|
+
path,
|
|
1460
|
+
message
|
|
1461
|
+
}]);
|
|
1462
|
+
}
|
|
1463
|
+
};
|
|
888
1464
|
}
|
|
889
|
-
|
|
890
1465
|
// src/schema/date.ts
|
|
1466
|
+
/**
|
|
1467
|
+
* Create a validator that ensures a value is a valid Date object.
|
|
1468
|
+
*
|
|
1469
|
+
* @example
|
|
1470
|
+
* const validate = date();
|
|
1471
|
+
* validate(new Date()); // ok(Date)
|
|
1472
|
+
* validate('not a date'); // err([{ path: [], message: 'Must be a Date object' }])
|
|
1473
|
+
*
|
|
1474
|
+
* @param message - Custom error message
|
|
1475
|
+
* @returns A validator that checks if value is a valid Date
|
|
1476
|
+
*/
|
|
891
1477
|
function date(message = "Must be a Date object") {
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
1478
|
+
return (value, path = []) => {
|
|
1479
|
+
if (!(value instanceof Date)) return err([{
|
|
1480
|
+
path,
|
|
1481
|
+
message
|
|
1482
|
+
}]);
|
|
1483
|
+
if (Number.isNaN(value.getTime())) return err([{
|
|
1484
|
+
path,
|
|
1485
|
+
message: "Invalid Date"
|
|
1486
|
+
}]);
|
|
1487
|
+
return ok(value);
|
|
1488
|
+
};
|
|
1489
|
+
}
|
|
1490
|
+
/**
|
|
1491
|
+
* Create a validator that ensures a Date is within a specified range.
|
|
1492
|
+
*
|
|
1493
|
+
* @example
|
|
1494
|
+
* const validate = dateRange(new Date('2023-01-01'), new Date('2023-12-31'));
|
|
1495
|
+
* validate(new Date('2023-06-15')); // ok(Date)
|
|
1496
|
+
* validate(new Date('2024-01-01')); // err(...)
|
|
1497
|
+
*
|
|
1498
|
+
* @param min - The minimum valid date (inclusive)
|
|
1499
|
+
* @param max - The maximum valid date (inclusive)
|
|
1500
|
+
* @param message - Custom error message
|
|
1501
|
+
* @returns A validator that checks if a date is between min and max
|
|
1502
|
+
*/
|
|
1503
|
+
function dateRange(min, max, message = `Must be between ${min.toISOString().split("T", 1)[0]} and ${max.toISOString().split("T", 1)[0]}`) {
|
|
1504
|
+
return (value, path = []) => {
|
|
1505
|
+
if (value < min || value > max) return err([{
|
|
1506
|
+
path,
|
|
1507
|
+
message
|
|
1508
|
+
}]);
|
|
1509
|
+
return ok(value);
|
|
1510
|
+
};
|
|
1511
|
+
}
|
|
1512
|
+
/**
|
|
1513
|
+
* Create a validator that ensures a Date is in the past.
|
|
1514
|
+
*
|
|
1515
|
+
* @example
|
|
1516
|
+
* const validate = pastDate();
|
|
1517
|
+
* validate(new Date('1990-01-01')); // ok(Date)
|
|
1518
|
+
*
|
|
1519
|
+
* @param message - Custom error message
|
|
1520
|
+
* @returns A validator that checks if a date is in the past
|
|
1521
|
+
*/
|
|
915
1522
|
function pastDate(message = "Must be a date in the past") {
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
}
|
|
1523
|
+
return (value, path = []) => {
|
|
1524
|
+
if (value >= /* @__PURE__ */ new Date()) return err([{
|
|
1525
|
+
path,
|
|
1526
|
+
message
|
|
1527
|
+
}]);
|
|
1528
|
+
return ok(value);
|
|
1529
|
+
};
|
|
1530
|
+
}
|
|
1531
|
+
/**
|
|
1532
|
+
* Create a validator that ensures a Date is in the future.
|
|
1533
|
+
*
|
|
1534
|
+
* @example
|
|
1535
|
+
* const validate = futureDate();
|
|
1536
|
+
* const nextYear = new Date();
|
|
1537
|
+
* nextYear.setFullYear(nextYear.getFullYear() + 1);
|
|
1538
|
+
* validate(nextYear); // ok(Date)
|
|
1539
|
+
*
|
|
1540
|
+
* @param message - Custom error message
|
|
1541
|
+
* @returns A validator that checks if a date is in the future
|
|
1542
|
+
*/
|
|
923
1543
|
function futureDate(message = "Must be a date in the future") {
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
}
|
|
1544
|
+
return (value, path = []) => {
|
|
1545
|
+
if (value <= /* @__PURE__ */ new Date()) return err([{
|
|
1546
|
+
path,
|
|
1547
|
+
message
|
|
1548
|
+
}]);
|
|
1549
|
+
return ok(value);
|
|
1550
|
+
};
|
|
1551
|
+
}
|
|
1552
|
+
/**
|
|
1553
|
+
* Create a validator that ensures a Date is today or in the future.
|
|
1554
|
+
* Uses calendar date comparison (ignoring time portions).
|
|
1555
|
+
*
|
|
1556
|
+
* @example
|
|
1557
|
+
* const validate = todayOrFuture();
|
|
1558
|
+
* validate(new Date()); // ok(Date)
|
|
1559
|
+
*
|
|
1560
|
+
* @param message - Custom error message
|
|
1561
|
+
* @returns A validator that checks if a date is today or in the future
|
|
1562
|
+
*/
|
|
931
1563
|
function todayOrFuture(message = "Must be today or a future date") {
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
1564
|
+
const today = /* @__PURE__ */ new Date();
|
|
1565
|
+
today.setHours(0, 0, 0, 0);
|
|
1566
|
+
return (value, path = []) => {
|
|
1567
|
+
if (value < today) return err([{
|
|
1568
|
+
path,
|
|
1569
|
+
message
|
|
1570
|
+
}]);
|
|
1571
|
+
return ok(value);
|
|
1572
|
+
};
|
|
940
1573
|
}
|
|
941
|
-
|
|
942
1574
|
// src/schema/boolean.ts
|
|
1575
|
+
/**
|
|
1576
|
+
* Create a validator that ensures a value is a boolean.
|
|
1577
|
+
*
|
|
1578
|
+
* @example
|
|
1579
|
+
* const validate = boolean();
|
|
1580
|
+
* validate(true); // ok(true)
|
|
1581
|
+
* validate('not a boolean'); // err([{ path: [], message: 'Must be a boolean' }])
|
|
1582
|
+
*
|
|
1583
|
+
* @param message - Custom error message
|
|
1584
|
+
* @returns A validator that checks if a value is a boolean
|
|
1585
|
+
*/
|
|
943
1586
|
function boolean(message = "Must be a boolean") {
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
}
|
|
1587
|
+
return (value, path = []) => {
|
|
1588
|
+
if (typeof value !== "boolean") return err([{
|
|
1589
|
+
path,
|
|
1590
|
+
message
|
|
1591
|
+
}]);
|
|
1592
|
+
return ok(value);
|
|
1593
|
+
};
|
|
1594
|
+
}
|
|
1595
|
+
/**
|
|
1596
|
+
* Create a validator that ensures a boolean matches the expected value.
|
|
1597
|
+
*
|
|
1598
|
+
* @example
|
|
1599
|
+
* const validate = matches(true);
|
|
1600
|
+
* validate(true); // ok(true)
|
|
1601
|
+
* validate(false); // err([{ path: [], message: 'Value must be true' }])
|
|
1602
|
+
*
|
|
1603
|
+
* @param expected - The expected boolean value
|
|
1604
|
+
* @param message - Custom error message
|
|
1605
|
+
* @returns A validator that confirms the value matches the expected boolean
|
|
1606
|
+
*/
|
|
951
1607
|
function matches(expected, message = `Value must be ${expected}`) {
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
1608
|
+
return (value, path = []) => {
|
|
1609
|
+
if (value !== expected) return err([{
|
|
1610
|
+
path,
|
|
1611
|
+
message
|
|
1612
|
+
}]);
|
|
1613
|
+
return ok(value);
|
|
1614
|
+
};
|
|
958
1615
|
}
|
|
959
|
-
|
|
960
1616
|
// src/schema/union.ts
|
|
961
1617
|
function union(validators, options) {
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
allErrors.push(result.error);
|
|
995
|
-
if (!collectAllErrors) {
|
|
996
|
-
break;
|
|
997
|
-
}
|
|
998
|
-
}
|
|
999
|
-
return buildError(allErrors);
|
|
1000
|
-
};
|
|
1618
|
+
const { collectAllErrors = true, errorPrefix } = options || {};
|
|
1619
|
+
const buildError = (allErrors) => err(allErrors.flat().map((error) => ({
|
|
1620
|
+
path: error.path,
|
|
1621
|
+
message: errorPrefix ? `${errorPrefix}: ${error.message}` : error.message
|
|
1622
|
+
})));
|
|
1623
|
+
return (value, parentPath = []) => {
|
|
1624
|
+
if (validators.length === 0) return err([{
|
|
1625
|
+
path: parentPath,
|
|
1626
|
+
message: "No validators provided to union"
|
|
1627
|
+
}]);
|
|
1628
|
+
const allErrors = [];
|
|
1629
|
+
for (let i = 0; i < validators.length; i++) {
|
|
1630
|
+
const result = validators[i](value, parentPath);
|
|
1631
|
+
if (result instanceof Promise) return (async () => {
|
|
1632
|
+
const asyncResult = await result;
|
|
1633
|
+
if (isOk(asyncResult)) return asyncResult;
|
|
1634
|
+
allErrors.push(asyncResult.error);
|
|
1635
|
+
if (!collectAllErrors) return buildError(allErrors);
|
|
1636
|
+
for (let j = i + 1; j < validators.length; j++) {
|
|
1637
|
+
const r = await validators[j](value, parentPath);
|
|
1638
|
+
if (isOk(r)) return r;
|
|
1639
|
+
allErrors.push(r.error);
|
|
1640
|
+
if (!collectAllErrors) break;
|
|
1641
|
+
}
|
|
1642
|
+
return buildError(allErrors);
|
|
1643
|
+
})();
|
|
1644
|
+
if (isOk(result)) return result;
|
|
1645
|
+
allErrors.push(result.error);
|
|
1646
|
+
if (!collectAllErrors) break;
|
|
1647
|
+
}
|
|
1648
|
+
return buildError(allErrors);
|
|
1649
|
+
};
|
|
1001
1650
|
}
|
|
1002
1651
|
function discriminatedUnion(discriminantField, validatorMap, fallbackMessage = `Invalid discriminant value for '${discriminantField}'`) {
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
}
|
|
1023
|
-
]);
|
|
1024
|
-
}
|
|
1025
|
-
const result = validator(value, parentPath);
|
|
1026
|
-
if (result instanceof Promise) {
|
|
1027
|
-
return result.then((r) => r);
|
|
1028
|
-
}
|
|
1029
|
-
return result;
|
|
1030
|
-
};
|
|
1652
|
+
return (value, parentPath = []) => {
|
|
1653
|
+
if (value === null || typeof value !== "object") return err([{
|
|
1654
|
+
path: parentPath,
|
|
1655
|
+
message: "Expected an object"
|
|
1656
|
+
}]);
|
|
1657
|
+
const discriminantValue = value[discriminantField];
|
|
1658
|
+
if (typeof discriminantValue !== "string") return err([{
|
|
1659
|
+
path: [...parentPath, discriminantField],
|
|
1660
|
+
message: `Missing or invalid discriminant field '${discriminantField}'`
|
|
1661
|
+
}]);
|
|
1662
|
+
const validator = validatorMap[discriminantValue];
|
|
1663
|
+
if (!validator) return err([{
|
|
1664
|
+
path: [...parentPath, discriminantField],
|
|
1665
|
+
message: `${fallbackMessage}: '${discriminantValue}'`
|
|
1666
|
+
}]);
|
|
1667
|
+
const result = validator(value, parentPath);
|
|
1668
|
+
if (result instanceof Promise) return result.then((r) => r);
|
|
1669
|
+
return result;
|
|
1670
|
+
};
|
|
1031
1671
|
}
|
|
1032
|
-
|
|
1033
1672
|
// src/schema/enum.ts
|
|
1673
|
+
/**
|
|
1674
|
+
* Create a validator for TypeScript enum values.
|
|
1675
|
+
* Works with both string and numeric enums.
|
|
1676
|
+
*
|
|
1677
|
+
* @example
|
|
1678
|
+
* enum Status { Pending = "PENDING", Approved = "APPROVED" }
|
|
1679
|
+
* const validate = enumValue(Status);
|
|
1680
|
+
* validate("PENDING"); // ok("PENDING")
|
|
1681
|
+
* validate("INVALID"); // err([{ path: [], message: 'Value must be one of: PENDING, APPROVED' }])
|
|
1682
|
+
*
|
|
1683
|
+
* @example
|
|
1684
|
+
* // With excluded values
|
|
1685
|
+
* const validate = enumValue(Status, "Not allowed", [Status.Pending]);
|
|
1686
|
+
* validate("PENDING"); // err(...)
|
|
1687
|
+
*
|
|
1688
|
+
* @param enumObject - The enum object to validate against
|
|
1689
|
+
* @param message - Custom error message
|
|
1690
|
+
* @param excludedValues - Values to exclude from the valid set
|
|
1691
|
+
* @returns A validator that ensures the value is a valid enum value
|
|
1692
|
+
*/
|
|
1034
1693
|
function enumValue(enumObject, message, excludedValues) {
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1694
|
+
return (value, path = []) => {
|
|
1695
|
+
const enumValues = Object.values(enumObject);
|
|
1696
|
+
if (!enumValues.includes(value)) {
|
|
1697
|
+
const defaultMessage = `Value must be one of: ${enumValues.join(", ")}`;
|
|
1698
|
+
return err([{
|
|
1699
|
+
path,
|
|
1700
|
+
message: message || defaultMessage
|
|
1701
|
+
}]);
|
|
1702
|
+
}
|
|
1703
|
+
if (excludedValues && excludedValues.includes(value)) return err([{
|
|
1704
|
+
path,
|
|
1705
|
+
message: `${message || `Selected value is excluded from valid enum values`}`
|
|
1706
|
+
}]);
|
|
1707
|
+
return ok(value);
|
|
1708
|
+
};
|
|
1047
1709
|
}
|
|
1048
|
-
|
|
1049
1710
|
// src/schema/bigint.ts
|
|
1711
|
+
/**
|
|
1712
|
+
* Create a validator that ensures a value is a bigint.
|
|
1713
|
+
*
|
|
1714
|
+
* @example
|
|
1715
|
+
* const validate = bigint();
|
|
1716
|
+
* validate(9007199254740993n); // ok(9007199254740993n)
|
|
1717
|
+
* validate(123); // err([{ path: [], message: 'Must be a bigint' }])
|
|
1718
|
+
*
|
|
1719
|
+
* @param message - Custom error message
|
|
1720
|
+
* @returns A validator that checks if the value is a bigint
|
|
1721
|
+
*/
|
|
1050
1722
|
function bigint(message = "Must be a bigint") {
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1723
|
+
return (value, path = []) => {
|
|
1724
|
+
if (typeof value !== "bigint") return err([{
|
|
1725
|
+
path,
|
|
1726
|
+
message
|
|
1727
|
+
}]);
|
|
1728
|
+
return ok(value);
|
|
1729
|
+
};
|
|
1057
1730
|
}
|
|
1058
|
-
|
|
1059
1731
|
// src/schema/standard.ts
|
|
1060
1732
|
function mapErrors(errors) {
|
|
1061
|
-
|
|
1733
|
+
return errors.map((e) => ({
|
|
1734
|
+
message: e.message,
|
|
1735
|
+
path: e.path
|
|
1736
|
+
}));
|
|
1062
1737
|
}
|
|
1063
1738
|
function toStandardSchema(validator) {
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
return { issues: [{ message: error instanceof Error ? error.message : String(error) }] };
|
|
1079
|
-
}
|
|
1080
|
-
},
|
|
1081
|
-
types: void 0
|
|
1082
|
-
}
|
|
1083
|
-
};
|
|
1739
|
+
return { "~standard": {
|
|
1740
|
+
version: 1,
|
|
1741
|
+
vendor: "railway-ts",
|
|
1742
|
+
validate(value) {
|
|
1743
|
+
try {
|
|
1744
|
+
const result = validator(value);
|
|
1745
|
+
if (result instanceof Promise) return result.then((r) => isOk(r) ? { value: r.value } : { issues: mapErrors(r.error) }).catch((error) => ({ issues: [{ message: error instanceof Error ? error.message : String(error) }] }));
|
|
1746
|
+
return isOk(result) ? { value: result.value } : { issues: mapErrors(result.error) };
|
|
1747
|
+
} catch (error) {
|
|
1748
|
+
return { issues: [{ message: error instanceof Error ? error.message : String(error) }] };
|
|
1749
|
+
}
|
|
1750
|
+
},
|
|
1751
|
+
types: void 0
|
|
1752
|
+
} };
|
|
1084
1753
|
}
|
|
1085
|
-
|
|
1086
1754
|
export { ROOT_ERROR_KEY, _getAbortEarly, _withAbortEarly, array, between, bigint, boolean, chain, chainAsync, date, dateRange, discriminatedUnion, divisibleBy, email, emptyAsOptional, enumValue, finite, formatErrors, futureDate, integer, is, isoDate, isoDateTime, isoDuration, isoTime, literal, matches, max, maxItems, maxLength, min, minItems, minLength, negative, nonEmpty, nonZero, notEmpty, nullable, number, object, oneOf, optional, parseBigInt, parseBool, parseDate, parseEnum, parseISODate, parseJSON, parseNumber, parseString, parseURL, pastDate, pattern, phoneNumber, positive, precision, refine, refineAsync, refineAt, refineAtAsync, required, string, stringEnum, toStandardSchema, todayOrFuture, transform, tuple, tupleOf, union, unique, url, uuid, validate, validateAndFormatResult, when, whenAsync };
|
|
1087
|
-
|
|
1755
|
+
|
|
1088
1756
|
//# sourceMappingURL=index.mjs.map
|