1use crate::php;
33use std::collections::HashSet;
34use std::path::Path;
35use syn::parse::Parser;
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct PublicProperty {
39 pub name: String,
40 pub rust_type: String,
41 pub default_literal: String,
44}
45
46pub struct ConvertedLivewireComponent {
47 pub properties: Vec<PublicProperty>,
49 pub unsupported_properties: Vec<String>,
56 pub view_name: Option<String>,
61 pub layout_name: Option<String>,
71}
72
73pub fn convert(source: &str, class_name: &str) -> Result<ConvertedLivewireComponent, String> {
74 let tree = php::parse(source).map_err(|e| e.to_string())?;
75 if php::has_syntax_error(&tree) {
76 return Err("file has a syntax error the parser couldn't recover from".to_string());
77 }
78 let Some(class_node) = php::find_class(&tree, source, class_name) else {
79 return Err(format!("class `{class_name}` not found in this file"));
80 };
81
82 let (properties, unsupported_properties) = public_properties(class_node, source);
83 let (view_name, layout_name) = render_view_target(class_node, source);
84
85 Ok(ConvertedLivewireComponent {
86 properties,
87 unsupported_properties,
88 view_name,
89 layout_name,
90 })
91}
92
93fn public_properties(
101 class_node: tree_sitter::Node,
102 source: &str,
103) -> (Vec<PublicProperty>, Vec<String>) {
104 let bytes = source.as_bytes();
105 let mut properties = Vec::new();
106 let mut unsupported = Vec::new();
107 let Some(body) = class_node.child_by_field_name("body") else {
108 return (properties, unsupported);
109 };
110 for declaration in php::direct_children_of_kind(body, "property_declaration") {
111 let is_public = php::direct_children_of_kind(declaration, "visibility_modifier")
112 .iter()
113 .any(|m| m.utf8_text(bytes) == Ok("public"));
114 if !is_public {
115 continue;
116 }
117 for element in php::direct_children_of_kind(declaration, "property_element") {
118 let Some(name_node) = element.child_by_field_name("name") else {
119 continue;
120 };
121 let Some(name_inner) = name_node.named_child(0) else {
122 continue;
123 };
124 let Ok(name) = name_inner.utf8_text(bytes) else {
125 continue;
126 };
127 let Some(default_value) = element.child_by_field_name("default_value") else {
128 unsupported.push(format!(
129 "${name}: no literal default value to infer a Rust type/default from"
130 ));
131 continue;
132 };
133 match rust_literal(default_value, bytes) {
134 Some((rust_type, default_literal)) => properties.push(PublicProperty {
135 name: name.to_string(),
136 rust_type,
137 default_literal,
138 }),
139 None => unsupported.push(format!(
140 "${name}: default value isn't a plain literal this phase can translate"
141 )),
142 }
143 }
144 }
145 (properties, unsupported)
146}
147
148fn rust_literal(node: tree_sitter::Node, bytes: &[u8]) -> Option<(String, String)> {
163 match node.kind() {
164 "string" => {
165 let text = php::unquote(node.utf8_text(bytes).ok()?);
166 Some(("String".to_string(), format!("{text:?}.to_string()")))
167 }
168 "encapsed_string" if node.named_child_count() == 0 => {
173 Some(("String".to_string(), "\"\".to_string()".to_string()))
174 }
175 "encapsed_string" if node.named_child_count() == 1 => {
176 let content = node.named_child(0)?;
177 if content.kind() != "string_content" {
178 return None;
179 }
180 let text = content.utf8_text(bytes).ok()?;
181 Some(("String".to_string(), format!("{text:?}.to_string()")))
182 }
183 "boolean" => Some(("bool".to_string(), node.utf8_text(bytes).ok()?.to_string())),
184 "integer" => Some(("i64".to_string(), node.utf8_text(bytes).ok()?.to_string())),
185 "float" => Some(("f64".to_string(), node.utf8_text(bytes).ok()?.to_string())),
186 _ => None,
187 }
188}
189
190fn render_view_target(
198 class_node: tree_sitter::Node,
199 source: &str,
200) -> (Option<String>, Option<String>) {
201 let Some(body) = class_node.child_by_field_name("body") else {
202 return (None, None);
203 };
204 for method in php::direct_children_of_kind(body, "method_declaration") {
205 let Some(name_node) = method.child_by_field_name("name") else {
206 continue;
207 };
208 if name_node.utf8_text(source.as_bytes()) != Ok("render") {
209 continue;
210 }
211 let Some(method_body) = method.child_by_field_name("body") else {
212 continue;
213 };
214 for statement in php::direct_children_of_kind(method_body, "return_statement") {
215 let Some(expr) = php::return_expression(statement) else {
216 continue;
217 };
218 if let Some(name) = view_call_argument(expr, source) {
219 return (Some(name), render_layout_target(expr, source));
220 }
221 }
222 }
223 (None, None)
224}
225
226fn render_layout_target(node: tree_sitter::Node, source: &str) -> Option<String> {
232 match node.kind() {
233 "member_call_expression" => {
234 let name_node = node.child_by_field_name("name")?;
235 if name_node.utf8_text(source.as_bytes()).ok()? == "layout" {
236 let arg = php::argument_node(node, 0)?;
237 return if arg.kind() == "string" {
238 Some(php::unquote(arg.utf8_text(source.as_bytes()).ok()?))
239 } else {
240 None
241 };
242 }
243 let object = node.child_by_field_name("object")?;
244 render_layout_target(object, source)
245 }
246 _ => None,
247 }
248}
249
250fn view_call_argument(node: tree_sitter::Node, source: &str) -> Option<String> {
257 match node.kind() {
258 "function_call_expression" => {
259 let function = node.child_by_field_name("function")?;
260 if function.utf8_text(source.as_bytes()).ok()? != "view" {
261 return None;
262 }
263 let arg = php::argument_node(node, 0)?;
264 if arg.kind() != "string" {
265 return None;
266 }
267 Some(php::unquote(arg.utf8_text(source.as_bytes()).ok()?))
268 }
269 "member_call_expression" => {
270 let object = node.child_by_field_name("object")?;
271 view_call_argument(object, source)
272 }
273 _ => None,
274 }
275}
276
277pub fn view_is_safe_for_scope(
299 views_root: &Path,
300 view_name: &str,
301 bound_names: &HashSet<String>,
302) -> bool {
303 let Some(nodes) = load_and_resolve(views_root, view_name) else {
304 return false;
305 };
306 tree_is_safe(&nodes, views_root, bound_names)
307}
308
309pub struct HeadPush {
312 pub text: Option<String>,
320}
321
322pub fn head_pushes(views_root: &Path, view_name: &str) -> Vec<HeadPush> {
348 let Some(root) = load_template(views_root, view_name) else {
349 return Vec::new();
350 };
351 let mut out = Vec::new();
352 let mut visited = HashSet::new();
353 collect_head_pushes(&root, views_root, &mut visited, &mut out);
354 out
355}
356
357fn collect_head_pushes(
358 nodes: &[larust_view::Node],
359 views_root: &Path,
360 visited: &mut HashSet<String>,
361 out: &mut Vec<HeadPush>,
362) {
363 use larust_view::Node;
364 for node in nodes {
365 match node {
366 Node::Push { name, body } if name == "head" => {
367 out.push(HeadPush {
368 text: static_push_text(body),
369 });
370 collect_head_pushes(body, views_root, visited, out);
375 }
376 Node::If {
377 then_branch,
378 else_branch,
379 ..
380 } => {
381 collect_head_pushes(then_branch, views_root, visited, out);
382 collect_head_pushes(else_branch, views_root, visited, out);
383 }
384 Node::Foreach { body, .. }
385 | Node::Section { body, .. }
386 | Node::LoadOnce(body)
387 | Node::Live { body, .. } => collect_head_pushes(body, views_root, visited, out),
388 Node::Resource { name, slot, .. } => {
389 collect_head_pushes(slot, views_root, visited, out);
390 if visited.insert(name.clone()) {
397 if let Some(resource_nodes) = load_template(views_root, name) {
398 collect_head_pushes(&resource_nodes, views_root, visited, out);
399 }
400 }
401 }
402 _ => {}
403 }
404 }
405}
406
407fn static_push_text(nodes: &[larust_view::Node]) -> Option<String> {
408 let mut out = String::new();
409 for node in nodes {
410 match node {
411 larust_view::Node::Text(text) => out.push_str(text),
412 _ => return None,
413 }
414 }
415 Some(out)
416}
417
418#[derive(Debug, Clone, Copy)]
420pub enum LayoutGlobalResolution {
421 Literal(&'static str),
425 CapturedAtMount {
430 field_type: &'static str,
431 mount_expr: &'static str,
432 },
433}
434
435pub struct LayoutGlobal {
436 pub name: &'static str,
437 pub resolution: LayoutGlobalResolution,
438}
439
440pub const KNOWN_LAYOUT_GLOBALS: &[LayoutGlobal] = &[
461 LayoutGlobal {
462 name: "theme",
463 resolution: LayoutGlobalResolution::Literal("\"lightmode\".to_string()"),
464 },
465 LayoutGlobal {
466 name: "csrf_token",
467 resolution: LayoutGlobalResolution::CapturedAtMount {
468 field_type: "String",
469 mount_expr: "larust_http::csrf::token(session).await",
470 },
471 },
472];
473
474pub fn layout_globals_for(
485 views_root: &Path,
486 layout_view: &str,
487 bound_names: &HashSet<String>,
488) -> Option<Vec<&'static LayoutGlobal>> {
489 let global_names: HashSet<String> = KNOWN_LAYOUT_GLOBALS
490 .iter()
491 .map(|global| global.name.to_string())
492 .collect();
493 let referenced = referenced_names(views_root, layout_view, bound_names, &global_names)?;
494 Some(
495 KNOWN_LAYOUT_GLOBALS
496 .iter()
497 .filter(|global| referenced.contains(global.name))
498 .collect(),
499 )
500}
501
502pub fn referenced_names(
523 views_root: &Path,
524 view_name: &str,
525 always_bound: &HashSet<String>,
526 candidates: &HashSet<String>,
527) -> Option<HashSet<String>> {
528 let full_bound: HashSet<String> = always_bound.union(candidates).cloned().collect();
529 if !view_is_safe_for_scope(views_root, view_name, &full_bound) {
530 return None;
531 }
532 Some(
533 candidates
534 .iter()
535 .filter(|candidate| {
536 let mut without_candidate = full_bound.clone();
537 without_candidate.remove(*candidate);
538 !view_is_safe_for_scope(views_root, view_name, &without_candidate)
539 })
540 .cloned()
541 .collect(),
542 )
543}
544
545fn load_and_resolve(views_root: &Path, view_name: &str) -> Option<Vec<larust_view::Node>> {
546 let root = load_template(views_root, view_name)?;
547 larust_view::resolve(root, &mut |parent| {
548 load_template(views_root, parent)
549 .ok_or_else(|| larust_view::ParseError::new(format!("template `{parent}` not found")))
550 })
551 .ok()
552}
553
554fn load_template(views_root: &Path, name: &str) -> Option<Vec<larust_view::Node>> {
555 let path = views_root
556 .join(name.replace('.', "/"))
557 .with_extension("blade.xr");
558 let source = std::fs::read_to_string(&path).ok()?;
559 larust_view::parse(&source).ok()
560}
561
562fn tree_is_safe(nodes: &[larust_view::Node], views_root: &Path, bound: &HashSet<String>) -> bool {
571 let mut scope = bound.clone();
572 for node in nodes {
573 if let larust_view::Node::Code(code) = node {
574 match code_block_bound_names(code, &scope) {
575 Some(new_names) => {
576 scope.extend(new_names);
577 continue;
578 }
579 None => return false,
580 }
581 }
582 if !node_is_safe(node, views_root, &scope) {
583 return false;
584 }
585 }
586 true
587}
588
589fn expr_is_bound(expr: &str, bound: &HashSet<String>) -> bool {
599 syn::parse_str::<syn::Expr>(expr).is_ok_and(|parsed| expr_free_names_are_bound(&parsed, bound))
600}
601
602fn node_is_safe(node: &larust_view::Node, views_root: &Path, bound: &HashSet<String>) -> bool {
603 use larust_view::Node;
604 match node {
605 Node::Text(_) => true,
606 Node::Code(code) => code_block_bound_names(code, bound).is_some(),
613 Node::Interpolate { expr, .. } => expr_is_bound(expr, bound),
614 Node::Js(expr) => expr_is_bound(expr, bound),
618 Node::If {
619 cond,
620 then_branch,
621 else_branch,
622 } => {
623 expr_is_bound(cond, bound)
624 && tree_is_safe(then_branch, views_root, bound)
625 && tree_is_safe(else_branch, views_root, bound)
626 }
627 Node::Foreach {
635 binding,
636 iter,
637 body,
638 } => {
639 let Ok(pat) = syn::Pat::parse_single.parse_str(binding) else {
644 return false;
645 };
646 let Some(pat_names) = pat_bound_names(&pat) else {
647 return false;
648 };
649 if !expr_is_bound(iter, bound) {
650 return false;
651 }
652 let mut scope = bound.clone();
653 scope.extend(pat_names);
654 tree_is_safe(body, views_root, &scope)
655 }
656 Node::Extends(_) => true,
657 Node::Section { body, .. } => tree_is_safe(body, views_root, bound),
658 Node::Yield(_) => true,
659 Node::Push { body, .. } => tree_is_safe(body, views_root, bound),
660 Node::Stack(_) => true,
661 Node::Csrf => false,
663 Node::Global { fallback, .. } => fallback
664 .as_deref()
665 .map(|f| expr_is_bound(f, bound))
666 .unwrap_or(true),
667 Node::Globals(_) => true,
668 Node::Wire { .. } => false,
670 Node::LarustScripts => true,
674 Node::LoadOnce(body) => tree_is_safe(body, views_root, bound),
675 Node::Resource { name, props, slot } => {
676 if !props.iter().all(|(_, expr)| expr_is_bound(expr, bound)) {
677 return false;
678 }
679 if !tree_is_safe(slot, views_root, bound) {
680 return false;
681 }
682 let Some(included) = load_template(views_root, name) else {
687 return false;
688 };
689 let included_bound: HashSet<String> =
690 props.iter().map(|(key, _)| key.clone()).collect();
691 tree_is_safe(&included, views_root, &included_bound)
692 }
693 Node::Live { channel, body } => {
698 expr_is_bound(channel, bound) && tree_is_safe(body, views_root, bound)
699 }
700 Node::Vitex(_) => true,
705 Node::PersistGlobal { .. } => false,
714 Node::Can { .. } | Node::Role { .. } => false,
718 Node::Spa(body) => tree_is_safe(body, views_root, bound),
725 Node::Image { props } => props.iter().all(|(_, expr)| expr_is_bound(expr, bound)),
732 }
733}
734
735fn code_block_bound_names(code: &str, bound: &HashSet<String>) -> Option<HashSet<String>> {
754 let Ok(block) = syn::parse_str::<syn::Block>(&format!("{{{code}}}")) else {
755 return None;
756 };
757 let mut scope = bound.clone();
758 let mut own_names = HashSet::new();
759 for stmt in &block.stmts {
760 match stmt {
761 syn::Stmt::Local(local) => {
762 let init = local.init.as_ref()?;
763 if init.diverge.is_some() {
764 return None; }
766 let syn::Pat::Ident(pat_ident) = &local.pat else {
767 return None; };
769 if pat_ident.by_ref.is_some() || pat_ident.subpat.is_some() {
770 return None;
771 }
772 if !expr_free_names_are_bound(&init.expr, &scope) {
773 return None;
774 }
775 let name = pat_ident.ident.to_string();
776 scope.insert(name.clone());
777 own_names.insert(name);
778 }
779 syn::Stmt::Expr(syn::Expr::Binary(bin), Some(_))
788 if matches!(
789 bin.op,
790 syn::BinOp::AddAssign(_)
791 | syn::BinOp::SubAssign(_)
792 | syn::BinOp::MulAssign(_)
793 | syn::BinOp::DivAssign(_)
794 | syn::BinOp::RemAssign(_)
795 ) =>
796 {
797 let syn::Expr::Path(path) = bin.left.as_ref() else {
798 return None;
799 };
800 if path.qself.is_some() || path.path.segments.len() != 1 {
801 return None;
802 }
803 let name = path.path.segments[0].ident.to_string();
804 if !scope.contains(&name) {
805 return None;
806 }
807 if !expr_free_names_are_bound(&bin.right, &scope) {
808 return None;
809 }
810 }
811 _ => return None,
812 }
813 }
814 Some(own_names)
815}
816
817fn pat_bound_names(pat: &syn::Pat) -> Option<HashSet<String>> {
825 match pat {
826 syn::Pat::Ident(pat_ident) if pat_ident.by_ref.is_none() && pat_ident.subpat.is_none() => {
827 Some(HashSet::from([pat_ident.ident.to_string()]))
828 }
829 syn::Pat::Tuple(tuple) => {
830 let mut names = HashSet::new();
831 for elem in &tuple.elems {
832 names.extend(pat_bound_names(elem)?);
833 }
834 Some(names)
835 }
836 _ => None,
837 }
838}
839
840fn expr_free_names_are_bound(expr: &syn::Expr, bound: &HashSet<String>) -> bool {
848 use syn::Expr;
849 match expr {
850 Expr::Lit(_) => true,
851 Expr::Path(path_expr) => {
857 if path_expr.qself.is_none() && path_expr.path.segments.len() == 1 {
858 bound.contains(&path_expr.path.segments[0].ident.to_string())
859 } else {
860 true
861 }
862 }
863 Expr::Call(call) => {
864 expr_free_names_are_bound(&call.func, bound)
865 && call
866 .args
867 .iter()
868 .all(|arg| expr_free_names_are_bound(arg, bound))
869 }
870 Expr::MethodCall(call) => {
871 expr_free_names_are_bound(&call.receiver, bound)
872 && call
873 .args
874 .iter()
875 .all(|arg| expr_free_names_are_bound(arg, bound))
876 }
877 Expr::Field(field) => expr_free_names_are_bound(&field.base, bound),
882 Expr::Array(array) => array
890 .elems
891 .iter()
892 .all(|elem| expr_free_names_are_bound(elem, bound)),
893 Expr::Binary(bin) => {
894 expr_free_names_are_bound(&bin.left, bound)
895 && expr_free_names_are_bound(&bin.right, bound)
896 }
897 Expr::Unary(un) => expr_free_names_are_bound(&un.expr, bound),
898 Expr::Reference(r) => expr_free_names_are_bound(&r.expr, bound),
899 Expr::Paren(p) => expr_free_names_are_bound(&p.expr, bound),
900 Expr::Group(g) => expr_free_names_are_bound(&g.expr, bound),
901 Expr::Cast(c) => expr_free_names_are_bound(&c.expr, bound),
902 Expr::Index(idx) => {
903 expr_free_names_are_bound(&idx.expr, bound)
904 && expr_free_names_are_bound(&idx.index, bound)
905 }
906 Expr::If(if_expr) => {
907 expr_free_names_are_bound(&if_expr.cond, bound)
908 && block_free_names_are_bound(&if_expr.then_branch, bound)
909 && if_expr
910 .else_branch
911 .as_ref()
912 .is_none_or(|(_, else_expr)| expr_free_names_are_bound(else_expr, bound))
913 }
914 Expr::Block(b) => block_free_names_are_bound(&b.block, bound),
915 Expr::Macro(m) => {
919 if !m.mac.path.is_ident("format") {
920 return false;
921 }
922 let Ok(args) = m.mac.parse_body_with(
923 syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated,
924 ) else {
925 return false;
926 };
927 args.iter().all(|arg| expr_free_names_are_bound(arg, bound))
928 }
929 Expr::Closure(closure) => {
934 if closure.inputs.len() > 1 {
935 return false;
936 }
937 let mut scope = bound.clone();
938 if let Some(input) = closure.inputs.first() {
939 let syn::Pat::Ident(pat_ident) = input else {
940 return false;
941 };
942 scope.insert(pat_ident.ident.to_string());
943 }
944 expr_free_names_are_bound(&closure.body, &scope)
945 }
946 _ => false,
947 }
948}
949
950fn block_free_names_are_bound(block: &syn::Block, bound: &HashSet<String>) -> bool {
956 block.stmts.iter().all(|stmt| match stmt {
957 syn::Stmt::Expr(expr, _) => expr_free_names_are_bound(expr, bound),
958 _ => false,
959 })
960}
961
962#[cfg(test)]
963mod tests {
964 use super::*;
965
966 #[test]
967 fn extracts_public_properties_with_literal_defaults() {
968 let source = "<?php\nclass Home extends Component {\n public $title = \"Hello\";\n public $banner = true;\n public $count = 5;\n}\n";
969 let result = convert(source, "Home").unwrap();
970 assert_eq!(result.properties.len(), 3);
971 let title = result
972 .properties
973 .iter()
974 .find(|p| p.name == "title")
975 .unwrap();
976 assert_eq!(title.rust_type, "String");
977 assert_eq!(title.default_literal, "\"Hello\".to_string()");
978 let banner = result
979 .properties
980 .iter()
981 .find(|p| p.name == "banner")
982 .unwrap();
983 assert_eq!(banner.rust_type, "bool");
984 assert_eq!(banner.default_literal, "true");
985 let count = result
986 .properties
987 .iter()
988 .find(|p| p.name == "count")
989 .unwrap();
990 assert_eq!(count.rust_type, "i64");
991 assert_eq!(count.default_literal, "5");
992 assert!(result.unsupported_properties.is_empty());
993 }
994
995 #[test]
996 fn an_empty_double_quoted_string_default_is_a_supported_literal() {
997 let source = r#"<?php
1002class Home extends Component {
1003 public $canonical = "";
1004}
1005"#;
1006 let result = convert(source, "Home").unwrap();
1007 assert!(result.unsupported_properties.is_empty());
1008 assert_eq!(result.properties.len(), 1);
1009 assert_eq!(result.properties[0].rust_type, "String");
1010 assert_eq!(result.properties[0].default_literal, "\"\".to_string()");
1011 }
1012
1013 #[test]
1014 fn protected_and_private_properties_are_never_exposed() {
1015 let source = "<?php\nclass Home extends Component {\n protected $guard = 'web';\n private $secret = 'x';\n public $title = \"Hello\";\n}\n";
1016 let result = convert(source, "Home").unwrap();
1017 assert_eq!(result.properties.len(), 1);
1018 assert_eq!(result.properties[0].name, "title");
1019 }
1020
1021 #[test]
1022 fn an_interpolated_double_quoted_string_is_flagged_not_guessed() {
1023 let source = r#"<?php
1024class Home extends Component {
1025 public $greeting = "Hello {$name}";
1026}
1027"#;
1028 let result = convert(source, "Home").unwrap();
1029 assert!(result.properties.is_empty());
1030 assert_eq!(result.unsupported_properties.len(), 1);
1031 assert!(result.unsupported_properties[0].contains("greeting"));
1032 }
1033
1034 #[test]
1035 fn a_property_with_no_default_is_flagged_not_guessed() {
1036 let source = "<?php\nclass Home extends Component {\n public $current;\n}\n";
1037 let result = convert(source, "Home").unwrap();
1038 assert!(result.properties.is_empty());
1039 assert_eq!(result.unsupported_properties.len(), 1);
1040 assert!(result.unsupported_properties[0].contains("current"));
1041 }
1042
1043 #[test]
1044 fn a_non_literal_default_is_flagged_not_guessed() {
1045 let source = "<?php\nclass Home extends Component {\n public $items = [1, 2, 3];\n}\n";
1046 let result = convert(source, "Home").unwrap();
1047 assert!(result.properties.is_empty());
1048 assert_eq!(result.unsupported_properties.len(), 1);
1049 assert!(result.unsupported_properties[0].contains("items"));
1050 }
1051
1052 #[test]
1053 fn extracts_the_view_name_from_a_plain_render_return() {
1054 let source = "<?php\nclass Home extends Component {\n public function render()\n {\n return view('livewire.pages.index');\n }\n}\n";
1055 let result = convert(source, "Home").unwrap();
1056 assert_eq!(result.view_name.as_deref(), Some("livewire.pages.index"));
1057 assert!(result.layout_name.is_none());
1058 }
1059
1060 #[test]
1061 fn extracts_the_view_name_through_a_chained_layout_call() {
1062 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";
1064 let result = convert(source, "Home").unwrap();
1065 assert_eq!(result.view_name.as_deref(), Some("livewire.pages.index"));
1066 assert_eq!(
1067 result.layout_name.as_deref(),
1068 Some("components.layouts.app")
1069 );
1070 }
1071
1072 #[test]
1073 fn no_render_method_means_no_view_name() {
1074 let source = "<?php\nclass Home extends Component {\n}\n";
1075 let result = convert(source, "Home").unwrap();
1076 assert!(result.view_name.is_none());
1077 }
1078
1079 #[test]
1080 fn rejects_when_the_class_is_not_found_in_the_file() {
1081 let source = "<?php\nclass Other extends Component {}\n";
1082 assert!(convert(source, "Home").is_err());
1083 }
1084
1085 fn write_view(dir: &std::path::Path, dotted_name: &str, content: &str) {
1086 let path = dir.join(dotted_name.replace('.', "/") + ".blade.xr");
1087 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1088 std::fs::write(path, content).unwrap();
1089 }
1090
1091 #[test]
1092 fn a_template_with_only_bound_interpolations_is_safe() {
1093 let dir = tempfile::tempdir().unwrap();
1094 write_view(
1095 dir.path(),
1096 "pages.index",
1097 "<h1>{{ title }}</h1><p>{{ query }}</p>",
1098 );
1099 let bound = HashSet::from(["title".to_string(), "query".to_string()]);
1100 assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1101 }
1102
1103 #[test]
1104 fn layout_globals_for_finds_only_the_names_actually_referenced() {
1105 let dir = tempfile::tempdir().unwrap();
1110 write_view(
1111 dir.path(),
1112 "layouts.app",
1113 r#"<html class="{{ theme }}"><meta name="csrf-token" content="{{ csrf_token }}"><body>{{ slot }}</body></html>"#,
1114 );
1115 let bound = HashSet::from(["slot".to_string()]);
1116 let globals = layout_globals_for(dir.path(), "layouts.app", &bound).unwrap();
1117 let names: HashSet<&str> = globals.iter().map(|g| g.name).collect();
1118 assert_eq!(names, HashSet::from(["theme", "csrf_token"]));
1119 }
1120
1121 #[test]
1122 fn layout_globals_for_finds_nothing_when_the_layout_uses_neither_known_global() {
1123 let dir = tempfile::tempdir().unwrap();
1124 write_view(dir.path(), "layouts.app", "<body>{{ slot }}</body>");
1125 let bound = HashSet::from(["slot".to_string()]);
1126 let globals = layout_globals_for(dir.path(), "layouts.app", &bound).unwrap();
1127 assert!(globals.is_empty());
1128 }
1129
1130 #[test]
1131 fn layout_globals_for_is_none_when_an_unrelated_name_stays_unbound() {
1132 let dir = tempfile::tempdir().unwrap();
1133 write_view(
1134 dir.path(),
1135 "layouts.app",
1136 "<body>{{ slot }}{{ theme }}{{ subtitle }}</body>",
1137 );
1138 let bound = HashSet::from(["slot".to_string()]);
1139 assert!(layout_globals_for(dir.path(), "layouts.app", &bound).is_none());
1140 }
1141
1142 #[test]
1143 fn referenced_names_finds_only_the_candidates_the_template_actually_mentions() {
1144 let dir = tempfile::tempdir().unwrap();
1148 write_view(
1149 dir.path(),
1150 "layouts.app",
1151 r#"<html class="{{ theme }}"><body>{{ slot }}</body></html>"#,
1152 );
1153 let candidates: HashSet<String> = ["theme", "slot", "title", "url", "canonical"]
1154 .into_iter()
1155 .map(String::from)
1156 .collect();
1157 let found =
1158 referenced_names(dir.path(), "layouts.app", &HashSet::new(), &candidates).unwrap();
1159 assert_eq!(
1160 found,
1161 HashSet::from(["theme".to_string(), "slot".to_string()])
1162 );
1163 }
1164
1165 #[test]
1166 fn a_bare_word_that_only_appears_as_a_substring_of_another_identifier_is_not_referenced() {
1167 let dir = tempfile::tempdir().unwrap();
1174 write_view(
1175 dir.path(),
1176 "layouts.app",
1177 "<meta name=\"mytheme-title\"><body>{{ slot }}</body>",
1178 );
1179 let bound = HashSet::from(["slot".to_string()]);
1180 let globals = layout_globals_for(dir.path(), "layouts.app", &bound).unwrap();
1181 assert!(globals.is_empty());
1182 }
1183
1184 #[test]
1185 fn an_unbound_interpolation_is_unsafe() {
1186 let dir = tempfile::tempdir().unwrap();
1187 write_view(dir.path(), "pages.index", "<h1>{{ subtitle }}</h1>");
1188 let bound = HashSet::from(["title".to_string()]);
1189 assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1190 }
1191
1192 #[test]
1193 fn a_top_level_wire_tag_is_unsafe() {
1194 let dir = tempfile::tempdir().unwrap();
1195 write_view(
1196 dir.path(),
1197 "pages.index",
1198 "<wire:search-box :query='query' />",
1199 );
1200 let bound = HashSet::from(["query".to_string()]);
1201 assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1202 }
1203
1204 #[test]
1205 fn a_resource_include_with_no_wire_or_csrf_inside_is_safe() {
1206 let dir = tempfile::tempdir().unwrap();
1207 write_view(
1208 dir.path(),
1209 "pages.index",
1210 "<resource:components.head :title='title'></resource:components.head>",
1211 );
1212 write_view(dir.path(), "components.head", "<title>{{ title }}</title>");
1213 let bound = HashSet::from(["title".to_string()]);
1214 assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1215 }
1216
1217 #[test]
1218 fn a_resource_include_that_transitively_uses_wire_is_unsafe() {
1219 let dir = tempfile::tempdir().unwrap();
1228 write_view(
1229 dir.path(),
1230 "pages.index",
1231 "<resource:components.navbar></resource:components.navbar>",
1232 );
1233 write_view(dir.path(), "components.navbar", "<wire:search-box />");
1234 let bound: HashSet<String> = HashSet::new();
1235 assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1236 }
1237
1238 #[test]
1239 fn a_foreach_over_a_bound_iterable_referencing_its_own_binding_is_safe() {
1240 let dir = tempfile::tempdir().unwrap();
1244 write_view(
1245 dir.path(),
1246 "pages.index",
1247 "@foreach(item in itemlist)<p>{{ item }}</p>@endforeach",
1248 );
1249 let bound = HashSet::from(["itemlist".to_string()]);
1250 assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1251 }
1252
1253 #[test]
1254 fn a_foreach_over_an_unbound_iterable_is_unsafe() {
1255 let dir = tempfile::tempdir().unwrap();
1256 write_view(
1257 dir.path(),
1258 "pages.index",
1259 "@foreach(item in itemlist)<p>{{ item }}</p>@endforeach",
1260 );
1261 let bound: HashSet<String> = HashSet::new();
1262 assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1263 }
1264
1265 #[test]
1266 fn a_foreach_body_referencing_a_name_outside_the_binding_and_outer_scope_is_unsafe() {
1267 let dir = tempfile::tempdir().unwrap();
1268 write_view(
1269 dir.path(),
1270 "pages.index",
1271 "@foreach(item in itemlist)<p>{{ subtitle }}</p>@endforeach",
1272 );
1273 let bound = HashSet::from(["itemlist".to_string()]);
1274 assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1275 }
1276
1277 #[test]
1278 fn a_keyed_with_loop_foreach_binds_both_tuple_names_and_the_loop_variable() {
1279 let dir = tempfile::tempdir().unwrap();
1286 write_view(
1287 dir.path(),
1288 "pages.index",
1289 "@foreach(((key, item), loop_) in larust_support::WithLoop::with_loop((items).iter().enumerate()))\
1290 {{ if larust_support::truthy::truthy(&(!(loop_.last))) { (\",\").to_string() } else { (\"\").to_string() } }}\
1291 @endforeach",
1292 );
1293 let bound = HashSet::from(["items".to_string()]);
1294 assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1295 }
1296
1297 #[test]
1298 fn a_resource_props_own_expression_must_also_be_bound() {
1299 let dir = tempfile::tempdir().unwrap();
1300 write_view(
1301 dir.path(),
1302 "pages.index",
1303 "<resource:components.head :title='unbound_name'></resource:components.head>",
1304 );
1305 write_view(dir.path(), "components.head", "<title>{{ title }}</title>");
1306 let bound: HashSet<String> = HashSet::new();
1307 assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1308 }
1309
1310 #[test]
1311 fn a_missing_template_is_unsafe() {
1312 let dir = tempfile::tempdir().unwrap();
1313 let bound: HashSet<String> = HashSet::new();
1314 assert!(!view_is_safe_for_scope(dir.path(), "pages.missing", &bound));
1315 }
1316
1317 #[test]
1318 fn a_csrf_directive_is_unsafe() {
1319 let dir = tempfile::tempdir().unwrap();
1320 write_view(dir.path(), "pages.form", "<form>@csrf</form>");
1321 let bound: HashSet<String> = HashSet::new();
1322 assert!(!view_is_safe_for_scope(dir.path(), "pages.form", &bound));
1323 }
1324
1325 #[test]
1326 fn a_can_directive_is_unsafe() {
1327 let dir = tempfile::tempdir().unwrap();
1331 write_view(
1332 dir.path(),
1333 "pages.editable",
1334 "@can(Permission::EditPosts)yes@endcan",
1335 );
1336 let bound: HashSet<String> = HashSet::new();
1337 assert!(!view_is_safe_for_scope(
1338 dir.path(),
1339 "pages.editable",
1340 &bound
1341 ));
1342 }
1343
1344 #[test]
1345 fn a_role_directive_is_unsafe() {
1346 let dir = tempfile::tempdir().unwrap();
1347 write_view(dir.path(), "pages.admin", "@role(Role::Admin)yes@endrole");
1348 let bound: HashSet<String> = HashSet::new();
1349 assert!(!view_is_safe_for_scope(dir.path(), "pages.admin", &bound));
1350 }
1351
1352 #[test]
1353 fn a_spa_directive_with_a_safe_body_is_safe() {
1354 let dir = tempfile::tempdir().unwrap();
1359 write_view(dir.path(), "pages.home", "@spa <p>hi</p> @endspa");
1360 let bound: HashSet<String> = HashSet::new();
1361 assert!(view_is_safe_for_scope(dir.path(), "pages.home", &bound));
1362 }
1363
1364 #[test]
1365 fn a_spa_directive_wrapping_an_unsafe_node_is_still_unsafe() {
1366 let dir = tempfile::tempdir().unwrap();
1367 write_view(dir.path(), "pages.home", "@spa @csrf @endspa");
1368 let bound: HashSet<String> = HashSet::new();
1369 assert!(!view_is_safe_for_scope(dir.path(), "pages.home", &bound));
1370 }
1371
1372 #[test]
1373 fn a_code_block_with_only_literal_lets_is_safe() {
1374 let dir = tempfile::tempdir().unwrap();
1376 write_view(
1377 dir.path(),
1378 "errors.404",
1379 "@code let mut title = \"Page Not Found\"; let mut noindex = true; @endcode<h1>{{ title }}</h1>",
1380 );
1381 let bound: HashSet<String> = HashSet::new();
1382 assert!(view_is_safe_for_scope(dir.path(), "errors.404", &bound));
1383 }
1384
1385 #[test]
1386 fn a_code_blocks_own_bindings_are_visible_to_later_siblings() {
1387 let dir = tempfile::tempdir().unwrap();
1388 write_view(
1389 dir.path(),
1390 "pages.index",
1391 "@code let mut greeting = \"hi\"; @endcode<p>{{ greeting }}</p>",
1392 );
1393 let bound: HashSet<String> = HashSet::new();
1394 assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1395 }
1396
1397 #[test]
1398 fn a_code_block_referencing_an_unbound_name_is_unsafe() {
1399 let dir = tempfile::tempdir().unwrap();
1400 write_view(
1401 dir.path(),
1402 "pages.index",
1403 "@code let mut greeting = format!(\"hi {}\", session); @endcode",
1404 );
1405 let bound: HashSet<String> = HashSet::new();
1406 assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1407 }
1408
1409 #[test]
1410 fn a_code_block_incrementing_an_already_bound_counter_is_safe() {
1411 let dir = tempfile::tempdir().unwrap();
1416 write_view(
1417 dir.path(),
1418 "pages.index",
1419 "@code let mut x = 0; @endcode@code x += 1; @endcode{{ x }}",
1420 );
1421 let bound: HashSet<String> = HashSet::new();
1422 assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1423 }
1424
1425 #[test]
1426 fn a_compound_assignment_to_an_unbound_name_is_unsafe() {
1427 let dir = tempfile::tempdir().unwrap();
1428 write_view(dir.path(), "pages.index", "@code x += 1; @endcode");
1429 let bound: HashSet<String> = HashSet::new();
1430 assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1431 }
1432
1433 #[test]
1434 fn a_compound_assignment_referencing_an_unbound_name_on_the_right_is_unsafe() {
1435 let dir = tempfile::tempdir().unwrap();
1436 write_view(
1437 dir.path(),
1438 "pages.index",
1439 "@code let mut x = 0; x += unbound_step; @endcode",
1440 );
1441 let bound: HashSet<String> = HashSet::new();
1442 assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1443 }
1444
1445 #[test]
1446 fn a_code_block_matching_the_real_head_component_shape_is_safe() {
1447 let dir = tempfile::tempdir().unwrap();
1452 write_view(
1453 dir.path(),
1454 "components.head",
1455 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 }}" />"#,
1456 );
1457 let bound = HashSet::from(["canonical".to_string()]);
1458 assert!(view_is_safe_for_scope(
1459 dir.path(),
1460 "components.head",
1461 &bound
1462 ));
1463 }
1464
1465 #[test]
1466 fn a_code_block_calling_vitex_tags_with_an_array_literal_is_safe() {
1467 let dir = tempfile::tempdir().unwrap();
1474 write_view(
1475 dir.path(),
1476 "layouts.app",
1477 r#"@code let __vitex_tags = larust_support::vitex::tags(&["resources/css/app.min.css", "resources/js/app.min.js"]); @endcode{!! __vitex_tags !!}"#,
1478 );
1479 assert!(view_is_safe_for_scope(
1480 dir.path(),
1481 "layouts.app",
1482 &HashSet::new()
1483 ));
1484 }
1485
1486 #[test]
1487 fn a_code_block_with_a_bound_single_param_closure_is_safe() {
1488 let dir = tempfile::tempdir().unwrap();
1491 write_view(
1492 dir.path(),
1493 "pages.index",
1494 r#"@code let mut keys = (keywords).split(",").map(|s| s.to_string()).collect::<Vec<String>>(); @endcode"#,
1495 );
1496 let bound = HashSet::from(["keywords".to_string()]);
1497 assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1498 }
1499
1500 #[test]
1501 fn a_code_block_with_a_bare_expression_statement_is_unsafe() {
1502 let dir = tempfile::tempdir().unwrap();
1509 write_view(
1510 dir.path(),
1511 "pages.index",
1512 "@code let mut x = 0; x.clear(); @endcode",
1513 );
1514 let bound: HashSet<String> = HashSet::new();
1515 assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1516 }
1517
1518 #[test]
1519 fn a_code_block_destructuring_a_pattern_is_unsafe() {
1520 let dir = tempfile::tempdir().unwrap();
1521 write_view(
1522 dir.path(),
1523 "pages.index",
1524 "@code let (a, b) = (1, 2); @endcode",
1525 );
1526 let bound: HashSet<String> = HashSet::new();
1527 assert!(!view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1528 }
1529
1530 #[test]
1531 fn a_code_block_indexing_a_bound_value_is_safe() {
1532 let dir = tempfile::tempdir().unwrap();
1535 write_view(
1536 dir.path(),
1537 "pages.index",
1538 r#"@code let mut body = (data["bodytext"]).replace("a", "b"); @endcode"#,
1539 );
1540 let bound = HashSet::from(["data".to_string()]);
1541 assert!(view_is_safe_for_scope(dir.path(), "pages.index", &bound));
1542 }
1543
1544 #[test]
1545 fn an_interpolation_containing_a_full_if_else_expression_is_safe_when_bound() {
1546 let dir = tempfile::tempdir().unwrap();
1554 write_view(
1555 dir.path(),
1556 "components.navbar",
1557 r#"<nav class="{{ if larust_support::truthy::truthy(&(banner)) { "" } else { "sticky-nav" } }}"></nav>"#,
1558 );
1559 let bound = HashSet::from(["banner".to_string()]);
1560 assert!(view_is_safe_for_scope(
1561 dir.path(),
1562 "components.navbar",
1563 &bound
1564 ));
1565 }
1566
1567 #[test]
1568 fn an_interpolation_with_a_method_chain_on_a_bound_value_is_safe() {
1569 let dir = tempfile::tempdir().unwrap();
1571 write_view(
1572 dir.path(),
1573 "components.navbar",
1574 r#"<a class="{{ if (current).contains(&("home")) { "active" } else { "" } }}">Home</a>"#,
1575 );
1576 let bound = HashSet::from(["current".to_string()]);
1577 assert!(view_is_safe_for_scope(
1578 dir.path(),
1579 "components.navbar",
1580 &bound
1581 ));
1582 }
1583
1584 #[test]
1585 fn head_pushes_finds_a_push_in_the_content_template_itself() {
1586 let dir = tempfile::tempdir().unwrap();
1587 write_view(
1588 dir.path(),
1589 "pages.contact",
1590 "@push('head')<link rel=\"stylesheet\" href=\"/css/text.min.css\">@endpush<div>hi</div>",
1591 );
1592 let pushes = head_pushes(dir.path(), "pages.contact");
1593 assert_eq!(pushes.len(), 1);
1594 assert_eq!(
1595 pushes[0].text.as_deref(),
1596 Some("<link rel=\"stylesheet\" href=\"/css/text.min.css\">")
1597 );
1598 }
1599
1600 #[test]
1601 fn head_pushes_reaches_through_a_nested_resource_tag() {
1602 let dir = tempfile::tempdir().unwrap();
1606 write_view(
1607 dir.path(),
1608 "elements.sunrise",
1609 "@push('head')<link rel=\"stylesheet\" href=\"/css/sunrise.min.css\">@endpush<div>sun</div>",
1610 );
1611 write_view(
1612 dir.path(),
1613 "pages.index",
1614 "<resource:elements.sunrise></resource:elements.sunrise>",
1615 );
1616 let pushes = head_pushes(dir.path(), "pages.index");
1617 assert_eq!(pushes.len(), 1);
1618 assert_eq!(
1619 pushes[0].text.as_deref(),
1620 Some("<link rel=\"stylesheet\" href=\"/css/sunrise.min.css\">")
1621 );
1622 }
1623
1624 #[test]
1625 fn head_pushes_with_dynamic_content_are_reported_as_unhoistable() {
1626 let dir = tempfile::tempdir().unwrap();
1627 write_view(
1628 dir.path(),
1629 "pages.contact",
1630 "@push('head')<title>{{ title }}</title>@endpush",
1631 );
1632 let pushes = head_pushes(dir.path(), "pages.contact");
1633 assert_eq!(pushes.len(), 1);
1634 assert!(pushes[0].text.is_none());
1635 }
1636
1637 #[test]
1638 fn head_pushes_does_not_duplicate_a_resource_included_more_than_once() {
1639 let dir = tempfile::tempdir().unwrap();
1640 write_view(
1641 dir.path(),
1642 "elements.questions",
1643 "@push('head')<link rel=\"stylesheet\" href=\"/css/questions.min.css\">@endpush",
1644 );
1645 write_view(
1646 dir.path(),
1647 "pages.contact",
1648 "<resource:elements.questions></resource:elements.questions>\
1649 <resource:elements.questions></resource:elements.questions>",
1650 );
1651 let pushes = head_pushes(dir.path(), "pages.contact");
1652 assert_eq!(pushes.len(), 1);
1653 }
1654
1655 #[test]
1656 fn head_pushes_for_a_missing_template_is_empty_not_an_error() {
1657 let dir = tempfile::tempdir().unwrap();
1658 assert!(head_pushes(dir.path(), "pages.nonexistent").is_empty());
1659 }
1660}