domainstack 1.1.1

Write validation once, use everywhere: Rust rules auto-generate JSON Schema + OpenAPI + TypeScript/Zod. WASM browser validation. Axum/Actix/Rocket adapters.
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
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
use crate::{Meta, Path, Violation};
use smallvec::SmallVec;
use std::collections::BTreeMap;

/// Represents a collection of validation violations.
///
/// This type aggregates all validation errors that occur during validation of a domain object.
/// It supports merging errors from multiple fields and nested structures.
///
/// # Examples
///
/// ```
/// use domainstack::{ValidationError, Path};
///
/// let mut err = ValidationError::new();
/// err.push("email", "invalid_email", "Invalid email format");
/// err.push("age", "out_of_range", "Must be between 18 and 120");
///
/// assert_eq!(err.violations.len(), 2);
/// assert!(!err.is_empty());
/// ```
///
/// ## Nested Errors
///
/// ```
/// use domainstack::{ValidationError, Path};
///
/// let mut child_err = ValidationError::new();
/// child_err.push("value", "invalid_email", "Invalid email format");
///
/// let mut parent_err = ValidationError::new();
/// parent_err.merge_prefixed("email", child_err);
///
/// // Error path becomes "email.value"
/// assert_eq!(parent_err.violations[0].path.to_string(), "email.value");
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ValidationError {
    pub violations: SmallVec<[Violation; 4]>,
}

impl ValidationError {
    pub fn new() -> Self {
        Self {
            violations: SmallVec::new(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.violations.is_empty()
    }

    pub fn single(path: impl Into<Path>, code: &'static str, message: impl Into<String>) -> Self {
        let mut err = Self::new();
        err.push(path, code, message);
        err
    }

    pub fn push(&mut self, path: impl Into<Path>, code: &'static str, message: impl Into<String>) {
        self.violations.push(Violation {
            path: path.into(),
            code,
            message: message.into(),
            meta: Meta::default(),
        });
    }

    pub fn extend(&mut self, other: ValidationError) {
        self.violations.extend(other.violations);
    }

    /// Merges violations from another error with a path prefix.
    ///
    /// This is optimized to avoid cloning the prefix for each violation.
    /// The prefix segments are collected once and reused for all violations.
    ///
    /// # Performance
    /// - Old: O(n) prefix clones where n = number of violations
    /// - New: O(1) prefix collection + O(n * m) segment clones where m = avg segments per path
    ///
    /// For typical use cases (< 10 violations), this optimization reduces allocations significantly.
    pub fn merge_prefixed(&mut self, prefix: impl Into<Path>, other: ValidationError) {
        let prefix = prefix.into();

        // Collect prefix segments once to avoid repeated cloning
        let prefix_segments = prefix.segments().to_vec();

        for mut violation in other.violations {
            // Build new path from prefix segments + violation segments
            let mut new_path = Path::root();

            // Add prefix segments
            for seg in &prefix_segments {
                match seg {
                    crate::PathSegment::Field(name) => new_path.push_field(name.clone()),
                    crate::PathSegment::Index(idx) => new_path.push_index(*idx),
                }
            }

            // Add violation's original path segments
            for seg in violation.path.segments() {
                match seg {
                    crate::PathSegment::Field(name) => new_path.push_field(name.clone()),
                    crate::PathSegment::Index(idx) => new_path.push_index(*idx),
                }
            }

            violation.path = new_path;
            self.violations.push(violation);
        }
    }

    /// Returns a map of field paths to error messages.
    ///
    /// **⚠️ Warning**: This method only returns messages and **loses error codes and metadata**.
    /// For complete error information including codes (needed for proper error classification,
    /// client-side handling, and internationalization), use [`field_violations_map()`](Self::field_violations_map) instead.
    ///
    /// # Examples
    ///
    /// ```
    /// use domainstack::ValidationError;
    ///
    /// let mut err = ValidationError::new();
    /// err.push("email", "invalid_format", "Invalid email format");
    /// err.push("email", "too_long", "Email too long");
    ///
    /// let map = err.field_errors_map();
    /// assert_eq!(map.get("email").unwrap().len(), 2);
    /// // Note: Error codes "invalid_format" and "too_long" are lost!
    /// ```
    #[deprecated(
        since = "0.5.0",
        note = "Use `field_violations_map()` instead to preserve error codes and metadata. \
                This method only returns messages and loses important error information."
    )]
    pub fn field_errors_map(&self) -> BTreeMap<String, Vec<String>> {
        let mut map = BTreeMap::new();
        for violation in &self.violations {
            map.entry(violation.path.to_string())
                .or_insert_with(Vec::new)
                .push(violation.message.clone());
        }
        map
    }

    pub fn field_violations_map(&self) -> BTreeMap<String, Vec<&Violation>> {
        let mut map = BTreeMap::new();
        for violation in &self.violations {
            map.entry(violation.path.to_string())
                .or_insert_with(Vec::new)
                .push(violation);
        }
        map
    }

