vld 0.3.0

Type-safe runtime validation library for Rust, inspired by Zod
Documentation
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
//! # vld — Type-safe runtime validation for Rust
//!
//! `vld` is a validation library inspired by [Zod](https://zod.dev/) that combines
//! schema definition with type-safe parsing.
//!
//! ## Quick Start
//!
//! ```rust
//! use vld::prelude::*;
//!
//! // Define a validated struct
//! vld::schema! {
//!     #[derive(Debug)]
//!     pub struct User {
//!         pub name: String => vld::string().min(2).max(50),
//!         pub email: String => vld::string().email(),
//!         pub age: Option<i64> => vld::number().int().gte(18).optional(),
//!     }
//! }
//!
//! // Parse from JSON string
//! let user = User::parse(r#"{"name": "Alex", "email": "alex@example.com"}"#).unwrap();
//! assert_eq!(user.name, "Alex");
//! assert_eq!(user.age, None);
//! ```

pub mod collections;
pub mod combinators;
#[cfg(feature = "diff")]
pub mod diff;
pub mod error;
pub mod format;
pub mod i18n;
pub mod input;
#[cfg(feature = "openapi")]
pub mod json_schema;
mod macros;
pub mod modifiers;
pub mod object;
pub mod primitives;
pub mod schema;

// Re-export serde_json for use in macros
#[doc(hidden)]
pub use serde_json;

// Re-export serde for DynSchema users
#[doc(hidden)]
pub use serde;

// ---------------------------------------------------------------------------
// Feature-gate helper macros.
//
// These are conditionally compiled based on **vld's** features, so when a
// foreign crate invokes `vld::schema!`, the check uses vld's features
// instead of the consumer's — eliminating `unexpected_cfgs` warnings.
// ---------------------------------------------------------------------------

/// Emit the given tokens only when the `serialize` feature is enabled on `vld`.
#[cfg(feature = "serialize")]
#[doc(hidden)]
#[macro_export]
macro_rules! __vld_if_serialize {
    ($($tt:tt)*) => { $($tt)* };
}

/// No-op: `serialize` feature is disabled.
#[cfg(not(feature = "serialize"))]
#[doc(hidden)]
#[macro_export]
macro_rules! __vld_if_serialize {
    ($($tt:tt)*) => {};
}

/// Emit the given tokens only when the `openapi` feature is enabled on `vld`.
#[cfg(feature = "openapi")]
#[doc(hidden)]
#[macro_export]
macro_rules! __vld_if_openapi {
    ($($tt:tt)*) => { $($tt)* };
}

/// No-op: `openapi` feature is disabled.
#[cfg(not(feature = "openapi"))]
#[doc(hidden)]
#[macro_export]
macro_rules! __vld_if_openapi {
    ($($tt:tt)*) => {};
}

#[cfg(feature = "openapi")]
#[doc(hidden)]
#[macro_export]
macro_rules! __vld_nested_schema_fn {
    ($ty:ty) => {
        Some(<$ty>::json_schema as fn() -> $crate::serde_json::Value)
    };
}

#[cfg(not(feature = "openapi"))]
#[doc(hidden)]
#[macro_export]
macro_rules! __vld_nested_schema_fn {
    ($ty:ty) => {
        None
    };
}

// Re-export regex_lite when the `regex` feature is enabled
#[cfg(feature = "regex")]
pub use regex_lite;

// Re-export the derive macro when the `derive` feature is enabled
#[cfg(feature = "derive")]
pub use vld_derive::Validate;

// ---------------------------------------------------------------------------
// Convenience constructors
// ---------------------------------------------------------------------------

/// Create a string validation schema.
pub fn string() -> primitives::ZString {
    primitives::ZString::new()
}

/// Create a number validation schema (`f64`).
pub fn number() -> primitives::ZNumber {
    primitives::ZNumber::new()
}

/// Create a boolean validation schema.
pub fn boolean() -> primitives::ZBoolean {
    primitives::ZBoolean::new()
}

/// 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.
pub fn bytes() -> primitives::ZBytes {
    primitives::ZBytes::new()
}

/// Create a decimal validation schema (`rust_decimal::Decimal`).
#[cfg(feature = "decimal")]
pub fn decimal() -> primitives::ZDecimal {
    primitives::ZDecimal::new()
}

