1
//! The native errors of the client forms: the `form-invalid` condition with
2
//! its field errors as a readable plist list, and every other [`Failure`].
3

            
4
use forms::FieldError;
5
use scripting::runtime::{EvalValue, HostCondition};
6

            
7
use crate::envelope::ErrorCode;
8
use crate::forms::outcome::key;
9
use crate::forms::{Failure, FormAction, count_result};
10
use crate::host_failure::not_found_condition;
11

            
12
5373
fn detail(errors: &[FieldError]) -> EvalValue {
13
5896
    let field_error = |error: &FieldError| {
14
5896
        EvalValue::List(vec![
15
5896
            key("FIELD"),
16
5896
            EvalValue::String(error.field.clone()),
17
5896
            key("MESSAGE"),
18
5896
            EvalValue::String(error.message.clone()),
19
5896
        ])
20
5896
    };
21
5373
    EvalValue::List(errors.iter().map(field_error).collect())
22
5373
}
23

            
24
/// The error a submit returns when its values are invalid.
25
#[must_use]
26
5373
pub fn form_invalid(errors: &[FieldError]) -> wasmtime::Error {
27
5373
    wasmtime::Error::new(HostCondition {
28
5373
        code: ErrorCode::FORM_INVALID.to_string(),
29
5373
        message: match errors.len() {
30
5033
            1 => "1 field invalid".to_string(),
31
340
            n => format!("{n} fields invalid"),
32
        },
33
5373
        detail: Some(detail(errors)),
34
    })
35
5373
}
36

            
37
/// A bad native argument: unknown form name or option source.
38
#[must_use]
39
2107
pub fn args_error(message: impl Into<String>) -> wasmtime::Error {
40
2107
    wasmtime::Error::new(HostCondition {
41
2107
        code: ErrorCode::ARGS.to_string(),
42
2107
        message: message.into(),
43
2107
        detail: None,
44
2107
    })
45
2107
}
46

            
47
/// The native error: `form-invalid` for field errors, the original error for
48
/// an internal failure, `not-found` for a missing entity, `args` for every other cause.
49
#[must_use]
50
5908
pub fn native_failure(failure: Failure) -> wasmtime::Error {
51
5908
    match failure {
52
5205
        Failure::Invalid(errors) => form_invalid(&errors),
53
23
        Failure::Internal(err) => err,
54
484
        missing @ Failure::Missing(_) => not_found_condition(missing.to_string(), None),
55
196
        other => args_error(other.to_string()),
56
    }
57
5908
}
58

            
59
/// Counts `result` as one request of `form`, then maps its failure to the native error.
60
54087
pub fn counted<T>(
61
54087
    form: &str,
62
54087
    action: FormAction,
63
54087
    result: Result<T, Failure>,
64
54087
) -> wasmtime::Result<T> {
65
54087
    count_result(form, action, result).map_err(native_failure)
66
54087
}