1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
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
415
416
417
418
419
420
421
422
423
424
425
426
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
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
562
563
564
565
566
567
568
569
570
571
572
573
574
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
//! # vld — type-safe runtime validation for Rust
//!
//! `vld` is a validation library inspired by [Zod](https://zod.dev/). Schemas
//! are values: chain checks on them, then parse untrusted input (JSON text,
//! bytes, files or `serde_json::Value`) into typed Rust values. A failed parse
//! returns a [`VldError`](error::VldError) with **every** issue, each with a
//! path, a typed [`IssueCode`](error::IssueCode) and a message.
//!
//! **Guide:** <https://s00d.github.io/vld/> · **Changelog / migration from
//! 0.4:** <https://s00d.github.io/vld/guides/migration>
//!
//! ## Quick start
//!
//! ```rust
//! use vld::prelude::*;
//!
//! vld::schema! {
//! #[derive(Debug)]
//! pub struct User {
//! pub name: String => vld::string().trim().min(2).max(50),
//! pub email: String => vld::string().email(),
//! pub age: Option<i64> => vld::number().int().gte(18).optional(),
//! }
//! }
//!
//! let user = User::parse(r#"{"name": " Alex ", "email": "alex@example.com"}"#).unwrap();
//! assert_eq!(user.name, "Alex");
//! assert_eq!(user.age, None);
//!
//! let err = User::parse(r#"{"name": "A", "email": "nope"}"#).unwrap_err();
//! assert_eq!(err.issues.len(), 2);
//! assert_eq!(err.issues[0].code.key(), "too_small");
//! ```
//!
//! Single values work the same way:
//!
//! ```rust
//! use vld::prelude::*;
//!
//! let port = vld::u16().min(1024);
//! assert_eq!(port.parse("8080").unwrap(), 8080);
//! assert!(port.parse("80").is_err());
//! ```
//!
//! ## Features
//!
//! None are enabled by default.
//!
//! | Feature | Enables |
//! |---|---|
//! | `derive` | `#[derive(Validate)]` |
//! | `openapi` | the `JsonSchema` trait and OpenAPI 3.1 documents |
//! | `diff` | breaking-change detection between JSON Schemas (implies `openapi`) |
//! | `regex` | `string().pattern(...)`, `rules::Pattern` (via `regex-lite`) |
//! | `chrono` / `jiff` / `time` | `vld::chrono`, `vld::jiff`, `vld::time` date schemas (additive) |
//! | `decimal` | `decimal()` (`rust_decimal`) |
//! | `net` | `ip_network()` (`ipnet`) |
//! | `file` / `file-advanced` | `file()` with size / type checks; hashes, image size, EXIF |
//! | `string-advanced` | `url_strict()`, `uri()`, `uuid_v4()` & co, `phone_e164_strict()`, `semver_full()` |
//!
//! ## Module map
//!
//! - [`mod@schema`] — the [`VldSchema`](schema::VldSchema) trait, [`VldParse`](schema::VldParse),
//! [`DynSchema`](schema::DynSchema), input sources, nested schemas and
//! [`parse_coerced`](schema::parse_coerced)
//! - [`error`] — [`VldError`](error::VldError), [`IssueCode`](error::IssueCode),
//! formatting ([`error::format`]) and translations ([`error::i18n`])
//! - [`primitives`], [`collections`], [`combinators`], [`modifiers`], [`mod@object`] — schema types
//! - `openapi` (feature `openapi`) — JSON Schema / OpenAPI generation and schema diffs
//! - [`prelude`] — everything needed for day-to-day use
//!
//! ## Size method names
//!
//! Size bounds are named after what they count:
//!
//! | Schema | Bounds | Exact |
//! |---|---|---|
//! | `string()` (characters) | `min` / `max` | `len` |
//! | `array()`, `bytes()` (items / bytes) | `min_len` / `max_len` | `len` |
//! | `set()` (unique items), `file()` (bytes) | `min_size` / `max_size` | — |
//! | `object()`, `record()` (keys) | `min_keys` / `max_keys` | — |
//! | numbers, dates | `min` / `max` (`gt` / `lt` exclusive) | — |
//!
//! `schema!` structs get `parse()`; `#[derive(Validate)]` generates
//! `vld_parse()` instead, as `parse` would clash with `clap::Parser::parse`
//! and similar derives.
/// Arrays, tuples, sets, maps and records.
/// Unions, intersections, refinements, transforms and pipes.
/// Optional, nullable, nullish and default wrappers.
/// Strings, numbers, booleans, dates and other leaf schemas.
/// The `VldSchema` / `VldParse` traits and nested-schema helpers.
// Old module paths (pre-0.5), kept as aliases.
pub use ;
pub use openapi as json_schema;
pub use diff;
pub use Schema;
pub use input;
// Date backends: additive, each in its own module.
pub use chrono;
pub use jiff;
pub use time;
// Re-export serde_json for use in macros
pub use serde_json;
// Re-export serde for DynSchema users
pub use serde;
// Re-export the derive macro when the `derive` feature is enabled
pub use Validate;
// ---------------------------------------------------------------------------
// Convenience constructors
// ---------------------------------------------------------------------------
/// Create a string validation schema.
/// Create a number validation schema (`f64`).
int_constructors!
/// Create an `f32` number schema (rejects values outside the `f32` range).
/// Create a boolean validation schema.
/// Create a bytes validation schema (`Vec<u8>`).
///
/// By default expects a JSON array of byte integers `0..=255`.
/// Use `.base64()` to additionally accept Base64 string input.
/// Create a decimal validation schema (`rust_decimal::Decimal`).
/// Create an IP network/CIDR schema (`ipnet::IpNet`).
/// Create a socket address schema (`std::net::SocketAddr`).
/// Create a raw JSON value schema with shape constraints.
/// Create a file validation schema.
///
/// Requires the `file` feature.
///
/// # Security
///
/// The path comes from the (untrusted) input and is checked against the
/// **server's** filesystem: by default any absolute path or `..` is
/// accepted, so `exists()` / `file()` / `dir()` reveal whether arbitrary
/// paths exist and `vld::file()` opens and reads them. Always confine user-supplied paths with
/// [`within(base)`](primitives::ZFile::within), which resolves `..` and symlinks and returns
/// the joined path.
/// Create a duration validation schema (`std::time::Duration`).
/// Create a path validation schema (`std::path::PathBuf`).
///
/// # Security
///
/// The path comes from the (untrusted) input and is checked against the
/// **server's** filesystem: by default any absolute path or `..` is
/// accepted, so `exists()` / `file()` / `dir()` reveal whether arbitrary
/// paths exist. Always confine user-supplied paths with
/// [`within(base)`](primitives::ZPath::within), which resolves `..` and symlinks and returns
/// the joined path.
/// Create an array validation schema.
/// Create a dynamic object validation schema.
///
/// For type-safe objects, prefer the [`schema!`] macro.
/// Create a schema for nested/composed structs.
/// Create a **named** nested schema. Usually called through [`nested!`].
///
/// - `name` — OpenAPI component name; the field's JSON Schema becomes
/// `{"$ref": "#/components/schemas/{name}"}`. Must match `[A-Za-z0-9._-]+`.
/// - `f` — parser for the nested value (e.g. `Address::parse_value`).
/// - `json_schema_fn` — full JSON Schema of the nested type, registered as the
/// component (`None` disables registration).
/// - `collect_nested_fn` — collects the nested type's own nested schemas so
/// grandchildren are registered too.
///
/// With `json_schema_fn` set, `to_openapi_document()` of the parent and the
/// `vld-utoipa` / `vld-aide` / `vld-schemars` integrations register the
/// component automatically.
/// Create a literal value schema. Validates exact match.
///
/// ```
/// use vld::prelude::*;
/// assert_eq!(vld::literal("admin").parse(r#""admin""#).unwrap(), "admin");
/// assert!(vld::literal(42i64).parse("42").is_ok());
/// assert!(vld::literal(true).parse("true").is_ok());
///
/// // A string known only at runtime: pass an owned `String`.
/// let tag = format!("v{}", 2);
/// assert!(vld::literal(tag).parse(r#""v2""#).is_ok());
/// ```
///
/// Schemas may be cached for the whole process, so the value must be owned
/// or `'static`: use `String` (`name.to_string()`) for a borrowed `&str`.
/// Create a string enum schema. Validates against a fixed set of values.
///
/// ```
/// use vld::prelude::*;
/// let role = vld::enumeration(&["admin", "user", "mod"]);
/// assert!(role.parse(r#""admin""#).is_ok());
/// assert!(role.parse(r#""hacker""#).is_err());
/// ```
/// Deserialize the JSON value into `T` with serde (Rust enums, `uuid::Uuid`,
/// `url::Url`, `semver::Version`, …).
///
/// Serde errors become a `parse_error` issue carrying the serde message.
/// The JSON Schema is `{}` unless set with [`ZFromSerde::schema`](primitives::ZFromSerde::schema).
///
/// ```
/// use vld::prelude::*;
///
/// #[derive(Debug, PartialEq, serde::Deserialize)]
/// #[serde(rename_all = "snake_case")]
/// enum Status { Active, OnHold }
///
/// let schema = vld::from_serde::<Status>()
/// .schema(serde_json::json!({"type": "string", "enum": ["active", "on_hold"]}));
/// assert_eq!(schema.parse(r#""on_hold""#).unwrap(), Status::OnHold);
/// assert!(schema.parse(r#""gone""#).is_err());
/// ```
/// Parse a JSON string with `T: FromStr` (`IpAddr`, `Uuid`, `Url`, numbers
/// as strings, …).
///
/// Parse errors become an `invalid_format` (`from_str`) issue whose message is
/// the error's `Display`. The JSON Schema is `{"type": "string"}` unless set
/// with [`ZFromStr::schema`](primitives::ZFromStr::schema).
///
/// ```
/// use vld::prelude::*;
/// use std::net::IpAddr;
///
/// let schema = vld::from_str::<IpAddr>()
/// .schema(serde_json::json!({"type": "string", "format": "ip"}));
/// let ip = schema.parse(r#""::1""#).unwrap();
/// assert!(ip.is_loopback());
/// assert!(schema.parse(r#""not-an-ip""#).is_err());
/// ```
/// Map fixed strings to values of `T` — a light alternative to
/// [`from_serde()`] for enums without `Deserialize`.
///
/// ```
/// use vld::prelude::*;
///
/// #[derive(Debug, Clone, PartialEq)]
/// enum Level { Low, High }
///
/// let level = vld::enum_of(&[("low", Level::Low), ("high", Level::High)]);
/// assert_eq!(level.parse(r#""high""#).unwrap(), Level::High);
/// let err = level.parse(r#""mid""#).unwrap_err();
/// assert_eq!(err.issues[0].code.key(), "invalid_enum_value");
/// ```
/// Create a schema that accepts any JSON value.
/// Create a schema that accepts only `null` (output `()`).
/// Create a schema that rejects every value (output [`std::convert::Infallible`]).
/// Create a single-`char` schema (a string of exactly one Unicode scalar value).
/// Create a date schema with the only enabled date backend.
///
/// Available only when exactly one of `chrono`, `jiff`, `time` is enabled;
/// otherwise use `vld::chrono::date()`, `vld::jiff::date()` or
/// `vld::time::date()` (see [`primitives::date`]).
/// Create a datetime schema with the only enabled date backend.
///
/// Available only when exactly one of `chrono`, `jiff`, `time` is enabled;
/// otherwise use `vld::chrono::datetime()` etc. (see [`primitives::date`]).
/// Create a time-of-day schema (`HH:MM:SS[.frac]`) with the only enabled
/// date backend.
///
/// Available only when exactly one of `chrono`, `jiff`, `time` is enabled;
/// otherwise use `vld::chrono::time()`, `vld::jiff::time()` or
/// `vld::time::time()` (see [`primitives::date`]).
/// Create a record (dictionary) schema. All values validated by the given schema.
///
/// ```
/// use vld::prelude::*;
/// let schema = vld::record(vld::number().positive());
/// let map = schema.parse(r#"{"a": 1, "b": 2}"#).unwrap();
/// assert_eq!(map.len(), 2);
/// ```
/// Create a record whose keys are validated and converted by `key_schema`.
///
/// Each object key is passed to `key_schema` as a JSON string (so use string
/// schemas, [`enumeration()`], [`enum_of()`] or [`from_str()`] for numeric
/// keys). Output is `HashMap<K::Output, V::Output>`; call `.ordered()` for a
/// `BTreeMap`. JSON Schema: `propertyNames` from the key schema,
/// `additionalProperties` from the value schema.
///
/// ```
/// use vld::prelude::*;
/// use std::collections::HashMap;
///
/// let scores = vld::record_with_keys(vld::from_str::<u32>(), vld::number());
/// let map: HashMap<u32, f64> = scores.parse(r#"{"1": 9.5, "2": 7}"#).unwrap();
/// assert_eq!(map[&1], 9.5);
/// assert!(scores.parse(r#"{"x": 1}"#).is_err());
///
/// let by_role = vld::record_with_keys(vld::enumeration(&["admin", "user"]), vld::boolean())
/// .ordered();
/// let m = by_role.parse(r#"{"user": true, "admin": false}"#).unwrap();
/// assert_eq!(m.keys().collect::<Vec<_>>(), ["admin", "user"]);
/// ```
/// Create a Map schema. Validates `[[key, value], ...]` arrays into `HashMap`.
/// Create a Set schema. Validates arrays into `HashSet` (unique elements).
/// Create a union of two schemas. Returns `Either<A, B>`.
/// Create a union of three schemas. Returns `Either3<A, B, C>`.
/// Create an intersection of two schemas (input must satisfy both).
///
/// Both schemas run on the same input. The output of the first schema is returned.
/// Create a discriminated union schema.
///
/// Routes to the correct variant schema based on the value of a discriminator field.
/// Create a lazy schema for recursive data structures.
///
/// The factory is called on the first parse of this node and its schema is
/// cached (see [`ZLazy`](combinators::ZLazy)), enabling self-referencing schemas.
/// Create a schema from a custom validation function.
///
/// The function receives a `&serde_json::Value` and returns `Result<T, String>`.
/// Preprocess the JSON value before passing it to a schema.