use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq)]
pub struct MetaTag {
pub attr_type: MetaAttrType,
pub key: String,
pub content: String,
}
#[derive(Debug, Clone, PartialEq)]
pub enum MetaAttrType {
Name,
Property,
HttpEquiv,
}
impl MetaTag {
pub fn render(&self) -> String {
let attr = match self.attr_type {
MetaAttrType::Name => "name",
MetaAttrType::Property => "property",
MetaAttrType::HttpEquiv => "http-equiv",
};
format!(
"<meta {}=\"{}\" content=\"{}\"/>",
attr,
html_escape(&self.key),
html_escape(&self.content)
)
}
}
fn extra_attr_allowed(name: &str) -> bool {
crate::is_valid_attr_name(name)
&& !name
.get(..2)
.is_some_and(|prefix| prefix.eq_ignore_ascii_case("on"))
}
#[derive(Debug, Clone, PartialEq)]
pub struct LinkTag {
pub rel: String,
pub href: String,
pub extra_attrs: HashMap<String, String>,
}
impl LinkTag {
pub fn render(&self) -> String {
let mut attrs = format!(
"rel=\"{}\" href=\"{}\"",
html_escape(&self.rel),
html_escape(&self.href)
);
for (key, value) in &self.extra_attrs {
if !extra_attr_allowed(key) {
continue;
}
attrs.push_str(&format!(" {}=\"{}\"", html_escape(key), html_escape(value)));
}
format!("<link {}/>", attrs)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ScriptTag {
pub src: Option<String>,
pub inline_content: Option<String>,
pub is_module: bool,
pub is_async: bool,
pub is_defer: bool,
pub extra_attrs: HashMap<String, String>,
}
fn escape_json_for_script(json: &str) -> String {
json.replace('<', "\\u003c")
.replace('>', "\\u003e")
.replace('&', "\\u0026")
}
fn escape_inline_script(content: &str) -> String {
crate::escape_raw_text("script", content)
}
impl ScriptTag {
pub fn render(&self) -> String {
let mut attrs = String::new();
if let Some(ref src) = self.src {
attrs.push_str(&format!(" src=\"{}\"", html_escape(src)));
}
if self.is_module {
attrs.push_str(" type=\"module\"");
}
if self.is_async {
attrs.push_str(" async");
}
if self.is_defer {
attrs.push_str(" defer");
}
for (key, value) in &self.extra_attrs {
if !extra_attr_allowed(key) {
continue;
}
attrs.push_str(&format!(" {}=\"{}\"", html_escape(key), html_escape(value)));
}
if let Some(ref content) = self.inline_content {
format!(
"<script{}>{}</script>",
attrs,
escape_inline_script(content)
)
} else {
format!("<script{}></script>", attrs)
}
}
}
#[derive(Debug, Clone, Default)]
pub struct HeadContext {
title_value: Option<String>,
description_value: Option<String>,
canonical_value: Option<String>,
og_type_value: Option<String>,
og_image_value: Option<String>,
robots_value: Option<String>,
charset: String,
viewport: String,
meta_tags: Vec<MetaTag>,
link_tags: Vec<LinkTag>,
script_tags: Vec<ScriptTag>,
json_ld: Option<String>,
}
impl HeadContext {
pub fn new() -> Self {
Self {
charset: "utf-8".to_string(),
viewport: "width=device-width, initial-scale=1.0".to_string(),
..Default::default()
}
}
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title_value = Some(title.into());
self
}
pub fn description(mut self, desc: impl Into<String>) -> Self {
self.description_value = Some(desc.into());
self
}
pub fn canonical(mut self, url: impl Into<String>) -> Self {
self.canonical_value = Some(url.into());
self
}
pub fn og_type(mut self, og: impl Into<String>) -> Self {
self.og_type_value = Some(og.into());
self
}
pub fn og_image(mut self, url: impl Into<String>) -> Self {
self.og_image_value = Some(url.into());
self
}
pub fn robots(mut self, directive: impl Into<String>) -> Self {
self.robots_value = Some(directive.into());
self
}
pub fn meta(mut self, name: impl Into<String>, content: impl Into<String>) -> Self {
self.meta_tags.push(MetaTag {
attr_type: MetaAttrType::Name,
key: name.into(),
content: content.into(),
});
self
}
pub fn meta_property(
mut self,
property: impl Into<String>,
content: impl Into<String>,
) -> Self {
self.meta_tags.push(MetaTag {
attr_type: MetaAttrType::Property,
key: property.into(),
content: content.into(),
});
self
}
pub fn link_stylesheet(mut self, href: impl Into<String>) -> Self {
self.link_tags.push(LinkTag {
rel: "stylesheet".to_string(),
href: href.into(),
extra_attrs: HashMap::new(),
});
self
}
pub fn link_preload(mut self, href: impl Into<String>, as_type: impl Into<String>) -> Self {
let mut extra = HashMap::new();
extra.insert("as".to_string(), as_type.into());
self.link_tags.push(LinkTag {
rel: "preload".to_string(),
href: href.into(),
extra_attrs: extra,
});
self
}
pub fn link(mut self, rel: impl Into<String>, href: impl Into<String>) -> Self {
self.link_tags.push(LinkTag {
rel: rel.into(),
href: href.into(),
extra_attrs: HashMap::new(),
});
self
}
pub fn script(mut self, src: impl Into<String>) -> Self {
self.script_tags.push(ScriptTag {
src: Some(src.into()),
inline_content: None,
is_module: false,
is_async: false,
is_defer: true,
extra_attrs: HashMap::new(),
});
self
}
pub fn script_module(mut self, src: impl Into<String>) -> Self {
self.script_tags.push(ScriptTag {
src: Some(src.into()),
inline_content: None,
is_module: true,
is_async: false,
is_defer: false,
extra_attrs: HashMap::new(),
});
self
}
pub fn script_inline(mut self, content: impl Into<String>) -> Self {
self.script_tags.push(ScriptTag {
src: None,
inline_content: Some(content.into()),
is_module: false,
is_async: false,
is_defer: false,
extra_attrs: HashMap::new(),
});
self
}
pub fn json_ld(mut self, json: impl Into<String>) -> Self {
self.json_ld = Some(json.into());
self
}
pub fn merge(mut self, child: &HeadContext) -> Self {
if child.title_value.is_some() {
self.title_value = child.title_value.clone();
}
if child.description_value.is_some() {
self.description_value = child.description_value.clone();
}
if child.canonical_value.is_some() {
self.canonical_value = child.canonical_value.clone();
}
if child.og_type_value.is_some() {
self.og_type_value = child.og_type_value.clone();
}
if child.og_image_value.is_some() {
self.og_image_value = child.og_image_value.clone();
}
if child.robots_value.is_some() {
self.robots_value = child.robots_value.clone();
}
if child.json_ld.is_some() {
self.json_ld = child.json_ld.clone();
}
for child_tag in &child.meta_tags {
if let Some(pos) = self
.meta_tags
.iter()
.position(|t| t.attr_type == child_tag.attr_type && t.key == child_tag.key)
{
self.meta_tags[pos] = child_tag.clone();
} else {
self.meta_tags.push(child_tag.clone());
}
}
self.link_tags.extend(child.link_tags.iter().cloned());
self.script_tags.extend(child.script_tags.iter().cloned());
self
}
pub fn render_tags(&self) -> String {
let mut parts: Vec<String> = Vec::new();
parts.push(format!(
"<meta charset=\"{}\"/>",
html_escape(&self.charset)
));
if !self.viewport.is_empty() {
parts.push(format!(
"<meta name=\"viewport\" content=\"{}\"/>",
html_escape(&self.viewport)
));
}
if let Some(ref title) = self.title_value {
parts.push(format!("<title>{}</title>", html_escape(title)));
}
if let Some(ref desc) = self.description_value {
parts.push(format!(
"<meta name=\"description\" content=\"{}\"/>",
html_escape(desc)
));
}
if let Some(ref canonical) = self.canonical_value {
parts.push(format!(
"<link rel=\"canonical\" href=\"{}\"/>",
html_escape(canonical)
));
}
if let Some(ref robots) = self.robots_value {
parts.push(format!(
"<meta name=\"robots\" content=\"{}\"/>",
html_escape(robots)
));
}
if let Some(ref title) = self.title_value {
parts.push(format!(
"<meta property=\"og:title\" content=\"{}\"/>",
html_escape(title)
));
}
if let Some(ref desc) = self.description_value {
parts.push(format!(
"<meta property=\"og:description\" content=\"{}\"/>",
html_escape(desc)
));
}
if let Some(ref og_type) = self.og_type_value {
parts.push(format!(
"<meta property=\"og:type\" content=\"{}\"/>",
html_escape(og_type)
));
}
if let Some(ref og_image) = self.og_image_value {
parts.push(format!(
"<meta property=\"og:image\" content=\"{}\"/>",
html_escape(og_image)
));
}
if let Some(ref canonical) = self.canonical_value {
parts.push(format!(
"<meta property=\"og:url\" content=\"{}\"/>",
html_escape(canonical)
));
}
for tag in &self.meta_tags {
parts.push(tag.render());
}
for tag in &self.link_tags {
parts.push(tag.render());
}
for tag in &self.script_tags {
parts.push(tag.render());
}
if let Some(ref json_ld) = self.json_ld {
parts.push(format!(
"<script type=\"application/ld+json\">{}</script>",
escape_json_for_script(json_ld)
));
}
parts.join("\n")
}
pub fn get_title(&self) -> Option<&str> {
self.title_value.as_deref()
}
pub fn get_description(&self) -> Option<&str> {
self.description_value.as_deref()
}
pub fn get_canonical(&self) -> Option<&str> {
self.canonical_value.as_deref()
}
}
fn html_escape(s: &str) -> String {
s.replace('&', "&")
.replace('"', """)
.replace('<', "<")
.replace('>', ">")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic_head_rendering() {
let head = HeadContext::new()
.title("Test Page")
.description("A test page description");
let tags = head.render_tags();
assert!(tags.contains("<title>Test Page</title>"));
assert!(tags.contains("name=\"description\" content=\"A test page description\""));
assert!(tags.contains("charset=\"utf-8\""));
assert!(tags.contains("name=\"viewport\""));
}
#[test]
fn canonical_and_og_tags() {
let head = HeadContext::new()
.title("Blog Post")
.canonical("https://example.com/blog/post-1")
.og_type("article")
.og_image("https://example.com/img.jpg");
let tags = head.render_tags();
assert!(tags.contains("rel=\"canonical\" href=\"https://example.com/blog/post-1\""));
assert!(tags.contains("og:type\" content=\"article\""));
assert!(tags.contains("og:image\" content=\"https://example.com/img.jpg\""));
assert!(tags.contains("og:url\" content=\"https://example.com/blog/post-1\""));
}
#[test]
fn custom_meta_tags() {
let head = HeadContext::new()
.meta("author", "Jane Doe")
.meta("theme-color", "#000000");
let tags = head.render_tags();
assert!(tags.contains("name=\"author\" content=\"Jane Doe\""));
assert!(tags.contains("name=\"theme-color\" content=\"#000000\""));
}
#[test]
fn link_and_script_tags() {
let head = HeadContext::new()
.link_stylesheet("/css/main.css")
.script_module("/js/app.js")
.script_inline("console.log('hello')");
let tags = head.render_tags();
assert!(tags.contains("rel=\"stylesheet\" href=\"/css/main.css\""));
assert!(tags.contains("src=\"/js/app.js\" type=\"module\""));
assert!(tags.contains("console.log('hello')"));
}
#[test]
fn merge_child_overwrites_scalars() {
let parent = HeadContext::new()
.title("Parent Title")
.description("Parent desc")
.canonical("/parent");
let child = HeadContext::new()
.title("Child Title")
.description("Child desc");
let merged = parent.merge(&child);
assert_eq!(merged.get_title(), Some("Child Title"));
assert_eq!(merged.get_description(), Some("Child desc"));
assert_eq!(merged.get_canonical(), Some("/parent"));
}
#[test]
fn merge_meta_tags_child_key_overwrites() {
let parent = HeadContext::new()
.meta("author", "Parent Author")
.meta("theme-color", "#fff");
let child = HeadContext::new()
.meta("author", "Child Author")
.meta("keywords", "rust,web");
let merged = parent.merge(&child);
let tags = merged.render_tags();
assert!(tags.contains("name=\"author\" content=\"Child Author\""));
assert!(!tags.contains("Parent Author"));
assert!(tags.contains("name=\"theme-color\" content=\"#fff\""));
assert!(tags.contains("name=\"keywords\" content=\"rust,web\""));
}
#[test]
fn link_extra_attrs_drop_invalid_names() {
let mut extra = HashMap::new();
extra.insert("x onload=alert(1) y".to_string(), "v".to_string());
extra.insert("crossorigin".to_string(), "anonymous".to_string());
let html = LinkTag {
rel: "preload".to_string(),
href: "/a.css".to_string(),
extra_attrs: extra,
}
.render();
assert!(!html.contains("onload"), "{html}");
assert!(html.contains(r#"crossorigin="anonymous""#), "{html}");
}
#[test]
fn merge_keeps_name_and_property_tags_with_the_same_key_apart() {
let parent = HeadContext::new().meta("author", "Name Author");
let child = HeadContext::new().meta_property("author", "Property Author");
let tags = parent.merge(&child).render_tags();
assert!(
tags.contains("name=\"author\" content=\"Name Author\""),
"{tags}"
);
assert!(
tags.contains("property=\"author\" content=\"Property Author\""),
"{tags}"
);
}
#[test]
fn merge_appends_links_and_scripts() {
let parent = HeadContext::new().link_stylesheet("/css/parent.css");
let child = HeadContext::new()
.link_stylesheet("/css/child.css")
.script("/js/child.js");
let merged = parent.merge(&child);
let tags = merged.render_tags();
assert!(tags.contains("/css/parent.css"));
assert!(tags.contains("/css/child.css"));
assert!(tags.contains("/js/child.js"));
}
#[test]
fn json_ld_rendering() {
let head =
HeadContext::new().json_ld(r#"{"@context":"https://schema.org","@type":"Article"}"#);
let tags = head.render_tags();
assert!(tags.contains("application/ld+json"));
assert!(tags.contains("@context"));
}
#[test]
fn html_escaping_in_head() {
let head = HeadContext::new().title("Page with \"quotes\" & <tags>");
let tags = head.render_tags();
assert!(tags.contains("&"));
assert!(tags.contains("<tags>"));
}
#[test]
fn robots_directive() {
let head = HeadContext::new().robots("noindex, nofollow");
let tags = head.render_tags();
assert!(tags.contains("name=\"robots\" content=\"noindex, nofollow\""));
}
#[test]
fn preload_link() {
let head = HeadContext::new().link_preload("/fonts/inter.woff2", "font");
let tags = head.render_tags();
assert!(tags.contains("rel=\"preload\""));
assert!(tags.contains("href=\"/fonts/inter.woff2\""));
assert!(tags.contains("as=\"font\""));
}
}
#[cfg(test)]
mod script_escaping_tests {
use super::*;
#[test]
fn json_ld_cannot_close_its_own_script_block() {
let hostile = r#"{"name":"</script><img src=x onerror=alert(1)>"}"#;
let html = HeadContext::new().json_ld(hostile).render_tags();
assert!(
!html.contains("</script><img"),
"JSON-LD broke out of its block: {html}"
);
assert!(html.contains(r"\u003c/script\u003e"));
assert_eq!(html.matches("</script>").count(), 1);
}
#[test]
fn json_ld_escaping_preserves_the_document() {
let escaped = escape_json_for_script(r#"{"a":"1 < 2 & 3 > 2"}"#);
let parsed: serde_json::Value = serde_json::from_str(&escaped).expect("still valid JSON");
assert_eq!(parsed["a"], "1 < 2 & 3 > 2");
}
#[test]
fn inline_script_cannot_close_its_own_block() {
let content = r#"const s = "</script><img src=x onerror=alert(1)>";"#;
let out = escape_inline_script(content);
assert!(!out.contains("</script>"), "breakout survived: {out}");
assert!(out.contains(r"<\/script>"));
}
#[test]
fn inline_script_escaping_is_case_insensitive_and_keeps_casing() {
let out = escape_inline_script("a </ScRiPt> b");
assert!(!out.to_ascii_lowercase().contains("</script"));
assert!(out.contains(r"<\/ScRiPt>"), "casing not preserved: {out}");
}
#[test]
fn inline_script_without_a_breakout_is_untouched() {
let content = "const x = a < b && c > d;";
assert_eq!(escape_inline_script(content), content);
}
#[test]
fn script_attribute_name_that_would_open_a_second_attribute_is_dropped() {
let mut extra = HashMap::new();
extra.insert("x onload=alert(1)".to_string(), "v".to_string());
extra.insert("data-ok".to_string(), "1".to_string());
let html = ScriptTag {
src: Some("/pkg/app.js".to_string()),
inline_content: None,
is_module: false,
is_async: false,
is_defer: false,
extra_attrs: extra,
}
.render();
assert!(
!html.contains("onload"),
"injected handler survived: {html}"
);
assert!(html.contains("data-ok=\"1\""));
}
#[test]
fn event_handler_extra_attrs_are_dropped() {
let extra: HashMap<String, String> = [
("onload", "alert(1)"),
("ONERROR", "alert(2)"),
("onClick", "alert(3)"),
("data-on", "kept"),
("nonce", "abc"),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
let link = LinkTag {
rel: "preload".to_string(),
href: "/a.css".to_string(),
extra_attrs: extra.clone(),
}
.render();
let script = ScriptTag {
src: Some("/pkg/app.js".to_string()),
inline_content: None,
is_module: false,
is_async: false,
is_defer: false,
extra_attrs: extra,
}
.render();
for html in [&link, &script] {
assert!(!html.contains("alert"), "event handler survived: {html}");
assert!(html.contains(r#"data-on="kept""#), "{html}");
assert!(html.contains(r#"nonce="abc""#), "{html}");
}
}
}