vld 0.6.1

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
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
use serde_json::{Map, Value};

use crate::error::{IssueCode, PathSegment, SizeOrigin, VldError};
use crate::schema::{DynSchema, VldSchema};

use super::field::{OptionalDynSchema, RequiredDynSchema};

struct ObjectField {
    name: String,
    schema: Box<dyn DynSchema + Send + Sync>,
}

/// How to handle unknown fields not declared in the schema.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum UnknownFieldMode {
    /// Silently drop unknown fields from the output (default).
    Strip,
    /// Reject unknown fields with a validation error.
    Strict,
    /// Keep unknown fields as-is in the output.
    Passthrough,
}

/// Conditional validation rule: when `condition_field` has `condition_value`,
/// validate `target_field` with `schema`.
struct ConditionalRule {
    condition_field: String,
    condition_value: serde_json::Value,
    target_field: String,
    schema: Box<dyn DynSchema + Send + Sync>,
}

/// Dynamic object schema with runtime-defined fields.
///
/// For compile-time type-safe objects, use the [`schema!`](crate::schema!) macro instead.
///
/// # Unknown field handling
///
/// - **`strip()`** (default) — unknown fields are silently removed from the output.
/// - **`strict()`** — unknown fields cause a validation error.
/// - **`passthrough()`** — unknown fields are kept as-is in the output.
///
/// # Example
/// ```
/// use vld::prelude::*;
///
/// let schema = vld::object()
///     .field("name", vld::string().min(1))
///     .field("age", vld::number().int().min(0));
/// ```
pub struct ZObject {
    fields: Vec<ObjectField>,
    unknown_mode: UnknownFieldMode,
    catchall_schema: Option<Box<dyn DynSchema + Send + Sync>>,
    conditional_rules: Vec<ConditionalRule>,
    min_keys: Option<usize>,
    max_keys: Option<usize>,
}

impl ZObject {
    /// Create the schema (the same as its `vld::` constructor function).
    pub fn new() -> Self {
        Self {
            fields: vec![],
            unknown_mode: UnknownFieldMode::Strip,
            catchall_schema: None,
            conditional_rules: vec![],
            min_keys: None,
            max_keys: None,
        }
    }

    /// Add `field`, replacing (in place) an earlier field with the same name.
    fn put(mut self, field: ObjectField) -> Self {
        match self.fields.iter_mut().find(|f| f.name == field.name) {
            Some(existing) => *existing = field,
            None => self.fields.push(field),
        }
        self
    }