/// Create an IP network/CIDR schema (`ipnet::IpNet`).
#[cfg(feature = "net")]
pub fn ip_network() -> primitives::ZIpNetwork {
    primitives::ZIpNetwork::new()
}

/// Create a socket address schema (`std::net::SocketAddr`).
pub fn socket_addr() -> primitives::ZSocketAddr {
    primitives::ZSocketAddr::new()
}

/// Create a raw JSON value schema with shape constraints.
pub fn json_value() -> primitives::ZJsonValue {
    primitives::ZJsonValue::new()
}

/// Create a file validation schema.
///
/// Requires the `file` feature.
#[cfg(feature = "file")]
pub fn file() -> primitives::ZFile {
    primitives::ZFile::new()
}

/// Create a duration validation schema (`std::time::Duration`).
///
/// Requires the `std` feature.
#[cfg(feature = "std")]
pub fn duration() -> primitives::ZDuration {
    primitives::ZDuration::new()
}

/// Create a path validation schema (`std::path::PathBuf`).
///
/// Requires the `std` feature.
#[cfg(feature = "std")]
pub fn path() -> primitives::ZPath {
    primitives::ZPath::new()
}

/// Create an array validation schema.
pub fn array<T: schema::VldSchema>(element: T) -> collections::ZArray<T> {
    collections::ZArray::new(element)
}

/// Create a dynamic object validation schema.
///
/// For type-safe objects, prefer the [`schema!`] macro.
pub fn object() -> object::ZObject {
    object::ZObject::new()
}

/// Create a schema for nested/composed structs.
pub fn nested<T, F>(f: F) -> schema::NestedSchema<T, F>
where
    F: Fn(&serde_json::Value) -> Result<T, error::VldError>,
{
    schema::NestedSchema::new(f)
}

pub fn nested_named<T, F>(
    name: &'static str,
    f: F,
    json_schema_fn: Option<fn() -> serde_json::Value>,
) -> schema::NestedSchema<T, F>
where
    F: Fn(&serde_json::Value) -> Result<T, error::VldError>,
{
    schema::NestedSchema::new_named(f, name, json_schema_fn)
}

/// Create a named nested schema with `$ref` generation and full JSON Schema.
///
/// ```ignore
/// vld::schema! {
///     pub struct User {
///         pub address: Address => vld::nested!(Address),
///     }
/// }
/// ```
#[macro_export]
macro_rules! nested {
    ($ty:ty) => {
        $crate::nested_named(
            stringify!($ty),
            <$ty>::parse_value,
            $crate::__vld_nested_schema_fn!($ty),
        )
    };
}

/// 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());
/// ```
pub fn literal<T: primitives::IntoLiteral>(val: T) -> primitives::ZLiteral<T> {
    primitives::ZLiteral::new(val)
}

/// 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());
/// ```
pub fn enumeration(variants: &[&str]) -> primitives::ZEnum {
    primitives::ZEnum::new(variants)
}

/// Create a schema that accepts any JSON value.
pub fn any() -> primitives::ZAny {
    primitives::ZAny::new()
}

/// Create a date validation schema. Parses ISO 8601 date strings (`YYYY-MM-DD`)
/// into `chrono::NaiveDate`.
///
/// Requires the `chrono` feature.
#[cfg(feature = "chrono")]
pub fn date() -> primitives::ZDate {
    primitives::ZDate::new()
}

/// Create a datetime validation schema. Parses ISO 8601 datetime strings
/// into `chrono::DateTime<chrono::Utc>`.
///
/// Requires the `chrono` feature.
#[cfg(feature = "chrono")]
pub fn datetime() -> primitives::ZDateTime {
    primitives::ZDateTime::new()
}

/// 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);
/// ```
pub fn record<V: schema::VldSchema>(value_schema: V) -> collections::ZRecord<V> {
    collections::ZRecord::new(value_schema)
}

/// Create a Map schema. Validates `[[key, value], ...]` arrays into `HashMap`.
pub fn map<K: schema::VldSchema, V: schema::VldSchema>(
    key_schema: K,
    value_schema: V,
) -> collections::ZMap<K, V> {
    collections::ZMap::new(key_schema, value_schema)
}

