footing 0.4.4

Feature-gated foundations for Rust backend services
Documentation
use serde_json::{Map, Value, json};

use super::{DocsError, DocsUi};

pub(super) fn resolve(overrides: Value, preset: bool, ui: &DocsUi) -> Result<Value, DocsError> {
    let Value::Object(overrides) = overrides else {
        return Err(DocsError::InvalidOptions("the root must be an object"));
    };
    match ui {
        DocsUi::Redoc(_) => redoc(overrides, preset),
        DocsUi::RapiDoc(_) => rapidoc(overrides, preset),
    }
}

fn rapidoc(overrides: Map<String, Value>, preset: bool) -> Result<Value, DocsError> {
    for (name, value) in &overrides {
        if !name.as_bytes().first().is_some_and(u8::is_ascii_lowercase)
            || !name
                .bytes()
                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
            || (name.starts_with("on") && name != "on-nav-tag-click")
            || matches!(
                name.as_str(),
                "spec-url" | "style" | "id" | "class" | "slot" | "is"
            )
        {
            return Err(DocsError::InvalidOptions(
                "RapiDoc requires native attribute names; spec-url, event handlers and DOM attributes are reserved",
            ));
        }
        if !matches!(value, Value::String(_) | Value::Bool(_) | Value::Number(_)) {
            return Err(DocsError::InvalidOptions(
                "RapiDoc attribute values must be strings, booleans or numbers",
            ));
        }
    }
    let mut options = if preset {
        json!({
            "render-style": "focused",
            "heading-text": "RapiDoc",
            "schema-style": "table",
            "schema-description-expanded": true,
            "default-schema-tab": "schema",
            "show-method-in-nav-bar": "as-colored-block",
            "sort-endpoints-by": "method",
            "primary-color": "#2d87e2",
            "persist-auth": false,
            "oauth-receiver": "oauth-receiver.html",
            "load-fonts": false,
            "regular-font": "system-ui, sans-serif",
            "mono-font": "ui-monospace, monospace",
            "allow-search": true,
            "allow-advanced-search": true,
            "allow-spec-file-download": true
        })
    } else {
        json!({})
    };
    merge(&mut options, Value::Object(overrides));
    Ok(options)
}

fn redoc(mut overrides: Map<String, Value>, preset: bool) -> Result<Value, DocsError> {
    if overrides
        .get("theme")
        .is_some_and(|theme| !theme.is_object())
    {
        return Err(DocsError::InvalidOptions("theme must be an object"));
    }
    for (legacy, reason) in [
        ("untrustedSpec", "use sanitize instead of untrustedSpec"),
        (
            "hideDownloadButton",
            "use hideDownloadButtons instead of hideDownloadButton",
        ),
        (
            "schemaExpansionLevel",
            "use schemasExpansionLevel instead of schemaExpansionLevel",
        ),
        (
            "jsonSampleExpandLevel",
            "use jsonSamplesExpandLevel instead of jsonSampleExpandLevel",
        ),
    ] {
        if overrides.contains_key(legacy) {
            return Err(DocsError::InvalidOptions(reason));
        }
    }
    // ReDoc 2.x's JavaScript || alias fallback treats numeric zero as absent.
    // Its supported string form preserves a zero JSON sample depth.
    if overrides
        .get("jsonSamplesExpandLevel")
        .and_then(Value::as_f64)
        == Some(0.0)
    {
        overrides.insert("jsonSamplesExpandLevel".to_owned(), json!("0"));
    }
    let mut options = if preset {
        json!({
            "disableSearch": false,
            "hideDownloadButtons": false,
            "sanitize": true,
            "schemasExpansionLevel": 1,
            "jsonSamplesExpandLevel": 2,
            "theme": {
                "typography": {
                    "fontFamily": "system-ui, sans-serif",
                    "headings": { "fontFamily": "system-ui, sans-serif" },
                    "code": { "fontFamily": "ui-monospace, monospace" }
                }
            }
        })
    } else {
        json!({})
    };
    merge(&mut options, Value::Object(overrides));
    Ok(options)
}

fn merge(target: &mut Value, overrides: Value) {
    match (target, overrides) {
        (Value::Object(target), Value::Object(overrides)) => {
            for (key, value) in overrides {
                merge(target.entry(key).or_insert(Value::Null), value);
            }
        }
        (target, value) => *target = value,
    }
}

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

    #[test]
    fn integer_and_float_zero_preserve_json_sample_depth() {
        for zero in [json!(0), json!(0.0), json!(-0.0)] {
            let overrides = Map::from_iter([("jsonSamplesExpandLevel".to_owned(), zero)]);
            let options = redoc(overrides, true).unwrap();
            assert_eq!(options["jsonSamplesExpandLevel"], "0");
        }
    }

    #[test]
    fn objects_merge_but_arrays_scalars_and_null_replace() {
        let mut value = json!({"theme": {"fonts": ["a", "b"], "size": 12, "color": "blue"}});
        merge(&mut value, json!({"theme": {"fonts": ["c"], "size": null}}));
        assert_eq!(
            value,
            json!({"theme": {"fonts": ["c"], "size": null, "color": "blue"}})
        );
    }
}