    /// Add a field with its validation schema. A field with the same name
    /// is replaced.
    ///
    /// With the `openapi` feature the field keeps its JSON Schema, its
    /// `required` status (`.optional()` / `.nullish()` / `.with_default(...)`
    /// / `.nullable()` are not required) and its named nested schemas.
    pub fn field<S: DynSchema + Send + Sync + 'static>(
        self,
        name: impl Into<String>,
        schema: S,
    ) -> Self {
        self.put(ObjectField {
            name: name.into(),
            schema: Box::new(schema),
        })
    }

    /// Add a field that is automatically optional (null/missing → `null`).
    ///
    /// The field won't cause a validation error if it is missing or null.
    /// When the value is missing/null the inner schema still runs first, so
    /// `.with_default(...)` and `.catch(...)` produce their value; otherwise
    /// the output is `null`.
    ///
    /// # Example
    /// ```
    /// use vld::prelude::*;
    ///
    /// let schema = vld::object()
    ///     .field("name", vld::string().min(1))
    ///     .field_optional("nickname", vld::string().min(1));
    ///
    /// let result = schema.parse(r#"{"name": "Alice"}"#).unwrap();
    /// assert_eq!(result.get("nickname").unwrap(), &serde_json::Value::Null);
    /// ```
    pub fn field_optional<S: DynSchema + Send + Sync + 'static>(
        self,
        name: impl Into<String>,
        schema: S,
    ) -> Self {
        self.put(ObjectField {
            name: name.into(),
            schema: Box::new(OptionalDynSchema(Box::new(schema))),
        })
    }

    /// Reject unknown fields not defined in the schema.
    pub fn strict(mut self) -> Self {
        self.unknown_mode = UnknownFieldMode::Strict;
        self
    }

    /// Silently remove unknown fields from the output (default behavior).
    pub fn strip(mut self) -> Self {
        self.unknown_mode = UnknownFieldMode::Strip;
        self
    }

    /// Keep unknown fields as-is in the output without validation.
    pub fn passthrough(mut self) -> Self {
        self.unknown_mode = UnknownFieldMode::Passthrough;
        self
    }

    /// Remove a field definition by name. Returns self for chaining.
    ///
    /// Useful with [`extend()`](Self::extend) to override fields.
    pub fn omit(mut self, name: &str) -> Self {
        self.fields.retain(|f| f.name != name);
        self
    }

    /// Keep only the listed fields, removing all others.
    pub fn pick(mut self, names: &[&str]) -> Self {
        self.fields.retain(|f| names.contains(&f.name.as_str()));
        self
    }

    /// Merge another object schema into this one.
    ///
    /// If both schemas define the same field, the one from `other` wins (and
    /// takes its place at the end). `other`'s settings are merged too: its
    /// unknown-field mode (when not the default `strip()`), `catchall`,
    /// `min_keys` / `max_keys` win when set, and its `when` rules are added.
    pub fn extend(mut self, other: ZObject) -> Self {
        for field in other.fields {
            self.fields.retain(|f| f.name != field.name);
            self.fields.push(field);
        }
        if other.unknown_mode != UnknownFieldMode::Strip {
            self.unknown_mode = other.unknown_mode;
        }
        self.catchall_schema = other.catchall_schema.or(self.catchall_schema);
        self.conditional_rules.extend(other.conditional_rules);
        self.min_keys = other.min_keys.or(self.min_keys);
        self.max_keys = other.max_keys.or(self.max_keys);
        self
    }

    /// Alias for [`extend`](Self::extend).
    pub fn merge(self, other: ZObject) -> Self {
        self.extend(other)
    }

    /// Make all fields optional: null/missing values return `null` in the output
    /// instead of failing validation.
    ///
    /// Equivalent to Zod's `.partial()`.
    pub fn partial(mut self) -> Self {
        self.fields = self
            .fields
            .into_iter()
            .map(|f| ObjectField {
                name: f.name,
                schema: Box::new(OptionalDynSchema(f.schema)),
            })
            .collect();
        self
    }

    /// Make all fields required: null values will fail validation.
    /// This is the opposite of [`partial()`](Self::partial).
    pub fn required(mut self) -> Self {
        self.fields = self
            .fields
            .into_iter()
            .map(|f| ObjectField {
                name: f.name,
                schema: Box::new(RequiredDynSchema(f.schema)),
            })
            .collect();
        self
    }

    /// Validate unknown fields using the given schema instead of stripping/rejecting them.
    ///
    /// When set, unknown fields are parsed through the catchall schema
    /// regardless of the unknown field mode.
    pub fn catchall<S: DynSchema + Send + Sync + 'static>(mut self, schema: S) -> Self {
        self.catchall_schema = Some(Box::new(schema));
        self
    }

    /// Add a conditional validation rule.
    ///
    /// When `condition_field` has the given value, `target_field` is validated
    /// with the provided schema **in addition** to any existing field schemas.
    /// Under [`strict()`](Self::strict) an undeclared `target_field` is not
    /// reported as unrecognized.
    ///
    /// # Example
    /// ```
    /// use vld::prelude::*;
    ///
    /// let schema = vld::object()
    ///     .field("role", vld::string())
    ///     .field_optional("admin_key", vld::string())
    ///     .when("role", "admin", "admin_key", vld::string().min(10));
    ///
    /// // When role != "admin", admin_key is optional and any value is fine
    /// let ok = schema.parse(r#"{"role": "user"}"#);
    /// assert!(ok.is_ok());
    ///
    /// // When role == "admin", admin_key must pass the extra schema
    /// let err = schema.parse(r#"{"role": "admin", "admin_key": "short"}"#);
    /// assert!(err.is_err());
    /// ```
    pub fn when<S: DynSchema + Send + Sync + 'static>(
        mut self,
        condition_field: impl Into<String>,
        condition_value: impl Into<serde_json::Value>,
        target_field: impl Into<String>,
        schema: S,
    ) -> Self {
        self.conditional_rules.push(ConditionalRule {
            condition_field: condition_field.into(),
            condition_value: condition_value.into(),
            target_field: target_field.into(),
            schema: Box::new(schema),
        });
        self
    }

    /// Require at least this many keys in the input object.
    pub fn min_keys(mut self, n: usize) -> Self {
        self.min_keys = Some(n);
        self
    }

    /// Require at most this many keys in the input object.
    pub fn max_keys(mut self, n: usize) -> Self {
        self.max_keys = Some(n);
        self
    }

    /// Get the list of field names defined in this schema.
    pub fn keyof(&self) -> Vec<String> {
        self.fields.iter().map(|f| f.name.clone()).collect()
    }
}

impl ZObject {
    /// JSON Schema of this object; same as
    /// [`JsonSchema::json_schema`](crate::openapi::JsonSchema::json_schema).
    #[cfg(feature = "openapi")]
    #[cfg_attr(docsrs, doc(cfg(feature = "openapi")))]
    pub fn to_json_schema(&self) -> Value {
        crate::openapi::JsonSchema::json_schema(self)
    }
}

impl Default for ZObject {
    fn default() -> Self {
        Self::new()
    }
}

impl VldSchema for ZObject {
    type Output = Map<String, Value>;

