#![warn(missing_docs)]
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};
pub mod action;
pub mod config;
pub mod control_flow;
#[cfg(feature = "auth")]
pub mod credentials;
pub mod csrf;
pub mod error_boundary;
#[cfg(feature = "graphql")]
pub mod graphql;
#[cfg(feature = "grpc-semantics")]
pub mod grpc_semantics;
pub mod head;
#[cfg(feature = "rest")]
pub mod http_error;
pub mod i18n;
#[deprecated(
since = "0.6.0",
note = "emits <source> elements for image variants nothing generates; write the <picture> with view! instead. Removed in 0.7.0"
)]
pub mod image;
pub mod resource;
#[cfg(not(target_arch = "wasm32"))]
pub mod isr;
pub mod layout;
pub mod protocol;
pub mod render_policy;
pub mod render_stream;
pub mod resilience;
pub mod service_contract;
pub mod signal;
pub mod style_scope;
pub mod suspense;
#[cfg(not(target_arch = "wasm32"))]
pub mod ws;
#[cfg(any(feature = "rest", feature = "web"))]
pub mod server_fn;
#[cfg(not(target_arch = "wasm32"))]
pub mod telemetry;
fn escape_html_attr(s: &str) -> String {
s.replace('&', "&")
.replace('"', """)
.replace('<', "<")
.replace('>', ">")
}
fn escape_html_text(s: &str) -> String {
s.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
}
pub(crate) fn is_raw_text_element(tag: &str) -> bool {
tag.eq_ignore_ascii_case("script") || tag.eq_ignore_ascii_case("style")
}
pub(crate) fn escape_raw_text(tag: &str, content: &str) -> String {
let tag_lower = tag.to_ascii_lowercase();
let close = format!("</{tag_lower}");
let is_script = tag_lower == "script";
let lower = content.to_ascii_lowercase();
let mut out = String::with_capacity(content.len());
let mut cursor = 0;
loop {
let next_close = lower[cursor..].find(&close).map(|rel| (cursor + rel, true));
let next_comment = if is_script {
lower[cursor..]
.find("<!--")
.map(|rel| (cursor + rel, false))
} else {
None
};
let next = match (next_close, next_comment) {
(Some(a), Some(b)) => Some(if a.0 <= b.0 { a } else { b }),
(a, b) => a.or(b),
};
let Some((at, is_close)) = next else {
break;
};
out.push_str(&content[cursor..at]);
if is_close {
out.push_str("<\\/");
out.push_str(&content[at + 2..at + close.len()]);
cursor = at + close.len();
} else {
out.push_str("\\u003C!--");
cursor = at + 4;
}
}
out.push_str(&content[cursor..]);
out
}
fn raw_text_content(node: &Node, out: &mut String) {
match node {
Node::Text(text) => out.push_str(text),
Node::Comment(_) => {}
Node::Element(element) => out.push_str(&element.render()),
Node::Fragment(nodes) => nodes.iter().for_each(|n| raw_text_content(n, out)),
Node::Dynamic(f) => raw_text_content(&f(), out),
}
}
pub(crate) fn sanitize_comment(text: &str) -> String {
let mut out = text.to_string();
while out.contains("--") {
out = out.replace("--", "- -");
}
if out.starts_with('>') || out.starts_with("->") {
out.insert(0, ' ');
}
if out.ends_with('-') || out.ends_with("<!") {
out.push(' ');
}
out
}
pub(crate) fn is_valid_attr_name(name: &str) -> bool {
let mut chars = name.chars();
match chars.next() {
Some(c) if c.is_ascii_alphabetic() || c == '_' || c == ':' => {}
_ => return false,
}
chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | ':' | '.'))
}
#[cfg(not(target_arch = "wasm32"))]
pub mod service;
#[cfg(any(feature = "db-postgres", feature = "db-sqlite"))]
pub mod db;
#[cfg(any(feature = "db-postgres", feature = "db-sqlite"))]
pub mod repository;
#[cfg(feature = "rest")]
pub mod http;
#[cfg(feature = "rest")]
pub mod http_auth;
#[cfg(feature = "rest")]
pub mod http_headers;
#[cfg(feature = "rest")]
mod http_observability;
#[cfg(feature = "rest")]
mod http_protocol;
#[cfg(feature = "rest")]
pub mod http_runtime;
#[cfg(feature = "rest")]
pub mod http_security;
#[cfg(feature = "rest")]
pub(crate) mod jwks;
#[cfg(feature = "rest")]
pub mod static_assets;
#[cfg(not(target_arch = "wasm32"))]
pub mod store;
#[cfg(all(feature = "rest", test))]
mod auth_tests;
#[cfg(all(feature = "db-postgres", test))]
mod db_tests;
#[cfg(all(feature = "rest", test))]
mod api_tests;
#[cfg(all(feature = "rest", test))]
mod server_fn_tests;
#[cfg(all(feature = "rest", test))]
mod protocol_tests;
static NEXT_HYDRATION_BOUNDARY_ID: AtomicU64 = AtomicU64::new(1);
pub const HYDRATION_NODE_ID_ATTR: &str = "data-krab-node-id";
const ISLAND_NAME_ATTR: &str = "data-island";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HydrationNodeMarker {
pub boundary_id: String,
pub path: String,
}
impl HydrationNodeMarker {
pub fn new(boundary_id: impl Into<String>, path: impl Into<String>) -> Self {
Self {
boundary_id: boundary_id.into(),
path: path.into(),
}
}
pub fn root(boundary_id: &str) -> Self {
Self::new(boundary_id, "0")
}
pub fn child(&self, child_index: usize) -> Self {
Self::new(
&self.boundary_id,
child_hydration_path(&self.path, child_index),
)
}
pub fn parse(input: &str) -> Option<Self> {
let (boundary_id, path) = input.split_once('/')?;
let boundary_id = boundary_id.trim();
let path = path.trim();
if boundary_id.is_empty() || path.is_empty() {
return None;
}
Some(Self::new(boundary_id, path))
}
pub fn as_attr_value(&self) -> String {
format!("{}/{}", self.boundary_id, self.path)
}
}
pub fn next_hydration_boundary_id(scope: &str) -> String {
let id = NEXT_HYDRATION_BOUNDARY_ID.fetch_add(1, Ordering::Relaxed);
format!("{scope}:{id}")
}
pub fn annotate_hydration_tree(node: Node, boundary_id: &str) -> Node {
annotate_hydration_tree_with_marker(node, &HydrationNodeMarker::root(boundary_id))
}
fn annotate_hydration_tree_with_marker(node: Node, marker: &HydrationNodeMarker) -> Node {
match node {
Node::Element(mut element) => {
stamp_hydration_marker_if_absent(&mut element, || marker.as_attr_value());
if !element
.attributes
.iter()
.any(|attr| attr.name == ISLAND_NAME_ATTR)
{
element.children = annotate_hydration_children(element.children, marker);
}
Node::Element(element)
}
Node::Fragment(children) => Node::Fragment(annotate_hydration_children(children, marker)),
Node::Dynamic(factory) => {
let marker = marker.clone();
Node::Dynamic(Rc::new(move || {
annotate_hydration_tree_with_marker(factory(), &marker)
}))
}
Node::Text(text) => Node::Text(text),
Node::Comment(text) => Node::Comment(text),
}
}
fn annotate_hydration_children(
children: Vec<Node>,
parent_marker: &HydrationNodeMarker,
) -> Vec<Node> {
children
.into_iter()
.enumerate()
.map(|(index, child)| {
annotate_hydration_tree_with_marker(child, &parent_marker.child(index))
})
.collect()
}
pub(crate) fn child_hydration_path(parent_path: &str, child_index: usize) -> String {
if parent_path.is_empty() {
child_index.to_string()
} else {
format!("{parent_path}.{child_index}")
}
}
pub(crate) fn stamp_hydration_marker_if_absent(
element: &mut Element,
value: impl FnOnce() -> String,
) {
if !element
.attributes
.iter()
.any(|attr| attr.name == HYDRATION_NODE_ID_ATTR)
{
element
.attributes
.push(Attribute::new(HYDRATION_NODE_ID_ATTR.to_string(), value()));
}
}
pub trait Render {
fn render(&self) -> String;
}
impl Render for String {
fn render(&self) -> String {
self.clone()
}
}
impl Render for &str {
fn render(&self) -> String {
self.to_string()
}
}
impl<T: std::fmt::Display> Render for &T {
fn render(&self) -> String {
self.to_string()
}
}
#[derive(Clone)]
pub enum Node {
Element(Element),
Text(String),
Fragment(Vec<Node>),
Dynamic(Rc<dyn Fn() -> Node>),
Comment(String),
}
impl std::fmt::Debug for Node {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Node::Element(e) => f.debug_tuple("Element").field(e).finish(),
Node::Text(t) => f.debug_tuple("Text").field(t).finish(),
Node::Comment(t) => f.debug_tuple("Comment").field(t).finish(),
Node::Fragment(nodes) => f.debug_tuple("Fragment").field(nodes).finish(),
Node::Dynamic(_) => f.debug_tuple("Dynamic").finish(),
}
}
}
impl Default for Node {
fn default() -> Self {
Node::Fragment(Vec::new())
}
}
impl Render for Node {
fn render(&self) -> String {
match self {
Node::Element(el) => el.render(),
Node::Text(text) => escape_html_text(text),
Node::Comment(text) => format!("<!--{}-->", sanitize_comment(text)),
Node::Fragment(nodes) => nodes.iter().map(|n| n.render()).collect(),
Node::Dynamic(f) => f().render(),
}
}
}
#[derive(Debug, Clone)]
pub struct Element {
pub tag: String,
pub attributes: Vec<Attribute>,
pub children: Vec<Node>,
pub events: Vec<EventListener>,
}
#[derive(Clone)]
pub struct EventListener {
pub name: String,
#[cfg(feature = "web")]
pub callback: Rc<dyn Fn(web_sys::Event)>,
#[cfg(not(feature = "web"))]
pub callback: (),
}
impl std::fmt::Debug for EventListener {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EventListener")
.field("name", &self.name)
.finish()
}
}
impl Render for Element {
fn render(&self) -> String {
let attrs = self
.attributes
.iter()
.filter(|a| is_valid_attr_name(&a.name))
.filter_map(|a| {
a.current_value()
.map(|value| format!(" {}=\"{}\"", a.name, escape_html_attr(&value)))
})
.collect::<String>();
let children = if is_raw_text_element(&self.tag) {
let mut raw = String::new();
self.children
.iter()
.for_each(|c| raw_text_content(c, &mut raw));
escape_raw_text(&self.tag, &raw)
} else {
self.children.iter().map(|c| c.render()).collect::<String>()
};
match self.tag.as_str() {
"area" | "base" | "br" | "col" | "embed" | "hr" | "img" | "input" | "link" | "meta"
| "param" | "source" | "track" | "wbr" => {
format!("<{}{}/>{}", self.tag, attrs, children)
}
_ if self.children.is_empty() => format!("<{}{}></{}>", self.tag, attrs, self.tag),
_ => format!("<{}{}>{}</{}>", self.tag, attrs, children, self.tag),
}
}
}
pub type DynamicAttributeValue = Rc<dyn Fn() -> Option<String>>;
#[derive(Clone)]
pub struct Attribute {
pub name: String,
pub value: String,
pub dynamic: Option<DynamicAttributeValue>,
}
impl std::fmt::Debug for Attribute {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut debug = f.debug_struct("Attribute");
debug.field("name", &self.name);
match &self.dynamic {
Some(_) => debug.field("value", &"<dynamic>"),
None => debug.field("value", &self.value),
};
debug.finish()
}
}
impl Attribute {
pub fn new(name: String, value: String) -> Self {
Self {
name,
value,
dynamic: None,
}
}
pub fn dynamic<F, V>(name: impl Into<String>, source: F) -> Self
where
F: Fn() -> V + 'static,
V: IntoAttributeValue,
{
Self {
name: name.into(),
value: String::new(),
dynamic: Some(Rc::new(move || source().into_attribute_value())),
}
}
pub fn is_dynamic(&self) -> bool {
self.dynamic.is_some()
}
pub fn current_value(&self) -> Option<String> {
match &self.dynamic {
Some(source) => source(),
None => Some(self.value.clone()),
}
}
}
pub trait IntoAttributeValue {
fn into_attribute_value(self) -> Option<String>;
}
impl IntoAttributeValue for String {
fn into_attribute_value(self) -> Option<String> {
Some(self)
}
}
impl IntoAttributeValue for &str {
fn into_attribute_value(self) -> Option<String> {
Some(self.to_string())
}
}
impl IntoAttributeValue for &String {
fn into_attribute_value(self) -> Option<String> {
Some(self.clone())
}
}
impl IntoAttributeValue for std::borrow::Cow<'_, str> {
fn into_attribute_value(self) -> Option<String> {
Some(self.into_owned())
}
}
impl IntoAttributeValue for bool {
fn into_attribute_value(self) -> Option<String> {
self.then(String::new)
}
}
impl<T: IntoAttributeValue> IntoAttributeValue for Option<T> {
fn into_attribute_value(self) -> Option<String> {
self.and_then(IntoAttributeValue::into_attribute_value)
}
}
macro_rules! display_attribute_value {
($($t:ty),* $(,)?) => {
$(
impl IntoAttributeValue for $t {
fn into_attribute_value(self) -> Option<String> {
Some(self.to_string())
}
}
)*
};
}
display_attribute_value!(
char, i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64
);
pub trait IntoNode {
fn into_node(self) -> Node;
}
impl IntoNode for Node {
fn into_node(self) -> Node {
self
}
}
impl IntoNode for String {
fn into_node(self) -> Node {
Node::Text(self)
}
}
impl IntoNode for &str {
fn into_node(self) -> Node {
Node::Text(self.to_string())
}
}
impl IntoNode for i32 {
fn into_node(self) -> Node {
Node::Text(self.to_string())
}
}
impl IntoNode for &i32 {
fn into_node(self) -> Node {
Node::Text(self.to_string())
}
}
impl<F> IntoNode for F
where
F: Fn() -> Node + 'static,
{
fn into_node(self) -> Node {
Node::Dynamic(Rc::new(self))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn attr_value<'a>(node: &'a Node, name: &str) -> Option<&'a str> {
let Node::Element(element) = node else {
return None;
};
element
.attributes
.iter()
.find(|attr| attr.name == name)
.map(|attr| attr.value.as_str())
}
#[test]
fn annotate_hydration_tree_assigns_stable_element_paths() {
let node = Node::Element(Element {
tag: "div".to_string(),
attributes: vec![],
children: vec![Node::Element(Element {
tag: "span".to_string(),
attributes: vec![],
children: vec![Node::Text("hello".to_string())],
events: vec![],
})],
events: vec![],
});
let annotated = annotate_hydration_tree(node, "boundary:1");
let Node::Element(root) = annotated else {
panic!("expected root element");
};
assert_eq!(
root.attributes
.iter()
.find(|attr| attr.name == HYDRATION_NODE_ID_ATTR)
.map(|attr| attr.value.as_str()),
Some("boundary:1/0")
);
assert_eq!(
root.children
.first()
.and_then(|child| attr_value(child, HYDRATION_NODE_ID_ATTR)),
Some("boundary:1/0.0")
);
}
#[test]
fn hydration_node_marker_round_trips_and_builds_child_paths() {
let marker = HydrationNodeMarker::root("profile:7");
assert_eq!(marker.as_attr_value(), "profile:7/0");
let child = marker.child(2);
assert_eq!(child.as_attr_value(), "profile:7/0.2");
let parsed = HydrationNodeMarker::parse("profile:7/0.2").expect("marker should parse");
assert_eq!(parsed, child);
}
#[test]
fn annotate_hydration_tree_does_not_descend_into_nested_island_wrappers() {
let node = Node::Element(Element {
tag: "section".to_string(),
attributes: vec![],
children: vec![Node::Element(Element {
tag: "div".to_string(),
attributes: vec![Attribute::new(
ISLAND_NAME_ATTR.to_string(),
"NestedIsland".to_string(),
)],
children: vec![Node::Element(Element {
tag: "span".to_string(),
attributes: vec![Attribute::new(
HYDRATION_NODE_ID_ATTR.to_string(),
"nested-boundary/0".to_string(),
)],
children: vec![],
events: vec![],
})],
events: vec![],
})],
events: vec![],
});
let annotated = annotate_hydration_tree(node, "outer:1");
let Node::Element(root) = annotated else {
panic!("expected root element");
};
let Some(Node::Element(nested_wrapper)) = root.children.first() else {
panic!("expected nested island wrapper");
};
assert_eq!(
nested_wrapper
.attributes
.iter()
.find(|attr| attr.name == HYDRATION_NODE_ID_ATTR)
.map(|attr| attr.value.as_str()),
Some("outer:1/0.0")
);
assert_eq!(
nested_wrapper
.children
.first()
.and_then(|child| attr_value(child, HYDRATION_NODE_ID_ATTR)),
Some("nested-boundary/0")
);
}
}
#[cfg(test)]
mod render_safety_tests {
use super::*;
fn el(tag: &str, attrs: Vec<Attribute>, children: Vec<Node>) -> Element {
Element {
tag: tag.to_string(),
attributes: attrs,
children,
events: Vec::new(),
}
}
fn attr(name: &str, value: &str) -> Attribute {
Attribute::new(name.to_string(), value.to_string())
}
#[test]
fn dynamic_attribute_renders_its_current_value() {
let (label, set_label) = crate::signal::create_signal("first".to_string());
let node = el(
"div",
vec![Attribute::dynamic("title", move || label.get())],
vec![],
);
assert_eq!(node.render(), "<div title=\"first\"></div>");
set_label.set("se\"cond".to_string());
assert_eq!(node.render(), "<div title=\"se"cond\"></div>");
}
#[test]
fn dynamic_attribute_returning_none_is_omitted() {
let (busy, set_busy) = crate::signal::create_signal(false);
let node = el(
"button",
vec![
Attribute::dynamic("disabled", move || busy.get()),
attr("class", "b"),
],
vec![],
);
assert_eq!(node.render(), "<button class=\"b\"></button>");
set_busy.set(true);
assert_eq!(node.render(), "<button disabled=\"\" class=\"b\"></button>");
}
#[test]
fn attribute_values_convert_by_type() {
assert_eq!(true.into_attribute_value(), Some(String::new()));
assert_eq!(false.into_attribute_value(), None);
assert_eq!(Some(3u8).into_attribute_value(), Some("3".to_string()));
assert_eq!(None::<&str>.into_attribute_value(), None);
assert_eq!("x".into_attribute_value(), Some("x".to_string()));
}
#[test]
fn static_and_dynamic_attributes_report_their_kind() {
let fixed = attr("id", "a");
let live = Attribute::dynamic("id", || "b");
assert!(!fixed.is_dynamic());
assert!(live.is_dynamic());
assert_eq!(fixed.current_value().as_deref(), Some("a"));
assert_eq!(live.current_value().as_deref(), Some("b"));
assert!(format!("{live:?}").contains("<dynamic>"));
}
#[test]
fn attribute_name_that_would_open_a_second_attribute_is_dropped() {
let node = el(
"div",
vec![attr("x onload=alert(1)", "v"), attr("class", "ok")],
vec![],
);
let html = node.render();
assert!(
!html.contains("onload"),
"injected handler survived: {html}"
);
assert_eq!(html, "<div class=\"ok\"></div>");
}
#[test]
fn ordinary_attribute_names_still_render() {
let node = el(
"div",
vec![
attr("data-krab-boundary-id", "counter/0"),
attr("aria-label", "hi"),
attr("xml:lang", "en"),
attr("_private", "1"),
],
vec![],
);
let html = node.render();
assert!(html.contains("data-krab-boundary-id=\"counter/0\""));
assert!(html.contains("aria-label=\"hi\""));
assert!(html.contains("xml:lang=\"en\""));
assert!(html.contains("_private=\"1\""));
}
#[test]
fn attribute_values_are_still_escaped() {
let node = el("div", vec![attr("title", "\"><script>x</script>")], vec![]);
let html = node.render();
assert!(!html.contains("<script>"), "unescaped value: {html}");
assert!(html.contains(""><script>"));
}
#[test]
fn void_element_with_children_does_not_emit_a_closing_tag() {
let node = el(
"br",
vec![],
vec![Node::Text("after the break".to_string())],
);
let html = node.render();
assert_eq!(html, "<br/>after the break");
assert!(!html.contains("</br>"));
}
#[test]
fn script_text_is_emitted_raw_not_entity_escaped() {
let node = el(
"script",
vec![attr("type", "module")],
vec![Node::Text(
"const f = (a) => a && b < c; x > y;".to_string(),
)],
);
assert_eq!(
node.render(),
"<script type=\"module\">const f = (a) => a && b < c; x > y;</script>"
);
}
#[test]
fn style_text_is_emitted_raw_not_entity_escaped() {
let node = el(
"style",
vec![],
vec![Node::Text(".a > .b { content: \"&\"; }".to_string())],
);
assert_eq!(node.render(), "<style>.a > .b { content: \"&\"; }</style>");
}
#[test]
fn script_text_cannot_close_its_own_element() {
let node = el(
"script",
vec![],
vec![Node::Text(
"let s = \"</ScRiPt><img src=x onerror=alert(1)>\";".to_string(),
)],
);
let html = node.render();
assert_eq!(html.to_ascii_lowercase().matches("</script").count(), 1);
assert!(html.ends_with("</script>"));
assert!(html.contains(r"<\/ScRiPt>"), "casing not preserved: {html}");
}
#[test]
fn script_text_cannot_enter_the_double_escaped_state() {
let node = el(
"script",
vec![],
vec![Node::Text("var s = \"<!--<script>\";".to_string())],
);
let html = node.render();
assert!(!html.contains("<!--"), "{html}");
assert!(html.contains("\\u003C!--"), "{html}");
}
#[test]
fn style_text_cannot_close_its_own_element() {
let node = el(
"style",
vec![],
vec![Node::Text(
"a{} </STYLE><script>alert(1)</script>".to_string(),
)],
);
let html = node.render();
assert_eq!(html.to_ascii_lowercase().matches("</style").count(), 1);
assert!(html.contains(r"<\/STYLE>"), "{html}");
assert!(html.contains("<script>alert(1)</script>"));
}
#[test]
fn raw_text_elements_match_their_tag_case_insensitively() {
let node = el("SCRIPT", vec![], vec![Node::Text("a => b".to_string())]);
assert_eq!(node.render(), "<SCRIPT>a => b</SCRIPT>");
}
#[test]
fn text_outside_raw_text_elements_is_still_escaped() {
let node = el("p", vec![], vec![Node::Text("a => b".to_string())]);
assert_eq!(node.render(), "<p>a => b</p>");
}
#[test]
fn void_and_normal_elements_without_children_are_unchanged() {
assert_eq!(el("br", vec![], vec![]).render(), "<br/>");
assert_eq!(el("div", vec![], vec![]).render(), "<div></div>");
}
}