    /// Returns a new ValidationError with all paths prefixed.
    ///
    /// # Performance
    /// This method is optimized to collect prefix segments once and reuse them,
    /// avoiding repeated cloning of the prefix path.
    pub fn prefixed(self, prefix: impl Into<Path>) -> Self {
        let prefix = prefix.into();

        // Collect prefix segments once to avoid repeated cloning
        let prefix_segments: Vec<_> = prefix.segments().to_vec();

        let violations = self
            .violations
            .into_iter()
            .map(|mut v| {
                let mut new_path = Path::root();

                // Add prefix segments
                for seg in &prefix_segments {
                    match seg {
                        crate::PathSegment::Field(name) => new_path.push_field(name.clone()),
                        crate::PathSegment::Index(idx) => new_path.push_index(*idx),
                    }
                }

                // Add violation's original path segments
                for seg in v.path.segments() {
                    match seg {
                        crate::PathSegment::Field(name) => new_path.push_field(name.clone()),
                        crate::PathSegment::Index(idx) => new_path.push_index(*idx),
                    }
                }

                v.path = new_path;
                v
            })
            .collect();

        Self { violations }
    }

    /// Transform all violation messages using the provided function.
    ///
    /// This is useful for internationalization (i18n), message formatting,
    /// or any other message transformation needs.
    ///
    /// # Examples
    ///
    /// ```
    /// use domainstack::ValidationError;
    ///
    /// let mut err = ValidationError::new();
    /// err.push("email", "invalid", "Invalid email");
    /// err.push("age", "too_young", "Must be 18+");
    ///
    /// // Add prefix to all messages
    /// let err = err.map_messages(|msg| format!("Error: {}", msg));
    ///
    /// assert_eq!(err.violations[0].message, "Error: Invalid email");
    /// assert_eq!(err.violations[1].message, "Error: Must be 18+");
    /// ```
    ///
    /// ## Internationalization Example
    ///
    /// ```
    /// use domainstack::ValidationError;
    ///
    /// let mut err = ValidationError::new();
    /// err.push("email", "invalid_email", "Invalid email format");
    ///
    /// // Translate messages based on error code
    /// let err = err.map_messages(|msg| {
    ///     // In a real app, this would use error codes for translation
    ///     "Formato de email inválido".to_string()
    /// });
    ///
    /// assert_eq!(err.violations[0].message, "Formato de email inválido");
    /// ```
    pub fn map_messages<F>(mut self, f: F) -> Self
    where
        F: Fn(String) -> String,
    {
        for violation in &mut self.violations {
            let old_message = std::mem::take(&mut violation.message);
            violation.message = f(old_message);
        }
        self
    }

    /// Filter violations based on a predicate.
    ///
    /// This is useful for removing certain types of errors based on custom criteria.
    ///
    /// # Examples
    ///
    /// ```
    /// use domainstack::ValidationError;
    ///
    /// let mut err = ValidationError::new();
    /// err.push("email", "warning", "Email format questionable");
    /// err.push("age", "invalid", "Age is required");
    /// err.push("name", "warning", "Name seems unusual");
    ///
    /// // Remove all warnings, keep only errors
    /// let err = err.filter(|v| v.code != "warning");
    ///
    /// assert_eq!(err.violations.len(), 1);
    /// assert_eq!(err.violations[0].code, "invalid");
    /// ```
    pub fn filter<F>(self, f: F) -> Self
    where
        F: Fn(&Violation) -> bool,
    {
        let violations = self.violations.into_iter().filter(|v| f(v)).collect();
        Self { violations }
    }
}

impl std::fmt::Display for ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.violations.is_empty() {
            write!(f, "No validation errors")
        } else if self.violations.len() == 1 {
            write!(f, "Validation error: {}", self.violations[0].message)
        } else {
            write!(f, "Validation failed with {} errors", self.violations.len())
        }
    }
}

impl std::error::Error for ValidationError {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_new() {
        let err = ValidationError::new();
        assert!(err.is_empty());
        assert_eq!(err.violations.len(), 0);
    }

    #[test]
    fn test_default() {
        let err = ValidationError::default();
        assert!(err.is_empty());
    }

    #[test]
    fn test_is_empty() {
        let mut err = ValidationError::new();
        assert!(err.is_empty());

        err.push("email", "invalid", "Invalid email");
        assert!(!err.is_empty());
    }

    #[test]
    fn test_single() {
        let err = ValidationError::single("email", "invalid_email", "Invalid email format");

        assert!(!err.is_empty());
        assert_eq!(err.violations.len(), 1);
        assert_eq!(err.violations[0].code, "invalid_email");
        assert_eq!(err.violations[0].message, "Invalid email format");
        assert_eq!(err.violations[0].path.to_string(), "email");
    }

    #[test]
    fn test_push() {
        let mut err = ValidationError::new();
        err.push("email", "invalid_email", "Invalid email");
        err.push("age", "out_of_range", "Age out of range");

        assert_eq!(err.violations.len(), 2);
        assert_eq!(err.violations[0].path.to_string(), "email");
        assert_eq!(err.violations[1].path.to_string(), "age");
    }