    fn parse_value(&self, value: &Value) -> Result<Map<String, Value>, VldError> {
        let obj = crate::error::expect_object(value)?;

        let mut result = Map::new();
        let mut errors = VldError::new();
        // An inner `Err` may carry no issues: track failure, not issue count.
        let mut failed = false;

        if let Some(min) = self.min_keys {
            if obj.len() < min {
                errors.push_code(IssueCode::TooSmall {
                    origin: SizeOrigin::Object,
                    minimum: min.into(),
                    inclusive: true,
                });
            }
        }
        if let Some(max) = self.max_keys {
            if obj.len() > max {
                errors.push_code(IssueCode::TooBig {
                    origin: SizeOrigin::Object,
                    maximum: max.into(),
                    inclusive: true,
                });
            }
        }

        // Validate defined fields
        for field in &self.fields {
            let parsed = match obj.get(&field.name) {
                Some(v) => field.schema.dyn_parse(v),
                None => field
                    .schema
                    .dyn_parse_missing()
                    .map_err(crate::error::absent_field_error),
            };
            match parsed {
                Ok(v) => {
                    result.insert(field.name.clone(), v);
                }
                Err(e) => {
                    failed = true;
                    errors = errors.merge(e.with_prefix(PathSegment::Field(field.name.clone())));
                }
            }
        }

        // Handle unknown fields
        let known_keys: std::collections::HashSet<&str> =
            self.fields.iter().map(|f| f.name.as_str()).collect();
        let unknown_keys: Vec<&String> = obj
            .keys()
            .filter(|k| !known_keys.contains(&k.as_str()))
            .collect();

        if let Some(catchall) = &self.catchall_schema {
            for key in &unknown_keys {
                let val = &obj[key.as_str()];
                match catchall.dyn_parse(val) {
                    Ok(v) => {
                        result.insert((*key).clone(), v);
                    }
                    Err(e) => {
                        failed = true;
                        errors = errors.merge(e.with_prefix(PathSegment::Field((*key).clone())));
                    }
                }
            }
        } else {
            match self.unknown_mode {
                UnknownFieldMode::Strip => {}
                UnknownFieldMode::Strict => {
                    let is_target =
                        |k: &str| self.conditional_rules.iter().any(|r| r.target_field == k);
                    for key in unknown_keys.iter().filter(|k| !is_target(k)) {
                        errors = errors.merge(
                            VldError::from_code(IssueCode::UnrecognizedField)
                                .with_prefix(PathSegment::Field((*key).clone())),
                        );
                    }
                }
                UnknownFieldMode::Passthrough => {
                    for key in &unknown_keys {
                        result.insert((*key).clone(), obj[key.as_str()].clone());
                    }
                }
            }
        }

        // Evaluate conditional rules
        for rule in &self.conditional_rules {
            let cond_val = obj.get(&rule.condition_field).unwrap_or(&Value::Null);
            if *cond_val == rule.condition_value {
                let target_val = obj.get(&rule.target_field).unwrap_or(&Value::Null);
                if let Err(e) = rule.schema.dyn_parse(target_val) {
                    failed = true;
                    errors =
                        errors.merge(e.with_prefix(PathSegment::Field(rule.target_field.clone())));
                }
            }
        }

        if errors.is_empty() && !failed {
            Ok(result)
        } else {
            Err(errors)
        }
    }
}

/// Properties from the fields (with their own schemas and `required` status);
/// `additionalProperties` is `false` for `strict()`, the catchall schema when
/// set, `true` otherwise.
#[cfg(feature = "openapi")]
impl crate::openapi::JsonSchema for ZObject {
    fn json_schema(&self) -> Value {
        let required: Vec<&str> = self
            .fields
            .iter()
            .filter(|f| f.schema.dyn_is_required())
            .map(|f| f.name.as_str())
            .collect();
        let props: Map<String, Value> = self
            .fields
            .iter()
            .map(|f| (f.name.clone(), f.schema.dyn_json_schema()))
            .collect();
        let mut schema = serde_json::json!({
            "type": "object",
            "properties": props,
            "additionalProperties": self.unknown_mode != UnknownFieldMode::Strict,
        });
        if !required.is_empty() {
            schema["required"] = serde_json::json!(required);
        }
        if let Some(ref catchall) = self.catchall_schema {
            schema["additionalProperties"] = catchall.dyn_json_schema();
        }
        if let Some(min) = self.min_keys {
            schema["minProperties"] = serde_json::json!(min);
        }
        if let Some(max) = self.max_keys {
            schema["maxProperties"] = serde_json::json!(max);
        }
        schema
    }
}

#[cfg(feature = "openapi")]
impl crate::openapi::CollectNestedSchemas for ZObject {
    fn collect_nested_schemas(&self, out: &mut Vec<crate::schema::NestedSchemaEntry>) {
        let fields = self.fields.iter().map(|f| &f.schema);
        let rules = self.conditional_rules.iter().map(|r| &r.schema);
        for s in fields.chain(rules).chain(self.catchall_schema.iter()) {
            s.dyn_collect_nested_schemas(out);
        }
    }
}