oxblade 0.3.3

Laravel Blade templates for Rust: Blade's markup and directives with Rust expressions, rendering the same HTML as Laravel. Community package, not affiliated with Laravel.
Documentation
#![allow(missing_docs, clippy::unwrap_used, clippy::expect_used)]

use oxblade::{
    Shape,
    engine::{Environment, Limits, Options},
    error::ErrorKind,
    loader::MemoryLoader,
    value::{Value, ValueMap},
};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value as Json;

const EXCESSIVE_DEPTH: usize = 100_000;

#[derive(Serialize, Shape)]
#[serde(transparent)]
struct Nested(Json);

impl Nested {
    fn new(depth: usize) -> Self {
        Self((0..depth).fold(Json::Bool(true), |child, level| {
            if level % 2 == 0 {
                Json::Array(vec![child])
            } else {
                Json::Object(serde_json::Map::from_iter([("child".into(), child)]))
            }
        }))
    }
}

impl Drop for Nested {
    fn drop(&mut self) {
        let mut value = std::mem::take(&mut self.0);
        loop {
            value = match value {
                Json::Array(mut values) => values.pop().unwrap(),
                Json::Object(mut fields) => fields.remove("child").unwrap(),
                _ => break,
            };
        }
    }
}

impl<'de> Deserialize<'de> for Nested {
    fn deserialize<D: Deserializer<'de>>(input: D) -> Result<Self, D::Error> {
        usize::deserialize(input).map(Self::new)
    }
}

#[oxblade::component("depth-field")]
#[derive(Deserialize, Shape)]
struct DepthField {
    value: Nested,
}

#[derive(Deserialize, Shape)]
struct DepthMethod {
    #[serde(default)]
    active: bool,
}

#[oxblade::component("depth-method")]
impl DepthMethod {
    #[expose]
    fn nested(&self, depth: usize) -> Nested {
        Nested::new(depth)
    }
}

#[derive(Deserialize, Shape)]
struct DepthView {
    depth: usize,
}

#[derive(Serialize)]
struct Projection {
    value: Nested,
}

#[oxblade::component("depth-view")]
impl DepthView {
    fn view(&self) -> Projection {
        Projection {
            value: Nested::new(self.depth),
        }
    }
}

#[test]
fn generated_component_projections_bound_typed_data_before_traversal() {
    std::thread::Builder::new()
        .stack_size(2 * 1024 * 1024)
        .spawn(|| {
            let env = Environment::builder(
                MemoryLoader::new()
                    .view("field", "<x-depth-field :value=\"depth\"/>")
                    .view("components.depth-field", "@json(value)")
                    .view(
                        "method",
                        "<x-depth-method>@json(component.nested(depth))</x-depth-method>",
                    )
                    .view("components.depth-method", "{{ slot }}")
                    .view("view", "<x-depth-view :depth=\"depth\"/>")
                    .view("components.depth-view", "@json(value)"),
            )
            .components([
                DepthField::OXBLADE_COMPONENT,
                DepthMethod::OXBLADE_COMPONENT,
                DepthView::OXBLADE_COMPONENT,
            ])
            .options(Options {
                limits: Limits {
                    depth: 128,
                    ..Limits::default()
                },
                ..Options::default()
            })
            .build();

            let data = |depth: usize| ValueMap::from([("depth".into(), Value::Int(depth as i64))]);
            let expected = Nested::new(100).0.to_string();
            let results = ["field", "method", "view"].map(|name| {
                assert_eq!(env.render(name, data(100)).unwrap(), expected, "{name}");
                (
                    name,
                    env.render(name, data(EXCESSIVE_DEPTH))
                        .map_err(|error| (error.kind, error.message)),
                )
            });
            for (name, result) in results {
                let (kind, message) = result.unwrap_err();
                assert_eq!(kind, ErrorKind::Limit, "{name}");
                assert!(
                    message.starts_with("view JSON data depth limit exceeded"),
                    "{name}: {message}"
                );
            }
        })
        .unwrap()
        .join()
        .unwrap();
}

#[test]
fn component_conversion_preserves_html_and_integer_rules() {
    use oxblade::render::components::{serialize_fields, serialize_value};

    const MARKUP: &str = "<b>&</b>";
    assert!(
        matches!(serialize_value(oxblade::Html::new(MARKUP)).unwrap(), Value::Html(text) if text == MARKUP)
    );
    let borrowed_html = &oxblade::Html::new(MARKUP);
    assert!(matches!(serialize_value(borrowed_html).unwrap(), Value::Str(text) if text == MARKUP));
    assert!(
        matches!(&serialize_fields(std::collections::BTreeMap::from([("nested", oxblade::Html::new(MARKUP))])).unwrap()["nested"], Value::Str(text) if text == MARKUP)
    );
    assert!(matches!(
        serialize_value(i64::MAX as u64).unwrap(),
        Value::Int(i64::MAX)
    ));
    assert_eq!(
        serialize_value(i64::MAX as u64 + 1).unwrap_err().message,
        "component return value exceeds the Blade integer range"
    );
}