    #[test]
    fn test_extend() {
        let mut err1 = ValidationError::new();
        err1.push("email", "invalid", "Invalid email");

        let mut err2 = ValidationError::new();
        err2.push("age", "invalid", "Invalid age");

        err1.extend(err2);
        assert_eq!(err1.violations.len(), 2);
    }

    #[test]
    fn test_merge_prefixed() {
        let mut parent_err = ValidationError::new();

        let mut child_err = ValidationError::new();
        child_err.push("email", "invalid", "Invalid email");

        parent_err.merge_prefixed("guest", child_err);

        assert_eq!(parent_err.violations.len(), 1);
        assert_eq!(parent_err.violations[0].path.to_string(), "guest.email");
    }

    #[test]
    fn test_merge_prefixed_nested() {
        let mut root_err = ValidationError::new();

        let mut nested_err = ValidationError::new();
        nested_err.push(
            Path::root().field("guests").index(0).field("email"),
            "invalid",
            "Invalid email",
        );

        root_err.merge_prefixed("booking", nested_err);

        assert_eq!(root_err.violations.len(), 1);
        assert_eq!(
            root_err.violations[0].path.to_string(),
            "booking.guests[0].email"
        );
    }

    #[test]
    #[allow(deprecated)]
    fn test_field_errors_map() {
        let mut err = ValidationError::new();
        err.push("email", "invalid", "Invalid email");
        err.push("email", "too_long", "Email too long");
        err.push("age", "out_of_range", "Age out of range");

        let map = err.field_errors_map();

        assert_eq!(map.len(), 2);
        assert_eq!(map.get("email").unwrap().len(), 2);
        assert_eq!(map.get("age").unwrap().len(), 1);
        assert!(map
            .get("email")
            .unwrap()
            .contains(&"Invalid email".to_string()));
        assert!(map
            .get("email")
            .unwrap()
            .contains(&"Email too long".to_string()));
    }

    #[test]
    fn test_display_empty() {
        let err = ValidationError::new();
        assert_eq!(err.to_string(), "No validation errors");
    }

    #[test]
    fn test_display_single() {
        let err = ValidationError::single("email", "invalid", "Invalid email format");
        assert_eq!(err.to_string(), "Validation error: Invalid email format");
    }

    #[test]
    fn test_display_multiple() {
        let mut err = ValidationError::new();
        err.push("email", "invalid", "Invalid email");
        err.push("age", "invalid", "Invalid age");

        assert_eq!(err.to_string(), "Validation failed with 2 errors");
    }

    #[test]
    fn test_validation_error_equality() {
        let mut err1 = ValidationError::new();
        err1.push("email", "invalid", "Invalid email");
        err1.push("age", "out_of_range", "Age out of range");

        let mut err2 = ValidationError::new();
        err2.push("email", "invalid", "Invalid email");
        err2.push("age", "out_of_range", "Age out of range");

        assert_eq!(err1, err2);

        let mut err3 = ValidationError::new();
        err3.push("email", "invalid", "Invalid email");

        assert_ne!(err1, err3);
    }

    #[test]
    fn test_validation_error_equality_empty() {
        let err1 = ValidationError::new();
        let err2 = ValidationError::default();
        assert_eq!(err1, err2);
    }

    #[test]
    fn test_map_messages() {
        let mut err = ValidationError::new();
        err.push("email", "invalid", "Invalid email");
        err.push("age", "out_of_range", "Age out of range");

        let err = err.map_messages(|msg| format!("Error: {}", msg));

        assert_eq!(err.violations[0].message, "Error: Invalid email");
        assert_eq!(err.violations[1].message, "Error: Age out of range");
    }

    #[test]
    fn test_map_messages_preserves_other_fields() {
        let mut err = ValidationError::new();
        err.push("email", "invalid", "Invalid email");

        let err = err.map_messages(|msg| format!("Modified: {}", msg));

        assert_eq!(err.violations[0].code, "invalid");
        assert_eq!(err.violations[0].path.to_string(), "email");
        assert_eq!(err.violations[0].message, "Modified: Invalid email");
    }

    #[test]
    fn test_filter() {
        let mut err = ValidationError::new();
        err.push("email", "warning", "Email questionable");
        err.push("age", "invalid", "Age required");
        err.push("name", "warning", "Name unusual");

        let err = err.filter(|v| v.code != "warning");

        assert_eq!(err.violations.len(), 1);
        assert_eq!(err.violations[0].code, "invalid");
        assert_eq!(err.violations[0].path.to_string(), "age");
    }

    #[test]
    fn test_filter_all() {
        let mut err = ValidationError::new();
        err.push("email", "warning", "Email questionable");
        err.push("name", "warning", "Name unusual");

        let err = err.filter(|v| v.code != "warning");

        assert!(err.is_empty());
    }

    #[test]
    fn test_filter_none() {
        let mut err = ValidationError::new();
        err.push("email", "invalid", "Invalid email");
        err.push("age", "out_of_range", "Age out of range");

        let err = err.filter(|_| true);

        assert_eq!(err.violations.len(), 2);
    }
}