use crate::php;
use std::collections::HashSet;
use std::path::Path;
use syn::parse::Parser;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PublicProperty {
pub name: String,
pub rust_type: String,
pub default_literal: String,
}
pub struct ConvertedLivewireComponent {
pub properties: Vec<PublicProperty>,
pub unsupported_properties: Vec<String>,
pub view_name: Option<String>,
pub layout_name: Option<String>,
}
pub fn convert(source: &str, class_name: &str) -> Result<ConvertedLivewireComponent, String> {
let tree = php::parse(source).map_err(|e| e.to_string())?;
if php::has_syntax_error(&tree) {
return Err("file has a syntax error the parser couldn't recover from".to_string());
}
let Some(class_node) = php::find_class(&tree, source, class_name) else {
return Err(format!("class `{class_name}` not found in this file"));
};
let (properties, unsupported_properties) = public_properties(class_node, source);
let (view_name, layout_name) = render_view_target(class_node, source);
Ok(ConvertedLivewireComponent {
properties,
unsupported_properties,
view_name,
layout_name,
})
}
fn public_properties(
class_node: tree_sitter::Node,
source: &str,
) -> (Vec<PublicProperty>, Vec<String>) {
let bytes = source.as_bytes();
let mut properties = Vec::new();
let mut unsupported = Vec::new();
let Some(body) = class_node.child_by_field_name("body") else {
return (properties, unsupported);
};
for declaration in php::direct_children_of_kind(body, "property_declaration") {
let is_public = php::direct_children_of_kind(declaration, "visibility_modifier")
.iter()
.any(|m| m.utf8_text(bytes) == Ok("public"));
if !is_public {
continue;
}
for element in php::direct_children_of_kind(declaration, "property_element") {
let Some(name_node) = element.child_by_field_name("name") else {
continue;
};
let Some(name_inner) = name_node.named_child(0) else {
continue;
};
let Ok(name) = name_inner.utf8_text(bytes) else {
continue;
};
let Some(default_value) = element.child_by_field_name("default_value") else {
unsupported.push(format!(
"${name}: no literal default value to infer a Rust type/default from"
));
continue;
};
match rust_literal(default_value, bytes) {
Some((rust_type, default_literal)) => properties.push(PublicProperty {
name: name.to_string(),
rust_type,
default_literal,
}),
None => unsupported.push(format!(
"${name}: default value isn't a plain literal this phase can translate"
)),
}
}
}
(properties, unsupported)
}
fn rust_literal(node: tree_sitter::Node, bytes: &[u8]) -> Option<(String, String)> {
match node.kind() {
"string" => {
let text = php::unquote(node.utf8_text(bytes).ok()?);
Some(("String".to_string(), format!("{text:?}.to_string()")))
}
"encapsed_string" if node.named_child_count() == 0 => {
Some(("String".to_string(), "\"\".to_string()".to_string()))
}
"encapsed_string" if node.named_child_count() == 1 => {
let content = node.named_child(0)?;
if content.kind() != "string_content" {
return None;
}
let text = content.utf8_text(bytes).ok()?;
Some(("String".to_string(), format!("{text:?}.to_string()")))
}
"boolean" => Some(("bool".to_string(), node.utf8_text(bytes).ok()?.to_string())),
"integer" => Some(("i64".to_string(), node.utf8_text(bytes).ok()?.to_string())),
"float" => Some(("f64".to_string(), node.utf8_text(bytes).ok()?.to_string())),
_ => None,
}
}
fn render_view_target(
class_node: tree_sitter::Node,
source: &str,
) -> (Option<String>, Option<String>) {
let Some(body) = class_node.child_by_field_name("body") else {
return (None, None);
};
for method in php::direct_children_of_kind(body, "method_declaration") {
let Some(name_node) = method.child_by_field_name("name") else {
continue;
};
if name_node.utf8_text(source.as_bytes()) != Ok("render") {
continue;
}
let Some(method_body) = method.child_by_field_name("body") else {
continue;
};
for statement in php::direct_children_of_kind(method_body, "return_statement") {
let Some(expr) = php::return_expression(statement) else {
continue;
};
if let Some(name) = view_call_argument(expr, source) {
return (Some(name), render_layout_target(expr, source));
}
}
}
(None, None)
}
fn render_layout_target(node: tree_sitter::Node, source: &str) -> Option<String> {
match node.kind() {
"member_call_expression" => {
let name_node = node.child_by_field_name("name")?;
if name_node.utf8_text(source.as_bytes()).ok()? == "layout" {
let arg = php::argument_node(node, 0)?;
return if arg.kind() == "string" {
Some(php::unquote(arg.utf8_text(source.as_bytes()).ok()?))
} else {
None
};
}
let object = node.child_by_field_name("object")?;
render_layout_target(object, source)
}
_ => None,
}
}
fn view_call_argument(node: tree_sitter::Node, source: &str) -> Option<String> {
match node.kind() {
"function_call_expression" => {
let function = node.child_by_field_name("function")?;
if function.utf8_text(source.as_bytes()).ok()? != "view" {
return None;
}
let arg = php::argument_node(node, 0)?;
if arg.kind() != "string" {
return None;
}
Some(php::unquote(arg.utf8_text(source.as_bytes()).ok()?))
}
"member_call_expression" => {
let object = node.child_by_field_name("object")?;
view_call_argument(object, source)
}
_ => None,
}
}
pub fn view_is_safe_for_scope(
views_root: &Path,
view_name: &str,
bound_names: &HashSet<String>,
) -> bool {
let Some(nodes) = load_and_resolve(views_root, view_name) else {
return false;
};
tree_is_safe(&nodes, views_root, bound_names)
}
pub struct HeadPush {
pub text: Option<String>,
}
pub fn head_pushes(views_root: &Path, view_name: &str) -> Vec<HeadPush> {
let Some(root) = load_template(views_root, view_name) else {
return Vec::new();
};
let mut out = Vec::new();
let mut visited = HashSet::new();
collect_head_pushes(&root, views_root, &mut visited, &mut out);
out
}
fn collect_head_pushes(
nodes: &[larust_view::Node],
views_root: &Path,
visited: &mut HashSet<String>,
out: &mut Vec<HeadPush>,
) {
use larust_view::Node;
for node in nodes {
match node {
Node::Push { name, body } if name == "head" => {
out.push(HeadPush {
text: static_push_text(body),
});
collect_head_pushes(body, views_root, visited, out);
}
Node::If {
then_branch,
else_branch,
..
} => {
collect_head_pushes(then_branch, views_root, visited, out);
collect_head_pushes(else_branch, views_root, visited, out);
}
Node::Foreach { body, .. }
| Node::Section { body, .. }
| Node::LoadOnce(body)
| Node::Live { body, .. } => collect_head_pushes(body, views_root, visited, out),
Node::Resource { name, slot, .. } => {
collect_head_pushes(slot, views_root, visited, out);
if visited.insert(name.clone()) {
if let Some(resource_nodes) = load_template(views_root, name) {
collect_head_pushes(&resource_nodes, views_root, visited, out);
}
}
}
_ => {}
}
}
}
fn static_push_text(nodes: &[larust_view::Node]) -> Option<String> {
let mut out = String::new();
for node in nodes {
match node {
larust_view::Node::Text(text) => out.push_str(text),
_ => return None,
}
}
Some(out)
}
#[derive(Debug, Clone, Copy)]
pub enum LayoutGlobalResolution {
Literal(&'static str),
CapturedAtMount {
field_type: &'static str,
mount_expr: &'static str,
},
}
pub struct LayoutGlobal {
pub name: &'static str,
pub resolution: LayoutGlobalResolution,
}
pub const KNOWN_LAYOUT_GLOBALS: &[LayoutGlobal] = &[
LayoutGlobal {
name: "theme",
resolution: LayoutGlobalResolution::Literal("\"lightmode\".to_string()"),
},
LayoutGlobal {
name: "csrf_token",
resolution: LayoutGlobalResolution::CapturedAtMount {
field_type: "String",
mount_expr: "larust_http::csrf::token(session).await",
},
},
];
pub fn layout_globals_for(
views_root: &Path,
layout_view: &str,
bound_names: &HashSet<String>,
) -> Option<Vec<&'static LayoutGlobal>> {
let global_names: HashSet<String> = KNOWN_LAYOUT_GLOBALS
.iter()
.map(|global| global.name.to_string())
.collect();
let referenced = referenced_names(views_root, layout_view, bound_names, &global_names)?;
Some(
KNOWN_LAYOUT_GLOBALS
.iter()
.filter(|global| referenced.contains(global.name))
.collect(),
)
}
pub fn referenced_names(
views_root: &Path,
view_name: &str,
always_bound: &HashSet<String>,
candidates: &HashSet<String>,
) -> Option<HashSet<String>> {
let full_bound: HashSet<String> = always_bound.union(candidates).cloned().collect();
if !view_is_safe_for_scope(views_root, view_name, &full_bound) {
return None;
}
Some(
candidates
.iter()
.filter(|candidate| {
let mut without_candidate = full_bound.clone();
without_candidate.remove(*candidate);
!view_is_safe_for_scope(views_root, view_name, &without_candidate)
})
.cloned()
.collect(),
)
}
fn load_and_resolve(views_root: &Path, view_name: &str) -> Option<Vec<larust_view::Node>> {
let root = load_template(views_root, view_name)?;
larust_view::resolve(root, &mut |parent| {
load_template(views_root, parent)
.ok_or_else(|| larust_view::ParseError::new(format!("template `{parent}` not found")))
})
.ok()
}
fn load_template(views_root: &Path, name: &str) -> Option<Vec<larust_view::Node>> {
let path = views_root
.join(name.replace('.', "/"))
.with_extension("blade.xr");
let source = std::fs::read_to_string(&path).ok()?;
larust_view::parse(&source).ok()
}
fn tree_is_safe(nodes: &[larust_view::Node], views_root: &Path, bound: &HashSet<String>) -> bool {
let mut scope = bound.clone();
for node in nodes {
if let larust_view::Node::Code(code) = node {
match code_block_bound_names(code, &scope) {
Some(new_names) => {
scope.extend(new_names);
continue;
}
None => return false,
}
}
if !node_is_safe(node, views_root, &scope) {
return false;
}
}
true
}
fn expr_is_bound(expr: &str, bound: &HashSet<String>) -> bool {
syn::parse_str::<syn::Expr>(expr).is_ok_and(|parsed| expr_free_names_are_bound(&parsed, bound))
}
fn node_is_safe(node: &larust_view::Node, views_root: &Path, bound: &HashSet<String>) -> bool {
use larust_view::Node;
match node {
Node::Text(_) => true,
Node::Code(code) => code_block_bound_names(code, bound).is_some(),
Node::Interpolate { expr, .. } => expr_is_bound(expr, bound),
Node::Js(expr) => expr_is_bound(expr, bound),
Node::If {
cond,
then_branch,
else_branch,
} => {
expr_is_bound(cond, bound)
&& tree_is_safe(then_branch, views_root, bound)
&& tree_is_safe(else_branch, views_root, bound)
}
Node::Foreach {
binding,
iter,
body,
} => {
let Ok(pat) = syn::Pat::parse_single.parse_str(binding) else {
return false;
};
let Some(pat_names) = pat_bound_names(&pat) else {
return false;
};
if !expr_is_bound(iter, bound) {
return false;
}
let mut scope = bound.clone();
scope.extend(pat_names);
tree_is_safe(body, views_root, &scope)
}
Node::Extends(_) => true,
Node::Section { body, .. } => tree_is_safe(body, views_root, bound),
Node::Yield(_) => true,
Node::Push { body, .. } => tree_is_safe(body, views_root, bound),
Node::Stack(_) => true,
Node::Csrf => false,
Node::Global { fallback, .. } => fallback
.as_deref()
.map(|f| expr_is_bound(f, bound))
.unwrap_or(true),
Node::Globals(_) => true,
Node::Wire { .. } => false,
Node::LarustScripts => true,
Node::LoadOnce(body) => tree_is_safe(body, views_root, bound),
Node::Resource { name, props, slot } => {
if !props.iter().all(|(_, expr)| expr_is_bound(expr, bound)) {
return false;
}
if !tree_is_safe(slot, views_root, bound) {
return false;
}
let Some(included) = load_template(views_root, name) else {
return false;
};
let included_bound: HashSet<String> =
props.iter().map(|(key, _)| key.clone()).collect();
tree_is_safe(&included, views_root, &included_bound)
}
Node::Live { channel, body } => {
expr_is_bound(channel, bound) && tree_is_safe(body, views_root, bound)
}
Node::Vitex(_) => true,
Node::PersistGlobal { .. } => false,
Node::Can { .. } | Node::Role { .. } => false,
Node::Spa(body) => tree_is_safe(body, views_root, bound),
Node::Image { props } => props.iter().all(|(_, expr)| expr_is_bound(expr, bound)),
}
}
fn code_block_bound_names(code: &str, bound: &HashSet<String>) -> Option<HashSet<String>> {
let Ok(block) = syn::parse_str::<syn::Block>(&format!("{{{code}}}")) else {
return None;
};
let mut scope = bound.clone();
let mut own_names = HashSet::new();
for stmt in &block.stmts {
match stmt {
syn::Stmt::Local(local) => {
let init = local.init.as_ref()?;
if init.diverge.is_some() {
return None; }
let syn::Pat::Ident(pat_ident) = &local.pat else {
return None; };
if pat_ident.by_ref.is_some() || pat_ident.subpat.is_some() {
return None;
}
if !expr_free_names_are_bound(&init.expr, &scope) {
return None;
}
let name = pat_ident.ident.to_string();
scope.insert(name.clone());
own_names.insert(name);
}
syn::Stmt::Expr(syn::Expr::Binary(bin), Some(_))
if matches!(
bin.op,
syn::BinOp::AddAssign(_)
| syn::BinOp::SubAssign(_)
| syn::BinOp::MulAssign(_)
| syn::BinOp::DivAssign(_)
| syn::BinOp::RemAssign(_)
) =>
{
let syn::Expr::Path(path) = bin.left.as_ref() else {
return None;
};
if path.qself.is_some() || path.path.segments.len() != 1 {
return None;
}
let name = path.path.segments[0].ident.to_string();
if !scope.contains(&name) {
return None;
}
if !expr_free_names_are_bound(&bin.right, &scope) {
return None;
}
}
_ => return None,
}
}
Some(own_names)
}
fn pat_bound_names(pat: &syn::Pat) -> Option<HashSet<String>> {
match pat {
syn::Pat::Ident(pat_ident) if pat_ident.by_ref.is_none() && pat_ident.subpat.is_none() => {
Some(HashSet::from([pat_ident.ident.to_string()]))
}
syn::Pat::Tuple(tuple) => {
let mut names = HashSet::new();
for elem in &tuple.elems {
names.extend(pat_bound_names(elem)?);
}
Some(names)
}
_ => None,
}
}
fn expr_free_names_are_bound(expr: &syn::Expr, bound: &HashSet<String>) -> bool {
use syn::Expr;
match expr {
Expr::Lit(_) => true,
Expr::Path(path_expr) => {
if path_expr.qself.is_none() && path_expr.path.segments.len() == 1 {
bound.contains(&path_expr.path.segments[0].ident.to_string())
} else {
true
}
}
Expr::Call(call) => {
expr_free_names_are_bound(&call.func, bound)
&& call
.args
.iter()
.all(|arg| expr_free_names_are_bound(arg, bound))
}
Expr::MethodCall(call) => {
expr_free_names_are_bound(&call.receiver, bound)
&& call
.args
.iter()
.all(|arg| expr_free_names_are_bound(arg, bound))
}
Expr::Field(field) => expr_free_names_are_bound(&field.base, bound),
Expr::Array(array) => array
.elems
.iter()
.all(|elem| expr_free_names_are_bound(elem, bound)),
Expr::Binary(bin) => {
expr_free_names_are_bound(&bin.left, bound)
&& expr_free_names_are_bound(&bin.right, bound)
}
Expr::Unary(un) => expr_free_names_are_bound(&un.expr, bound),
Expr::Reference(r) => expr_free_names_are_bound(&r.expr, bound),
Expr::Paren(p) => expr_free_names_are_bound(&p.expr, bound),
Expr::Group(g) => expr_free_names_are_bound(&g.expr, bound),
Expr::Cast(c) => expr_free_names_are_bound(&c.expr, bound),
Expr::Index(idx) => {
expr_free_names_are_bound(&idx.expr, bound)
&& expr_free_names_are_bound(&idx.index, bound)
}
Expr::If(if_expr) => {
expr_free_names_are_bound(&if_expr.cond, bound)
&& block_free_names_are_bound(&if_expr.then_branch, bound)
&& if_expr
.else_branch
.as_ref()
.is_none_or(|(_, else_expr)| expr_free_names_are_bound(else_expr, bound))
}
Expr::Block(b) => block_free_names_are_bound(&b.block, bound),
Expr::Macro(m) => {
if !m.mac.path.is_ident("format") {
return false;
}
let Ok(args) = m.mac.parse_body_with(
syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated,
) else {
return false;
};
args.iter().all(|arg| expr_free_names_are_bound(arg, bound))
}
Expr::Closure(closure) => {
if closure.inputs.len() > 1 {
return false;
}
let mut scope = bound.clone();
if let Some(input) = closure.inputs.first() {
let syn::Pat::Ident(pat_ident) = input else {
return false;
};
scope.insert(pat_ident.ident.to_string());
}
expr_free_names_are_bound(&closure.body, &scope)
}
_ => false,
}
}
fn block_free_names_are_bound(block: &syn::Block, bound: &HashSet<String>) -> bool {
block.stmts.iter().all(|stmt| match stmt {
syn::Stmt::Expr(expr, _) => expr_free_names_are_bound(expr, bound),
_ => false,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extracts_public_properties_with_literal_defaults() {
let source = "<?php\nclass Home extends Component {\n public $title = \"Hello\";\n public $banner = true;\n public $count = 5;\n}\n";
let result = convert(source, "Home").unwrap();
assert_eq!(result.properties.len(), 3);
let title = result
.properties
.iter()
.find(|p| p.name == "title")
.unwrap();
assert_eq!(title.rust_type, "String");
assert_eq!(title.default_literal, "\"Hello\".to_string()");
let banner = result
.properties
.iter()
.find(|p| p.name == "banner")
.unwrap();
assert_eq!(banner.rust_type, "bool");
assert_eq!(banner.default_literal, "true");
let count = result
.properties
.iter()
.find(|p| p.name == "count")
.unwrap();
assert_eq!(count.rust_type, "i64");
assert_eq!(count.default_literal, "5");
assert!(result.unsupported_properties.is_empty());
}
#[test]
fn an_empty_double_quoted_string_default_is_a_supported_literal() {
let source = r#"<?php
class Home extends Component {
public $canonical = "";
}
"#;
let result = convert(source, "Home").unwrap();
assert!(result.unsupported_properties.is_empty());
assert_eq!(result.properties.len(), 1);
assert_eq!(result.properties[0].rust_type, "String");
assert_eq!(result.properties[0].default_literal, "\"\".to_string()");
}
#[test]
fn protected_and_private_properties_are_never_exposed() {
let source = "<?php\nclass Home extends Component {\n protected $guard = 'web';\n private $secret = 'x';\n public $title = \"Hello\";\n}\n";
let result = convert(source, "Home").unwrap();
assert_eq!(result.properties.len(), 1);
assert_eq!(result.properties[0].name, "title");
}
#[test]
fn an_interpolated_double_quoted_string_is_flagged_not_guessed() {
let source = r#"<?php
class Home extends Component {
public $greeting = "Hello {$name}";
}
"#;
let result = convert(source, "Home").unwrap();
assert!(result.properties.is_empty());
assert_eq!(result.unsupported_properties.len(), 1);
assert!(result.unsupported_properties[0].contains("greeting"));
}
#[test]
fn a_property_with_no_default_is_flagged_not_guessed() {
let source = "<?php\nclass Home extends Component {\n public $current;\n}\n";
let result = convert(source, "Home").unwrap();
assert!(result.properties.is_empty());
assert_eq!(result.unsupported_properties.len(), 1);
assert!(result.unsupported_properties[0].contains("current"));
}
#[test]
fn a_non_literal_default_is_flagged_not_guessed() {
let source = "<?php\nclass Home extends Component {\n public $items = [1, 2, 3];\n}\n";
let result = convert(source, "Home").unwrap();
assert!(result.properties.is_empty());
assert_eq!(result.unsupported_properties.len(), 1);
assert!(result.unsupported_properties[0].contains("items"));
}
#[test]
fn extracts_the_view_name_from_a_plain_render_return() {
let source = "<?php\nclass Home extends Component {\n public function render()\n {\n return view('livewire.pages.index');\n }\n}\n";
let result = convert(source, "Home").unwrap();
assert_eq!(result.view_name.as_deref(), Some("livewire.pages.index"));
assert!(result.layout_name.is_none());
}
#[test]
fn extracts_the_view_name_through_a_chained_layout_call() {
let source = "<?php\nclass Home extends Component {\n public function render()\n {\n return view('livewire.pages.index')->layout('components.layouts.app', ['title' => $this->title]);\n }\n}\n";
let result = convert(source, "Home").unwrap();
assert_eq!(result.view_name.as_deref(), Some("livewire.pages.index"));
assert_eq!(
result.layout_name.as_deref(),
Some("components.layouts.app")
);
}
#[test]
fn no_render_method_means_no_view_name() {
let source = "<?php\nclass Home extends Component {\n}\n";
let result = convert(source, "Home").unwrap();
assert!(result.view_name.is_none());
}
#[test]
fn rejects_when_the_class_is_not_found_in_the_file() {
let source = "<?php\nclass Other extends Component {}\n";
assert!(convert(source, "Home").is_err());
}
fn write_view(dir: &std::path::Path, dotted_name: &str, content: &str) {
let path = dir.join(dotted_name.replace('.', "/") + ".blade.xr");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, content).unwrap();
}
#[test]
fn a_template_with_only_bound_interpolations_is_safe() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.index",
"<h1>{{ title }}</h1><p>{{ query }}</p>",
);
let bound = HashSet::from(["title".to_string(), "query".to_string()]);
assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
}
#[test]
fn layout_globals_for_finds_only_the_names_actually_referenced() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"layouts.app",
r#"<html class="{{ theme }}"><meta name="csrf-token" content="{{ csrf_token }}"><body>{{ slot }}</body></html>"#,
);
let bound = HashSet::from(["slot".to_string()]);
let globals = layout_globals_for(dir.path(), "layouts.app", &bound).unwrap();
let names: HashSet<&str> = globals.iter().map(|g| g.name).collect();
assert_eq!(names, HashSet::from(["theme", "csrf_token"]));
}
#[test]
fn layout_globals_for_finds_nothing_when_the_layout_uses_neither_known_global() {
let dir = tempfile::tempdir().unwrap();
write_view(dir.path(), "layouts.app", "<body>{{ slot }}</body>");
let bound = HashSet::from(["slot".to_string()]);
let globals = layout_globals_for(dir.path(), "layouts.app", &bound).unwrap();
assert!(globals.is_empty());
}
#[test]
fn layout_globals_for_is_none_when_an_unrelated_name_stays_unbound() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"layouts.app",
"<body>{{ slot }}{{ theme }}{{ subtitle }}</body>",
);
let bound = HashSet::from(["slot".to_string()]);
assert!(layout_globals_for(dir.path(), "layouts.app", &bound).is_none());
}
#[test]
fn referenced_names_finds_only_the_candidates_the_template_actually_mentions() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"layouts.app",
r#"<html class="{{ theme }}"><body>{{ slot }}</body></html>"#,
);
let candidates: HashSet<String> = ["theme", "slot", "title", "url", "canonical"]
.into_iter()
.map(String::from)
.collect();
let found =
referenced_names(dir.path(), "layouts.app", &HashSet::new(), &candidates).unwrap();
assert_eq!(
found,
HashSet::from(["theme".to_string(), "slot".to_string()])
);
}
#[test]
fn a_bare_word_that_only_appears_as_a_substring_of_another_identifier_is_not_referenced() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"layouts.app",
"<meta name=\"mytheme-title\"><body>{{ slot }}</body>",
);
let bound = HashSet::from(["slot".to_string()]);
let globals = layout_globals_for(dir.path(), "layouts.app", &bound).unwrap();
assert!(globals.is_empty());
}
#[test]
fn an_unbound_interpolation_is_unsafe() {
let dir = tempfile::tempdir().unwrap();
write_view(dir.path(), "pages.index", "<h1>{{ subtitle }}</h1>");
let bound = HashSet::from(["title".to_string()]);
assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
}
#[test]
fn a_top_level_wire_tag_is_unsafe() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.index",
"<wire:search-box :query='query' />",
);
let bound = HashSet::from(["query".to_string()]);
assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
}
#[test]
fn a_resource_include_with_no_wire_or_csrf_inside_is_safe() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.index",
"<resource:components.head :title='title'></resource:components.head>",
);
write_view(dir.path(), "components.head", "<title>{{ title }}</title>");
let bound = HashSet::from(["title".to_string()]);
assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
}
#[test]
fn a_resource_include_that_transitively_uses_wire_is_unsafe() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.index",
"<resource:components.navbar></resource:components.navbar>",
);
write_view(dir.path(), "components.navbar", "<wire:search-box />");
let bound: HashSet<String> = HashSet::new();
assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
}
#[test]
fn a_foreach_over_a_bound_iterable_referencing_its_own_binding_is_safe() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.index",
"@foreach(item in itemlist)<p>{{ item }}</p>@endforeach",
);
let bound = HashSet::from(["itemlist".to_string()]);
assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
}
#[test]
fn a_foreach_over_an_unbound_iterable_is_unsafe() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.index",
"@foreach(item in itemlist)<p>{{ item }}</p>@endforeach",
);
let bound: HashSet<String> = HashSet::new();
assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
}
#[test]
fn a_foreach_body_referencing_a_name_outside_the_binding_and_outer_scope_is_unsafe() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.index",
"@foreach(item in itemlist)<p>{{ subtitle }}</p>@endforeach",
);
let bound = HashSet::from(["itemlist".to_string()]);
assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
}
#[test]
fn a_keyed_with_loop_foreach_binds_both_tuple_names_and_the_loop_variable() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.index",
"@foreach(((key, item), loop_) in larust_support::WithLoop::with_loop((items).iter().enumerate()))\
{{ if larust_support::truthy::truthy(&(!(loop_.last))) { (\",\").to_string() } else { (\"\").to_string() } }}\
@endforeach",
);
let bound = HashSet::from(["items".to_string()]);
assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
}
#[test]
fn a_resource_props_own_expression_must_also_be_bound() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.index",
"<resource:components.head :title='unbound_name'></resource:components.head>",
);
write_view(dir.path(), "components.head", "<title>{{ title }}</title>");
let bound: HashSet<String> = HashSet::new();
assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
}
#[test]
fn a_missing_template_is_unsafe() {
let dir = tempfile::tempdir().unwrap();
let bound: HashSet<String> = HashSet::new();
assert!(!view_is_safe_for_scope(dir.path(), "pages.missing", &bound));
}
#[test]
fn a_csrf_directive_is_unsafe() {
let dir = tempfile::tempdir().unwrap();
write_view(dir.path(), "pages.form", "<form>@csrf</form>");
let bound: HashSet<String> = HashSet::new();
assert!(!view_is_safe_for_scope(dir.path(), "pages.form", &bound));
}
#[test]
fn a_can_directive_is_unsafe() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.editable",
"@can(Permission::EditPosts)yes@endcan",
);
let bound: HashSet<String> = HashSet::new();
assert!(!view_is_safe_for_scope(
dir.path(),
"pages.editable",
&bound
));
}
#[test]
fn a_role_directive_is_unsafe() {
let dir = tempfile::tempdir().unwrap();
write_view(dir.path(), "pages.admin", "@role(Role::Admin)yes@endrole");
let bound: HashSet<String> = HashSet::new();
assert!(!view_is_safe_for_scope(dir.path(), "pages.admin", &bound));
}
#[test]
fn a_spa_directive_with_a_safe_body_is_safe() {
let dir = tempfile::tempdir().unwrap();
write_view(dir.path(), "pages.home", "@spa <p>hi</p> @endspa");
let bound: HashSet<String> = HashSet::new();
assert!(view_is_safe_for_scope(dir.path(), "pages.home", &bound));
}
#[test]
fn a_spa_directive_wrapping_an_unsafe_node_is_still_unsafe() {
let dir = tempfile::tempdir().unwrap();
write_view(dir.path(), "pages.home", "@spa @csrf @endspa");
let bound: HashSet<String> = HashSet::new();
assert!(!view_is_safe_for_scope(dir.path(), "pages.home", &bound));
}
#[test]
fn a_code_block_with_only_literal_lets_is_safe() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"errors.404",
"@code let mut title = \"Page Not Found\"; let mut noindex = true; @endcode<h1>{{ title }}</h1>",
);
let bound: HashSet<String> = HashSet::new();
assert!(view_is_safe_for_scope(dir.path(), "errors.404", &bound));
}
#[test]
fn a_code_blocks_own_bindings_are_visible_to_later_siblings() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.index",
"@code let mut greeting = \"hi\"; @endcode<p>{{ greeting }}</p>",
);
let bound: HashSet<String> = HashSet::new();
assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
}
#[test]
fn a_code_block_referencing_an_unbound_name_is_unsafe() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.index",
"@code let mut greeting = format!(\"hi {}\", session); @endcode",
);
let bound: HashSet<String> = HashSet::new();
assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
}
#[test]
fn a_code_block_incrementing_an_already_bound_counter_is_safe() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.index",
"@code let mut x = 0; @endcode@code x += 1; @endcode{{ x }}",
);
let bound: HashSet<String> = HashSet::new();
assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
}
#[test]
fn a_compound_assignment_to_an_unbound_name_is_unsafe() {
let dir = tempfile::tempdir().unwrap();
write_view(dir.path(), "pages.index", "@code x += 1; @endcode");
let bound: HashSet<String> = HashSet::new();
assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
}
#[test]
fn a_compound_assignment_referencing_an_unbound_name_on_the_right_is_unsafe() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.index",
"@code let mut x = 0; x += unbound_step; @endcode",
);
let bound: HashSet<String> = HashSet::new();
assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
}
#[test]
fn a_code_block_matching_the_real_head_component_shape_is_safe() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"components.head",
r#"@code let mut appUrl = larust_support::config("app.url").unwrap_or_default(); let mut canonicalUrl = if larust_support::truthy::truthy(&((canonical).starts_with("http://") || (canonical).starts_with("https://"))) { canonical } else { format!("{}{}", appUrl, canonical) }; @endcode<link href="{{ canonicalUrl }}" />"#,
);
let bound = HashSet::from(["canonical".to_string()]);
assert!(view_is_safe_for_scope(
dir.path(),
"components.head",
&bound
));
}
#[test]
fn a_code_block_calling_vitex_tags_with_an_array_literal_is_safe() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"layouts.app",
r#"@code let __vitex_tags = larust_support::vitex::tags(&["resources/css/app.min.css", "resources/js/app.min.js"]); @endcode{!! __vitex_tags !!}"#,
);
assert!(view_is_safe_for_scope(
dir.path(),
"layouts.app",
&HashSet::new()
));
}
#[test]
fn a_code_block_with_a_bound_single_param_closure_is_safe() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.index",
r#"@code let mut keys = (keywords).split(",").map(|s| s.to_string()).collect::<Vec<String>>(); @endcode"#,
);
let bound = HashSet::from(["keywords".to_string()]);
assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
}
#[test]
fn a_code_block_with_a_bare_expression_statement_is_unsafe() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.index",
"@code let mut x = 0; x.clear(); @endcode",
);
let bound: HashSet<String> = HashSet::new();
assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
}
#[test]
fn a_code_block_destructuring_a_pattern_is_unsafe() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.index",
"@code let (a, b) = (1, 2); @endcode",
);
let bound: HashSet<String> = HashSet::new();
assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
}
#[test]
fn a_code_block_indexing_a_bound_value_is_safe() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.index",
r#"@code let mut body = (data["bodytext"]).replace("a", "b"); @endcode"#,
);
let bound = HashSet::from(["data".to_string()]);
assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
}
#[test]
fn an_interpolation_containing_a_full_if_else_expression_is_safe_when_bound() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"components.navbar",
r#"<nav class="{{ if larust_support::truthy::truthy(&(banner)) { "" } else { "sticky-nav" } }}"></nav>"#,
);
let bound = HashSet::from(["banner".to_string()]);
assert!(view_is_safe_for_scope(
dir.path(),
"components.navbar",
&bound
));
}
#[test]
fn an_interpolation_with_a_method_chain_on_a_bound_value_is_safe() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"components.navbar",
r#"<a class="{{ if (current).contains(&("home")) { "active" } else { "" } }}">Home</a>"#,
);
let bound = HashSet::from(["current".to_string()]);
assert!(view_is_safe_for_scope(
dir.path(),
"components.navbar",
&bound
));
}
#[test]
fn head_pushes_finds_a_push_in_the_content_template_itself() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.contact",
"@push('head')<link rel=\"stylesheet\" href=\"/css/text.min.css\">@endpush<div>hi</div>",
);
let pushes = head_pushes(dir.path(), "pages.contact");
assert_eq!(pushes.len(), 1);
assert_eq!(
pushes[0].text.as_deref(),
Some("<link rel=\"stylesheet\" href=\"/css/text.min.css\">")
);
}
#[test]
fn head_pushes_reaches_through_a_nested_resource_tag() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"elements.sunrise",
"@push('head')<link rel=\"stylesheet\" href=\"/css/sunrise.min.css\">@endpush<div>sun</div>",
);
write_view(
dir.path(),
"pages.index",
"<resource:elements.sunrise></resource:elements.sunrise>",
);
let pushes = head_pushes(dir.path(), "pages.index");
assert_eq!(pushes.len(), 1);
assert_eq!(
pushes[0].text.as_deref(),
Some("<link rel=\"stylesheet\" href=\"/css/sunrise.min.css\">")
);
}
#[test]
fn head_pushes_with_dynamic_content_are_reported_as_unhoistable() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"pages.contact",
"@push('head')<title>{{ title }}</title>@endpush",
);
let pushes = head_pushes(dir.path(), "pages.contact");
assert_eq!(pushes.len(), 1);
assert!(pushes[0].text.is_none());
}
#[test]
fn head_pushes_does_not_duplicate_a_resource_included_more_than_once() {
let dir = tempfile::tempdir().unwrap();
write_view(
dir.path(),
"elements.questions",
"@push('head')<link rel=\"stylesheet\" href=\"/css/questions.min.css\">@endpush",
);
write_view(
dir.path(),
"pages.contact",
"<resource:elements.questions></resource:elements.questions>\
<resource:elements.questions></resource:elements.questions>",
);
let pushes = head_pushes(dir.path(), "pages.contact");
assert_eq!(pushes.len(), 1);
}
#[test]
fn head_pushes_for_a_missing_template_is_empty_not_an_error() {
let dir = tempfile::tempdir().unwrap();
assert!(head_pushes(dir.path(), "pages.nonexistent").is_empty());
}
}