#[test]
fn serialization_bounds_newtype_map_keys_without_changing_key_spelling() {
    struct Key(usize);

    impl Serialize for Key {
        fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            if self.0 == 0 {
                serializer.serialize_i128(i128::MAX)
            } else {
                serializer.serialize_newtype_struct("Key", &Self(self.0 - 1))
            }
        }
    }

    struct Data(usize);

    impl Serialize for Data {
        fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            use serde::ser::SerializeMap as _;
            let mut map = serializer.serialize_map(Some(1))?;
            map.serialize_entry(&Key(self.0), &true)?;
            map.end()
        }
    }

    let serialize = |depth| oxblade::data_json::serialize_model(&Data(depth), false);
    assert_eq!(
        serialize(100).unwrap().value.to_string(),
        format!(r#"{{"{}":true}}"#, i128::MAX),
    );
    let Err(error) = serialize(EXCESSIVE_DEPTH) else {
        panic!("map key wrappers must count toward serialization depth");
    };
    assert_eq!(error.kind, ErrorKind::Limit);
}

#[test]
fn deserialization_bounds_dynamic_object_entries() {
    use oxblade::{encode::JsonKind, render::components::argument, value::Object};

    #[derive(Debug)]
    struct NestedObject(usize);

    impl<'a> Object<'a> for NestedObject {
        fn type_name(&self) -> &'static str {
            "test array"
        }

        fn json_kind(&self) -> JsonKind<'_> {
            JsonKind::Array(Box::new(std::iter::empty()))
        }

        fn entries(&self, _: usize) -> oxblade::error::Result<Vec<(Value<'a>, Value<'a>)>> {
            let item = if self.0 == 0 {
                Value::Bool(true)
            } else {
                Value::object(Self(self.0 - 1))
            };
            Ok(vec![(Value::Int(0), item)])
        }
    }

    let input = |depth| Value::object(NestedObject(depth));
    let expected = (0..100).fold(Json::Bool(true), |child, _| Json::Array(vec![child]));
    assert_eq!(argument::<Json>(&input(99)).unwrap(), expected);
    assert_eq!(
        argument::<Json>(&input(EXCESSIVE_DEPTH)).unwrap_err().kind,
        ErrorKind::Limit
    );
}

#[test]
fn wildcard_paths_bound_depth_in_borrowed_collections() {
    let nested = (0..140).fold(Json::Bool(true), |child, _| Json::Array(vec![child]));
    let data = ValueMap::from([
        ("items".into(), Value::List(vec![Value::Json(&nested)])),
        (
            "path".into(),
            Value::string(std::iter::repeat_n("*", 140).collect::<Vec<_>>().join(".")),
        ),
    ]);
    let env = Environment::builder(MemoryLoader::new()).build();
    let error = env
        .render_str("@json(items.pluck(path))", data)
        .unwrap_err();
    assert_eq!(error.kind, ErrorKind::Limit);
}

#[derive(Deserialize, Shape)]
struct DepthAttributes {
    depth: usize,
}

#[oxblade::component("depth-attributes")]
impl DepthAttributes {
    fn with_attributes(&self, attributes: &mut oxblade::attributes::AttributeBag) {
        use oxblade::attributes::{AttributeValue, Attributes};
        let nested = (0..self.depth).fold(AttributeValue::Bool(true), |child, _| {
            AttributeValue::Array(Attributes::from([("child".into(), child)]))
        });
        attributes.offset_set("data-test", nested);
    }
}

#[test]
fn class_component_attribute_hook_bounds_owned_attributes() {
    let env = Environment::builder(MemoryLoader::new().view("components.depth-attributes", "ok"))
        .component(DepthAttributes::OXBLADE_COMPONENT)
        .build();
    let data = |depth| ValueMap::from([("depth".into(), Value::Int(depth))]);
    assert_eq!(
        env.render_component("depth-attributes", data(100)).unwrap(),
        "ok"
    );
    let error = env
        .render_component("depth-attributes", data(140))
        .unwrap_err();
    assert_eq!(error.kind, ErrorKind::Limit);
}