saola-kit 0.2.0

Saola core toolkit for Laravel for Rust (contexts, envelope protocol, i18n, masks, modules, Sanctum-compatible tokens)
Documentation
#![cfg(feature = "context")]

use std::collections::BTreeMap;

use saola_kit::context::{
    ContextLinksRule, ContextSpec, HrefOptions, RouteEntry, RouteIndex,
};
use serde_json::{Map, Value};

const FIXTURE_JSON: &str = include_str!("../../core/tests/fixtures/href-cases.json");

fn build_fixture_index(fixture: &Value) -> RouteIndex {
    let primary = fixture["primary"].as_str().expect("primary URL");
    let contexts_obj = fixture["contexts"].as_object().expect("contexts object");

    let mut contexts = Vec::new();
    let mut routes = Vec::new();

    for (slug, ctx_val) in contexts_obj {
        let hosts: Vec<String> = ctx_val["hosts"]
            .as_array()
            .expect("hosts array")
            .iter()
            .map(|v| v.as_str().expect("host string").to_owned())
            .collect();

        let mut spec = ContextSpec::new(slug).with_hosts(hosts);
        if slug == "api" {
            spec = spec.with_links_rule(ContextLinksRule::Public);
        }
        contexts.push(spec);

        let mut module_hosts: BTreeMap<String, Vec<String>> = BTreeMap::new();
        if let Some(mh) = ctx_val.get("moduleHosts").and_then(|v| v.as_object()) {
            for (module, val) in mh {
                let list = match val {
                    Value::String(s) => vec![s.clone()],
                    Value::Array(arr) => arr
                        .iter()
                        .map(|v| v.as_str().expect("module host string").to_owned())
                        .collect(),
                    _ => Vec::new(),
                };
                module_hosts.insert(module.clone(), list);
            }
        }

        let routes_obj = ctx_val["routes"].as_object().expect("routes object");
        for (full_name, path_val) in routes_obj {
            let path = path_val.as_str().expect("route path");
            let mut parts = full_name.splitn(3, '.');
            let _ctx = parts.next();
            let module = parts.next().unwrap_or("");
            let mut entry = RouteEntry::new(full_name, path).with_context(slug);
            if let Some(hosts) = module_hosts.get(module) {
                entry = entry.with_hosts(hosts.clone());
            }
            routes.push(entry);
        }
    }

    RouteIndex::new(contexts, routes, primary).expect("fixture RouteIndex")
}

#[test]
fn matches_all_32_shared_php_and_js_href_cases() {
    let fixture: Value = serde_json::from_str(FIXTURE_JSON).expect("valid href-cases.json");
    let index = build_fixture_index(&fixture);
    let cases = fixture["cases"].as_array().expect("cases array");
    assert_eq!(cases.len(), 32);

    for (i, case) in cases.iter().enumerate() {
        let name = case["name"].as_str().expect("case name");
        let empty_map = Map::new();
        let params = case["params"].as_object().unwrap_or(&empty_map);

        let mut options = match &case["from"] {
            Value::Null => HrefOptions::default(),
            Value::Object(from) => {
                let url = from["url"].as_str().expect("from.url");
                let ctx = from["context"].as_str();
                HrefOptions::from_url(url, ctx)
            }
            _ => panic!("unexpected from value in case #{i}"),
        };

        if let Some(opts) = case.get("options").and_then(|v| v.as_object()) {
            if let Some(ctx) = opts.get("context").and_then(|v| v.as_str()) {
                options = options.with_context(ctx);
            }
            if opts.get("absolute").and_then(|v| v.as_bool()) == Some(true) {
                options = options.absolute();
            }
        }

        let result = index.href_values(name, params, &options);
        if let Some(expected_err) = case.get("error").and_then(|v| v.as_str()) {
            let err = result.unwrap_err_or_panic(i, name);
            assert!(
                err.contains(expected_err),
                "case #{i} ({name}): expected error containing `{expected_err}`, got `{err}`"
            );
        } else {
            let expected = case["expect"].as_str().expect("expect URL");
            let actual = result.unwrap_or_else(|e| {
                panic!("case #{i} ({name}): unexpected error `{e}` (expected `{expected}`)")
            });
            assert_eq!(
                actual, expected,
                "case #{i} ({name}) URL mismatch"
            );
        }
    }
}

trait UnwrapErrMsg {
    fn unwrap_err_or_panic(self, case_idx: usize, name: &str) -> String;
}

impl<E: std::fmt::Display> UnwrapErrMsg for Result<String, E> {
    fn unwrap_err_or_panic(self, case_idx: usize, name: &str) -> String {
        match self {
            Ok(url) => panic!("case #{case_idx} ({name}): expected error, got `{url}`"),
            Err(err) => err.to_string(),
        }
    }
}

#[test]
fn client_links_carry_host_overrides_like_php_core() {
    let fixture: Value = serde_json::from_str(FIXTURE_JSON).expect("valid href-cases.json");
    let index = build_fixture_index(&fixture);

    let web = index.client_links("web", &[]);
    let store_entry = serde_json::to_value(&web.links["web.store.index"]).unwrap();
    assert_eq!(
        store_entry,
        serde_json::json!(["web", "/store", ["shop.test", "shop-alt.test"]])
    );

    let portal_entry = serde_json::to_value(&web.links["app.portal.index"]).unwrap();
    assert_eq!(
        portal_entry,
        serde_json::json!(["app", "/portal", ["portal.test"]])
    );

    assert!(!web.links.contains_key("web.home.index"));
    assert_eq!(
        serde_json::to_value(&web.links["app.home.index"]).unwrap(),
        serde_json::json!(["app", "/"])
    );

    let app_links = index.client_links("app", &[]);
    assert_eq!(
        app_links.links["web.store.index"],
        web.links["web.store.index"]
    );
    assert_eq!(
        app_links.links["app.portal.index"],
        web.links["app.portal.index"]
    );
}