/// Create a Set schema. Validates arrays into `HashSet` (unique elements).
pub fn set<T: schema::VldSchema>(element: T) -> collections::ZSet<T> {
    collections::ZSet::new(element)
}

/// Create a union of two schemas. Returns `Either<A, B>`.
pub fn union<A: schema::VldSchema, B: schema::VldSchema>(a: A, b: B) -> combinators::ZUnion2<A, B> {
    combinators::ZUnion2::new(a, b)
}

/// Create a union of three schemas. Returns `Either3<A, B, C>`.
pub fn union3<A: schema::VldSchema, B: schema::VldSchema, C: schema::VldSchema>(
    a: A,
    b: B,
    c: C,
) -> combinators::ZUnion3<A, B, C> {
    combinators::ZUnion3::new(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.
pub fn intersection<A: schema::VldSchema, B: schema::VldSchema>(
    a: A,
    b: B,
) -> combinators::ZIntersection<A, B> {
    combinators::ZIntersection::new(a, b)
}

/// Create a discriminated union schema.
///
/// Routes to the correct variant schema based on the value of a discriminator field.
pub fn discriminated_union(discriminator: impl Into<String>) -> combinators::ZDiscriminatedUnion {
    combinators::ZDiscriminatedUnion::new(discriminator)
}

/// Create a lazy schema for recursive data structures.
///
/// The factory function is called on each parse, enabling self-referencing schemas.
pub fn lazy<T: schema::VldSchema, F: Fn() -> T>(factory: F) -> combinators::ZLazy<T, F> {
    combinators::ZLazy::new(factory)
}

/// Create a schema from a custom validation function.
///
/// The function receives a `&serde_json::Value` and returns `Result<T, String>`.
pub fn custom<F, T>(check: F) -> combinators::ZCustom<F, T>
where
    F: Fn(&serde_json::Value) -> Result<T, String>,
{
    combinators::ZCustom::new(check)
}

/// Preprocess the JSON value before passing it to a schema.
pub fn preprocess<F, S>(preprocessor: F, schema: S) -> combinators::ZPreprocess<F, S>
where
    F: Fn(&serde_json::Value) -> serde_json::Value,
    S: schema::VldSchema,
{
    combinators::ZPreprocess::new(preprocessor, schema)
}

// ---------------------------------------------------------------------------
// Prelude
// ---------------------------------------------------------------------------

/// Common imports for working with `vld`.
pub mod prelude {
    pub use crate::collections::{ZArray, ZMap, ZRecord, ZSet};
    pub use crate::combinators::{
        Either, Either3, ZCatch, ZCustom, ZDescribe, ZDiscriminatedUnion, ZIntersection, ZLazy,
        ZMessage, ZPipe, ZPreprocess, ZRefine, ZSuperRefine, ZTransform, ZUnion2, ZUnion3,
    };
    pub use crate::error::{
        FieldResult, IssueBuilder, IssueCode, ParseResult, PathSegment, ValidationIssue, VldError,
    };
    pub use crate::format::{flatten_error, prettify_error, treeify_error};
    pub use crate::input::VldInput;
    #[cfg(feature = "openapi")]
    pub use crate::json_schema::JsonSchema;
    pub use crate::modifiers::{ZDefault, ZNullable, ZNullish, ZOptional};
    pub use crate::object::ZObject;
    #[cfg(feature = "decimal")]
    pub use crate::primitives::ZDecimal;
    #[cfg(feature = "net")]
    pub use crate::primitives::ZIpNetwork;
    #[cfg(feature = "file")]
    pub use crate::primitives::{FileStorage, ValidatedFile, ZFile};
    pub use crate::primitives::{
        IntoLiteral, ZAny, ZBoolean, ZBytes, ZEnum, ZInt, ZJsonValue, ZLiteral, ZNumber,
        ZSocketAddr, ZString,
    };
    #[cfg(feature = "chrono")]
    pub use crate::primitives::{ZDate, ZDateTime};
    #[cfg(feature = "std")]
    pub use crate::primitives::{ZDuration, ZPath};
    pub use crate::schema::{VldParse, VldSchema};
}