Skip to main content

vld_http_common/
lib.rs

1//! # vld-http-common — Shared HTTP helpers for `vld` web integrations
2//!
3//! This crate provides the common parsing helpers and the shared
4//! [`VldHttpError`] type used by `vld-actix`, `vld-axum`, `vld-ntex`,
5//! `vld-poem`, `vld-rama`, `vld-rocket`, `vld-salvo`, `vld-tower`,
6//! `vld-warp` and `vld-tonic`.
7//!
8//! Applications normally use it through a framework adapter. Depend on it
9//! directly to write an adapter for another framework or to build the same
10//! error body by hand. It is framework-agnostic: no HTTP framework or `http`
11//! crate dependency.
12//!
13//! Guide: <https://s00d.github.io/vld/integrations/shared/http-common>
14//! (the rules below, per framework:
15//! <https://s00d.github.io/vld/integrations/web/overview>).
16//!
17//! # Example
18//!
19//! ```
20//! use vld_http_common::{parse_json_body, require_json_content_type, VldHttpError};
21//!
22//! vld::schema! {
23//!     #[derive(Debug)]
24//!     pub struct User {
25//!         pub name: String => vld::string().min(2),
26//!     }
27//! }
28//!
29//! fn extract(content_type: Option<&str>, body: &[u8]) -> Result<User, VldHttpError> {
30//!     require_json_content_type(content_type)?; // 415
31//!     let value = parse_json_body(body)?;       // 422 on malformed JSON
32//!     Ok(User::parse_value(&value)?)            // 422 on validation errors
33//! }
34//!
35//! let err = extract(Some("application/json"), br#"{"name": "A"}"#).unwrap_err();
36//! assert_eq!(err.status(), 422);
37//! assert_eq!(err.body()["issues"][0]["code"], "too_small");
38//! assert_eq!(extract(Some("text/plain"), b"{}").unwrap_err().status(), 415);
39//!
40//! // Text sources (query, form, path, headers, cookies) use `parse_coerced`.
41//! vld::schema! {
42//!     #[derive(Debug)]
43//!     pub struct Search {
44//!         pub q: String => vld::string(),
45//!         pub page: i64 => vld::number().int().min(1),
46//!         pub tags: Vec<String> => vld::array(vld::string()),
47//!     }
48//! }
49//!
50//! let value = vld_http_common::query_string_to_json("q=123&page=2&tags=a");
51//! let s: Search = vld_http_common::parse_coerced(&value).unwrap();
52//! assert_eq!((s.q.as_str(), s.page, s.tags.len()), ("123", 2, 1));
53//! ```
54//!
55//! # Value semantics (all adapters)
56//!
57//! - Query strings and form bodies: repeated keys (`a=1&a=2`) and `a[]=1`
58//!   become arrays; `?flag` and `?x=` become `""`.
59//! - Values are coerced with [`coerce_value`], which never loses information.
60//! - Coerced sources are validated with [`parse_coerced`]: a coerced number /
61//!   boolean is turned back into text where the schema expects a string
62//!   (`?q=123` into `vld::string()` is `"123"`), and a single value is
63//!   wrapped into an array where the schema expects one (`?tags=a`).
64//! - JSON body extractors require a JSON `Content-Type` (`application/json`
65//!   or `application/*+json`, see [`is_json_content_type`]) and form
66//!   extractors `application/x-www-form-urlencoded`
67//!   ([`require_form_content_type`]); a missing or different type is **415**
68//!   `{"error": "Unsupported Media Type", "message": ...}`.
69//! - Malformed bodies (JSON, non-UTF-8 forms, more than [`MAX_FORM_FIELDS`]
70//!   form fields) → **422** with the [`ValidationErrorBody`] shape; oversized
71//!   bodies → **413** `{"error": "Payload too large"}`.
72//! - Header names containing `_` are ignored (see [`headers_to_json`]); all
73//!   `Cookie` headers are read and the first occurrence of a cookie name wins
74//!   (see [`cookie_headers_to_json`]).
75//!
76//! # Error bodies
77//!
78//! | Status | Body |
79//! |---|---|
80//! | 422 | `{"error": "Validation failed", "issues": [{"path": ".name", "message": "...", "code": "too_small"}]}` |
81//! | 413 | `{"error": "Payload too large"}` |
82//! | 415 | `{"error": "Unsupported Media Type", "message": "Expected Content-Type: ..."}` |
83//!
84//! `path` is `""` for the root (e.g. malformed JSON), `.field` for fields and
85//! `[0]` for array items (`.items[0].name`); `code` is
86//! [`IssueCode::key()`](vld::error::IssueCode::key).
87#![warn(missing_docs)]
88
89pub use vld::schema::parse_coerced;
90
91/// Default max request body size (2 MiB — same as axum `DefaultBodyLimit`).
92///
93/// Every adapter applies it to JSON and form bodies unless a limit is
94/// configured ([`VldBodyLimit`], the framework's own setting, or a
95/// constructor argument; per adapter:
96/// <https://s00d.github.io/vld/integrations/web/overview#body-limits>).
97pub const DEFAULT_BODY_LIMIT: usize = 2 * 1024 * 1024;
98
99/// Max number of `&`-separated fields in a form body ([`parse_form_body`]).
100///
101/// Caps the memory a small body can expand into (`a&a&a&…` turns every two
102/// bytes into a JSON value); more fields are a 422 parse error.
103pub const MAX_FORM_FIELDS: usize = 1000;
104
105/// Body size limit in bytes, registered as request/app data for the adapters
106/// without a framework-native body limit setting (`vld-actix` `app_data`,
107/// `vld-ntex` app state, `vld-poem` `.data(..)`; `vld-rama` has its own
108/// extension type).
109///
110/// Without it those adapters use [`DEFAULT_BODY_LIMIT`].
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub struct VldBodyLimit(pub usize);
113
114/// Shared adapter conformance suite (test support, `conformance` feature).
115#[cfg(feature = "conformance")]
116pub mod conformance;
117
118/// Coerce a raw string value (query, form, path, header, cookie) into JSON.
119///
120/// Coercion never loses information: a value is only converted when the
121/// conversion round-trips to exactly the same text.
122///
123/// - `"true"` / `"false"` (lowercase only) → `Bool`
124/// - canonical integers (`0`, `42`, `-7`; no `+`, no leading zeros) that fit
125///   `i64`/`u64` → `Number`
126/// - canonical decimals (`3.14`, `-0.5`; no exponent, no trailing zeros, no
127///   precision loss in `f64`) → `Number`
128/// - everything else — including `""`, `"null"`, `"01234"`, `"+1555"`,
129///   `"1e3"`, `"TRUE"` and ids beyond `u64` — stays a `String`
130///
131/// Use `vld::string().coerce()` / `vld::number().coerce()` in schemas when a
132/// field must accept both forms (e.g. a string field that may look numeric).
133pub fn coerce_value(raw: &str) -> serde_json::Value {
134    use serde_json::Value;
135    match raw {
136        "true" => return Value::Bool(true),
137        "false" => return Value::Bool(false),
138        _ => {}
139    }
140    if is_canonical_number(raw) {
141        if !raw.contains('.') {
142            if let Ok(n) = raw.parse::<i64>() {
143                return Value::Number(n.into());
144            }
145            if let Ok(n) = raw.parse::<u64>() {
146                return Value::Number(n.into());
147            }
148        } else if let Ok(f) = raw.parse::<f64>() {
149            // `f64` Display is the shortest round-trip form: `1.50` → `1.5`,
150            // `0.1000000000000000001` → `0.1`; both stay strings.
151            if f.is_finite() && f.to_string() == raw {
152                if let Some(n) = serde_json::Number::from_f64(f) {
153                    return Value::Number(n);
154                }
155            }
156        }
157    }
158    Value::String(raw.to_string())
159}
160
161/// `-?(0|[1-9][0-9]*)(\.[0-9]+)?`, excluding `-0`.
162fn is_canonical_number(s: &str) -> bool {
163    let negative = s.starts_with('-');
164    let digits = s.strip_prefix('-').unwrap_or(s);
165    let (int, frac) = match digits.split_once('.') {
166        Some((i, f)) => (i, Some(f)),
167        None => (digits, None),
168    };
169    let all_digits = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit());
170    if !all_digits(int) || (int.len() > 1 && int.starts_with('0')) {
171        return false;
172    }
173    if frac.is_some_and(|f| !all_digits(f)) {
174        return false;
175    }
176    !(negative && frac.is_none() && int == "0")
177}
178
179/// Parse a URL query string (or `application/x-www-form-urlencoded` body)
180/// into a `serde_json::Map`.
181///
182/// - keys and values are form-decoded ([`url_decode`]) and values coerced via
183///   [`coerce_value`];
184/// - a key without `=` (`?flag`) yields `""`, like `URLSearchParams`;
185/// - a repeated key (`a=1&a=2`) yields an array `[1, 2]`;
186/// - a key ending in `[]` (`a[]=1`) always yields an array under `a`.
187pub fn parse_query_string(query: &str) -> serde_json::Map<String, serde_json::Value> {
188    use serde_json::Value;
189    let mut map = serde_json::Map::new();
190
191    for pair in query.split('&').filter(|p| !p.is_empty()) {
192        let (key, raw_value) = pair.split_once('=').unwrap_or((pair, ""));
193        let mut key = url_decode(key);
194        let value = coerce_value(&url_decode(raw_value));
195
196        let force_array = key.ends_with("[]");
197        if force_array {
198            key.truncate(key.len() - 2);
199        }
200
201        match map.get_mut(&key) {
202            Some(Value::Array(items)) => items.push(value),
203            Some(existing) => {
204                let first = existing.take();
205                *existing = Value::Array(vec![first, value]);
206            }
207            None if force_array => {
208                map.insert(key, Value::Array(vec![value]));
209            }
210            None => {
211                map.insert(key, value);
212            }
213        }
214    }
215
216    map
217}
218
219/// Parse a URL query string into a `serde_json::Value::Object`.
220///
221/// Convenience wrapper around [`parse_query_string`].
222pub fn query_string_to_json(query: &str) -> serde_json::Value {
223    serde_json::Value::Object(parse_query_string(query))
224}
225
226/// Build a JSON object from a `Cookie` header value.
227///
228/// Cookie names are used as-is. Values are unquoted (`"abc"` → `abc`),
229/// percent-decoded (`+` is kept) and coerced via [`coerce_value`].
230///
231/// When a name repeats (`sid=legit; sid=evil`) the **first** occurrence
232/// wins, as in most cookie parsers (browsers send the most specific path
233/// first); letting a later one win enables cookie tossing from a sibling
234/// subdomain.
235pub fn cookies_to_json(cookie_header: &str) -> serde_json::Value {
236    let mut map = serde_json::Map::new();
237
238    for cookie in cookie_header.split(';') {
239        let cookie = cookie.trim();
240        if cookie.is_empty() {
241            continue;
242        }
243        let (name, value) = cookie.split_once('=').unwrap_or((cookie, ""));
244        let value = value.trim();
245        let value = value
246            .strip_prefix('"')
247            .and_then(|v| v.strip_suffix('"'))
248            .unwrap_or(value);
249        map.entry(name.trim())
250            .or_insert_with(|| coerce_value(&percent_decode(value)));
251    }
252
253    serde_json::Value::Object(map)
254}
255
256/// Build a JSON object from **all** `Cookie` header values of a request.
257///
258/// HTTP/2 clients may send one `Cookie` header per cookie, so the values are
259/// joined with `"; "` before [`cookies_to_json`] (the first occurrence of a
260/// name wins). Non-UTF-8 bytes become `U+FFFD`.
261pub fn cookie_headers_to_json<'a, I>(values: I) -> serde_json::Value
262where
263    I: IntoIterator<Item = &'a [u8]>,
264{
265    let values: Vec<_> = values.into_iter().map(String::from_utf8_lossy).collect();
266    cookies_to_json(&values.join("; "))
267}
268
269/// Build a JSON object from HTTP header name/value pairs.
270///
271/// - names are lowercased and `-` becomes `_` (`X-Request-Id` → `x_request_id`);
272/// - names that already contain `_` (`x_user`) are **skipped**: a client
273///   could otherwise fill the `x_user` field past a proxy that strips only
274///   `X-User` (nginx, for one, also drops such names by default);
275/// - non-UTF-8 bytes become `U+FFFD` instead of silently dropping the header;
276/// - repeated headers are joined with `", "` (RFC 9110 §5.3);
277/// - the joined value is coerced via [`coerce_value`].
278pub fn headers_to_json<'a, I>(headers: I) -> serde_json::Value
279where
280    I: IntoIterator<Item = (&'a str, &'a [u8])>,
281{
282    let mut map = serde_json::Map::new();
283    let mut raw: Vec<(String, String)> = Vec::new();
284    for (name, value) in headers {
285        if name.contains('_') {
286            continue;
287        }
288        let key = name.to_ascii_lowercase().replace('-', "_");
289        let value = String::from_utf8_lossy(value);
290        match raw.iter_mut().find(|(k, _)| *k == key) {
291            Some((_, v)) => {
292                v.push_str(", ");
293                v.push_str(&value);
294            }
295            None => raw.push((key, value.into_owned())),
296        }
297    }
298    for (k, v) in raw {
299        map.insert(k, coerce_value(&v));
300    }
301    serde_json::Value::Object(map)
302}
303
304/// Build a JSON object from already-decoded path parameters, coercing each
305/// value via [`coerce_value`].
306pub fn path_params_to_json<'a, I>(params: I) -> serde_json::Value
307where
308    I: IntoIterator<Item = (&'a str, &'a str)>,
309{
310    serde_json::Value::Object(
311        params
312            .into_iter()
313            .map(|(k, v)| (k.to_string(), coerce_value(v)))
314            .collect(),
315    )
316}
317
318/// Parse an `application/x-www-form-urlencoded` body.
319///
320/// Fails with a 422 parse error when the body is not valid UTF-8 or has more
321/// than [`MAX_FORM_FIELDS`] fields.
322pub fn parse_form_body(body: &[u8]) -> Result<serde_json::Value, VldHttpError> {
323    let s = std::str::from_utf8(body)
324        .map_err(|_| VldHttpError::parse("Form body is not valid UTF-8"))?;
325    if s.split('&').filter(|p| !p.is_empty()).count() > MAX_FORM_FIELDS {
326        return Err(VldHttpError::parse(format!(
327            "Too many form fields (max {MAX_FORM_FIELDS})"
328        )));
329    }
330    Ok(query_string_to_json(s))
331}
332
333/// Parse a JSON body; malformed JSON is a 422 parse error.
334pub fn parse_json_body(body: &[u8]) -> Result<serde_json::Value, VldHttpError> {
335    serde_json::from_slice(body).map_err(|e| VldHttpError::parse(format!("Invalid JSON: {e}")))
336}
337
338/// The media type without parameters, trimmed and lowercased
339/// (`Application/JSON; charset=utf-8` → `application/json`).
340fn media_type_essence(content_type: &str) -> String {
341    content_type
342        .split(';')
343        .next()
344        .unwrap_or("")
345        .trim()
346        .to_ascii_lowercase()
347}
348
349/// `true` for `application/json` and any `application/<x>+json` media type
350/// with a non-empty `<x>` (case-insensitive; parameters such as
351/// `; charset=utf-8` are ignored, even malformed ones).
352pub fn is_json_content_type(content_type: &str) -> bool {
353    let essence = media_type_essence(content_type);
354    essence == "application/json"
355        || essence
356            .strip_prefix("application/")
357            .and_then(|s| s.strip_suffix("+json"))
358            .is_some_and(|prefix| !prefix.is_empty())
359}
360
361/// Check the `Content-Type` of a JSON body: `Ok` for JSON media types
362/// ([`is_json_content_type`]), otherwise a **415** error (also when the
363/// header is missing or not valid UTF-8).
364pub fn require_json_content_type(content_type: Option<&str>) -> Result<(), VldHttpError> {
365    match content_type {
366        Some(ct) if is_json_content_type(ct) => Ok(()),
367        _ => Err(VldHttpError::unsupported_media_type()),
368    }
369}
370
371/// Check the `Content-Type` of a form body: `Ok` for
372/// `application/x-www-form-urlencoded` (case-insensitive, parameters
373/// allowed), otherwise a **415** error (also when the header is missing or
374/// not valid UTF-8).
375pub fn require_form_content_type(content_type: Option<&str>) -> Result<(), VldHttpError> {
376    match content_type.map(media_type_essence) {
377        Some(ct) if ct == "application/x-www-form-urlencoded" => Ok(()),
378        _ => Err(VldHttpError::unsupported_form_media_type()),
379    }
380}
381
382// ---------------------------------------------------------------------------
383// Shared error type
384// ---------------------------------------------------------------------------
385
386/// Framework-independent error produced by all `vld` HTTP adapters.
387///
388/// | Constructor | Status | Body |
389/// |---|---|---|
390/// | [`validation`](Self::validation) / [`parse`](Self::parse) | 422 | [`ValidationErrorBody`] |
391/// | [`payload_too_large`](Self::payload_too_large) | 413 | [`ErrorBody`] |
392/// | [`unsupported_media_type`](Self::unsupported_media_type) / [`unsupported_form_media_type`](Self::unsupported_form_media_type) | 415 | [`ErrorWithMessage`] |
393///
394/// Adapters only convert [`status`](Self::status) and [`body`](Self::body)
395/// into their framework's response type.
396#[derive(Debug, Clone)]
397pub struct VldHttpError {
398    status: u16,
399    error: vld::error::VldError,
400}
401
402impl VldHttpError {
403    /// 422 — schema validation failed.
404    pub fn validation(error: vld::error::VldError) -> Self {
405        Self { status: 422, error }
406    }
407
408    /// 422 — the input could not be parsed (malformed JSON, bad UTF-8, ...).
409    pub fn parse(message: impl Into<String>) -> Self {
410        Self::validation(vld::error::VldError::single(
411            vld::error::IssueCode::ParseError,
412            message.into(),
413        ))
414    }
415
416    /// 413 — the body exceeds the size limit.
417    ///
418    /// [`error`](Self::error) holds a single `ParseError` issue
419    /// `"Payload too large"` (also what `Display` prints).
420    pub fn payload_too_large() -> Self {
421        Self {
422            status: 413,
423            error: vld::error::VldError::single(
424                vld::error::IssueCode::ParseError,
425                "Payload too large",
426            ),
427        }
428    }
429
430    /// 415 — a JSON body was sent without a JSON `Content-Type`.
431    ///
432    /// [`error`](Self::error) holds a single `ParseError` issue with
433    /// [`UNSUPPORTED_MEDIA_TYPE_MESSAGE`].
434    pub fn unsupported_media_type() -> Self {
435        Self::unsupported(UNSUPPORTED_MEDIA_TYPE_MESSAGE)
436    }
437
438    /// 415 — a form body was sent without
439    /// `Content-Type: application/x-www-form-urlencoded`.
440    ///
441    /// [`error`](Self::error) holds a single `ParseError` issue with
442    /// [`UNSUPPORTED_FORM_MEDIA_TYPE_MESSAGE`].
443    pub fn unsupported_form_media_type() -> Self {
444        Self::unsupported(UNSUPPORTED_FORM_MEDIA_TYPE_MESSAGE)
445    }
446
447    fn unsupported(message: &str) -> Self {
448        Self {
449            status: 415,
450            error: vld::error::VldError::single(vld::error::IssueCode::ParseError, message),
451        }
452    }
453
454    /// HTTP status code (422, 413 or 415).
455    #[must_use]
456    pub fn status(&self) -> u16 {
457        self.status
458    }
459
460    /// The underlying validation error.
461    pub fn error(&self) -> &vld::error::VldError {
462        &self.error
463    }
464
465    /// Consume and return the underlying validation error.
466    pub fn into_error(self) -> vld::error::VldError {
467        self.error
468    }
469
470    /// JSON response body for this error.
471    pub fn body(&self) -> serde_json::Value {
472        match self.status {
473            413 => format_payload_too_large(),
474            415 => serde_json::to_value(ErrorWithMessage {
475                error: "Unsupported Media Type".into(),
476                message: self
477                    .error
478                    .issues
479                    .first()
480                    .map_or(UNSUPPORTED_MEDIA_TYPE_MESSAGE, |i| i.message.as_str())
481                    .into(),
482            })
483            .expect("ErrorWithMessage serialization cannot fail"),
484            _ => format_vld_error(&self.error),
485        }
486    }
487}
488
489impl From<vld::error::VldError> for VldHttpError {
490    fn from(error: vld::error::VldError) -> Self {
491        Self::validation(error)
492    }
493}
494
495impl std::fmt::Display for VldHttpError {
496    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
497        match self.status {
498            413 => f.write_str("Payload too large"),
499            415 => f.write_str("Unsupported Media Type"),
500            _ => write!(f, "Validation failed: {}", self.error),
501        }
502    }
503}
504
505impl std::error::Error for VldHttpError {}
506
507/// Implement `Deref`/`DerefMut` to the inner value for tuple extractors
508/// `Name<T>(pub T)`.
509#[doc(hidden)]
510#[macro_export]
511macro_rules! impl_deref {
512    ($($name:ident),+ $(,)?) => {$(
513        impl<T> ::std::ops::Deref for $name<T> {
514            type Target = T;
515            fn deref(&self) -> &T {
516                &self.0
517            }
518        }
519        impl<T> ::std::ops::DerefMut for $name<T> {
520            fn deref_mut(&mut self) -> &mut T {
521                &mut self.0
522            }
523        }
524    )+};
525}
526
527// ---------------------------------------------------------------------------
528// Error response schemas (defined via vld::schema!)
529// ---------------------------------------------------------------------------
530
531use serde::Serialize;
532
533vld::schema! {
534    /// Simple error body: `{ "error": "..." }`.
535    ///
536    /// Used for generic HTTP errors such as "Payload too large",
537    /// "Not Found", "Method Not Allowed", etc.
538    #[derive(Debug, Clone, Serialize)]
539    pub struct ErrorBody {
540        /// Short error title.
541        pub error: String => vld::string(),
542    }
543}
544
545vld::schema! {
546    /// Error body with a message: `{ "error": "...", "message": "..." }`.
547    ///
548    /// The **415** body ([`VldHttpError::unsupported_media_type`],
549    /// [`VldHttpError::unsupported_form_media_type`]).
550    #[derive(Debug, Clone, Serialize)]
551    pub struct ErrorWithMessage {
552        /// Short error title.
553        pub error: String   => vld::string(),
554        /// Details.
555        pub message: String => vld::string(),
556    }
557}
558
559vld::schema! {
560    /// A single validation issue:
561    /// `{ "path": "...", "message": "...", "code": "..." }` (`code` is
562    /// [`IssueCode::key()`](vld::error::IssueCode::key)).
563    #[derive(Debug, Clone, Serialize)]
564    pub struct ValidationIssue {
565        /// Path of the invalid value (`.user.email`, `[0]`).
566        pub path: String    => vld::string(),
567        /// Human-readable message.
568        pub message: String => vld::string(),
569        /// Issue code key (`too_small`, `invalid_string`, …).
570        pub code: String    => vld::string(),
571    }
572}
573
574/// Same as [`ValidationIssue`], which always carries `code`.
575#[deprecated(since = "0.5.0", note = "use `ValidationIssue`")]
576pub type ValidationIssueWithCode = ValidationIssue;
577
578vld::schema! {
579    /// Validation error response body:
580    /// `{ "error": "Validation failed", "issues": [...] }`.
581    #[derive(Debug, Clone, Serialize)]
582    pub struct ValidationErrorBody {
583        /// Always `"Validation failed"`.
584        pub error: String => vld::string(),
585        /// Every issue found.
586        pub issues: Vec<ValidationIssue> => vld::array(vld::nested(ValidationIssue::parse_value)),
587    }
588}
589
590// ---------------------------------------------------------------------------
591// Formatting helpers
592// ---------------------------------------------------------------------------
593
594/// `.user.name`, `.items[0]` — spelled out instead of relying on
595/// `PathSegment`'s `Display` so the wire format stays stable.
596fn format_path(path: &[vld::error::PathSegment]) -> String {
597    use std::fmt::Write;
598    use vld::error::PathSegment;
599    let mut out = String::new();
600    for seg in path {
601        let _ = match seg {
602            PathSegment::Field(name) => write!(out, ".{name}"),
603            PathSegment::Index(idx) => write!(out, "[{idx}]"),
604        };
605    }
606    out
607}
608
609/// Format a [`VldError`](vld::error::VldError) into a list of
610/// [`ValidationIssue`] structs.
611pub fn format_issues(err: &vld::error::VldError) -> Vec<ValidationIssue> {
612    err.issues
613        .iter()
614        .map(|i| ValidationIssue {
615            path: format_path(&i.path),
616            message: i.message.clone(),
617            code: i.code.key().to_string(),
618        })
619        .collect()
620}
621
622/// Format a [`VldError`](vld::error::VldError) into a JSON object with
623/// `"error"` and `"issues"` keys — ready to be sent as a 422 response body.
624///
625/// Internally constructs a [`ValidationErrorBody`] and serializes it.
626pub fn format_vld_error(err: &vld::error::VldError) -> serde_json::Value {
627    let body = ValidationErrorBody {
628        error: "Validation failed".into(),
629        issues: format_issues(err),
630    };
631    serde_json::to_value(body).expect("ValidationErrorBody serialization cannot fail")
632}
633
634/// Same as [`format_issues`], which always includes `code`.
635#[deprecated(since = "0.5.0", note = "use `format_issues`")]
636pub fn format_issues_with_code(err: &vld::error::VldError) -> Vec<ValidationIssue> {
637    format_issues(err)
638}
639
640/// Decode a form/query component: `+` → space, then [`percent_decode`].
641pub fn url_decode(input: &str) -> String {
642    percent_decode(&input.replace('+', " "))
643}
644
645/// Percent-decode a URL component (path segment, cookie value); `+` is kept.
646///
647/// Only `%` followed by exactly two hex digits is decoded; anything else is
648/// kept literally. Decoded bytes are read as UTF-8 (`%C3%A9` → `é`); invalid
649/// sequences become `U+FFFD`.
650pub fn percent_decode(input: &str) -> String {
651    let bytes = input.as_bytes();
652    let hex = |i: usize| bytes.get(i).and_then(|&b| (b as char).to_digit(16));
653    let mut out = Vec::with_capacity(bytes.len());
654    let mut i = 0;
655    while i < bytes.len() {
656        if bytes[i] == b'%' {
657            if let (Some(h), Some(l)) = (hex(i + 1), hex(i + 2)) {
658                out.push((h * 16 + l) as u8);
659                i += 3;
660                continue;
661            }
662        }
663        out.push(bytes[i]);
664        i += 1;
665    }
666    String::from_utf8(out).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
667}
668
669// ---------------------------------------------------------------------------
670// Standard HTTP error response helpers
671// ---------------------------------------------------------------------------
672
673/// Build a JSON error body for invalid JSON parse errors.
674///
675/// Returns `{ "error": "Invalid JSON", "message": "..." }`.
676#[deprecated(
677    since = "0.5.0",
678    note = "unused: the adapters answer malformed JSON with a 422 `VldHttpError::parse` body"
679)]
680pub fn format_json_parse_error(message: &str) -> serde_json::Value {
681    serde_json::to_value(ErrorWithMessage {
682        error: "Invalid JSON".into(),
683        message: message.into(),
684    })
685    .expect("ErrorWithMessage serialization cannot fail")
686}
687
688/// Build a JSON error body for invalid UTF-8 payloads.
689///
690/// Returns `{ "error": "Invalid UTF-8" }`.
691#[deprecated(
692    since = "0.5.0",
693    note = "unused: the adapters answer invalid UTF-8 with a 422 `VldHttpError::parse` body"
694)]
695pub fn format_utf8_error() -> serde_json::Value {
696    format_generic_error("Invalid UTF-8")
697}
698
699/// Build a JSON error body for payloads that exceed the size limit.
700///
701/// Returns `{ "error": "Payload too large" }`.
702///
703/// Internally constructs an [`ErrorBody`] and serializes it.
704pub fn format_payload_too_large() -> serde_json::Value {
705    format_generic_error("Payload too large")
706}
707
708/// Message of the 415 body and error for JSON extractors.
709pub const UNSUPPORTED_MEDIA_TYPE_MESSAGE: &str =
710    "Expected Content-Type: application/json (or application/*+json)";
711
712/// Message of the 415 body and error for form extractors.
713pub const UNSUPPORTED_FORM_MEDIA_TYPE_MESSAGE: &str =
714    "Expected Content-Type: application/x-www-form-urlencoded";
715
716/// Build the JSON error body for a non-JSON `Content-Type`.
717///
718/// Returns `{ "error": "Unsupported Media Type", "message": "Expected Content-Type: ..." }`.
719pub fn format_unsupported_media_type() -> serde_json::Value {
720    VldHttpError::unsupported_media_type().body()
721}
722
723/// Build a generic JSON error body with a custom error string.
724///
725/// Returns `{ "error": "<error>" }`.
726///
727/// Internally constructs an [`ErrorBody`] and serializes it.
728pub fn format_generic_error(error: &str) -> serde_json::Value {
729    serde_json::to_value(ErrorBody {
730        error: error.into(),
731    })
732    .expect("ErrorBody serialization cannot fail")
733}