Skip to main content

nenjo_xml/
template.rs

1//! Generic template rendering using MiniJinja.
2//!
3//! Supports Jinja2 syntax: `{{ variable }}`, `{% if %}`, `{% for %}`, filters.
4//! Template variables are provided as a flat `HashMap<String, String>` with
5//! dotted keys (e.g. `"document.id"`, `"profile.name"`). The tree builder groups
6//! these into nested MiniJinja access: `{{ document.id }}`, `{{ profile.name }}`.
7//!
8//! When a node has its own value AND children, the node's value is used for
9//! direct rendering (`{{ profile }}`), while children are still accessible
10//! (`{{ profile.id }}`). This enables the pattern where singular keys render
11//! full XML and dotted keys render individual fields.
12
13use std::collections::{BTreeMap, HashMap};
14
15use minijinja::{Environment, Value};
16use tracing::warn;
17
18/// Error type for template rendering failures.
19#[derive(Debug, thiserror::Error)]
20#[error("template render failed: {message}")]
21pub struct TemplateError {
22    pub message: String,
23    pub detail: String,
24}
25
26/// Render a template with the provided variables.
27///
28/// Variables are a flat `HashMap<String, String>` with dotted keys that get
29/// built into a nested tree for Jinja2 access. Falls back to returning the
30/// original template if rendering fails.
31///
32/// # Examples
33///
34/// ```
35/// use std::collections::HashMap;
36/// use nenjo_xml::template::render_template;
37///
38/// let mut vars = HashMap::new();
39/// vars.insert("profile.name".into(), "coder".into());
40/// vars.insert("document.title".into(), "Fix bug".into());
41///
42/// let result = render_template("{{ profile.name }}: {{ document.title }}", &vars);
43/// assert_eq!(result, "coder: Fix bug");
44/// ```
45pub fn render_template(template: &str, vars: &HashMap<String, String>) -> String {
46    match try_render_template(template, vars) {
47        Ok(rendered) => rendered,
48        Err(e) => {
49            warn!(
50                error = %e.message,
51                detail = %e.detail,
52                "MiniJinja render failed, returning original template"
53            );
54            template.to_string()
55        }
56    }
57}
58
59/// Like [`render_template`] but returns an error on failure instead of
60/// falling back to the original template.
61pub fn try_render_template(
62    template: &str,
63    vars: &HashMap<String, String>,
64) -> Result<String, TemplateError> {
65    try_render_template_with_undefined_behavior(
66        template,
67        vars,
68        minijinja::UndefinedBehavior::Chainable,
69    )
70}
71
72/// Like [`try_render_template`] but errors when a template references a
73/// variable that is not present in the render context.
74pub fn try_render_template_strict(
75    template: &str,
76    vars: &HashMap<String, String>,
77) -> Result<String, TemplateError> {
78    try_render_template_with_undefined_behavior(
79        template,
80        vars,
81        minijinja::UndefinedBehavior::Strict,
82    )
83}
84
85fn try_render_template_with_undefined_behavior(
86    template: &str,
87    vars: &HashMap<String, String>,
88    undefined_behavior: minijinja::UndefinedBehavior,
89) -> Result<String, TemplateError> {
90    if template.is_empty() {
91        return Ok(String::new());
92    }
93
94    let template = &escape_backslash_braces(template);
95    let context_value = vars_to_value(vars);
96
97    let mut env = Environment::new();
98    env.set_auto_escape_callback(|_| minijinja::AutoEscape::None);
99    env.set_undefined_behavior(undefined_behavior);
100
101    env.render_str(template, &context_value)
102        .map_err(|e| TemplateError {
103            message: e.to_string(),
104            detail: e.display_debug_info().to_string(),
105        })
106}
107
108/// Render a template with additional named templates registered in the same
109/// MiniJinja environment.
110///
111/// This is used for context-block composition where prompts can include named
112/// context block templates with MiniJinja's native `{% include %}` mechanism.
113pub fn render_template_with_named_templates(
114    template: &str,
115    vars: &HashMap<String, String>,
116    named_templates: &HashMap<String, String>,
117) -> String {
118    match try_render_template_with_named_templates(template, vars, named_templates) {
119        Ok(rendered) => rendered,
120        Err(e) => {
121            warn!(
122                error = %e.message,
123                detail = %e.detail,
124                "MiniJinja render failed, returning original template"
125            );
126            template.to_string()
127        }
128    }
129}
130
131/// Like [`render_template_with_named_templates`] but returns an error on
132/// failure instead of falling back to the original template.
133pub fn try_render_template_with_named_templates(
134    template: &str,
135    vars: &HashMap<String, String>,
136    named_templates: &HashMap<String, String>,
137) -> Result<String, TemplateError> {
138    try_render_template_with_named_templates_and_undefined_behavior(
139        template,
140        vars,
141        named_templates,
142        minijinja::UndefinedBehavior::Chainable,
143    )
144}
145
146/// Like [`try_render_template_with_named_templates`] but errors when a template
147/// references a variable that is not present in the render context.
148pub fn try_render_template_with_named_templates_strict(
149    template: &str,
150    vars: &HashMap<String, String>,
151    named_templates: &HashMap<String, String>,
152) -> Result<String, TemplateError> {
153    try_render_template_with_named_templates_and_undefined_behavior(
154        template,
155        vars,
156        named_templates,
157        minijinja::UndefinedBehavior::Strict,
158    )
159}
160
161fn try_render_template_with_named_templates_and_undefined_behavior(
162    template: &str,
163    vars: &HashMap<String, String>,
164    named_templates: &HashMap<String, String>,
165    undefined_behavior: minijinja::UndefinedBehavior,
166) -> Result<String, TemplateError> {
167    if template.is_empty() {
168        return Ok(String::new());
169    }
170
171    let template = &escape_backslash_braces(template);
172    let context_value = vars_to_value(vars);
173
174    let mut env = Environment::new();
175    env.set_auto_escape_callback(|_| minijinja::AutoEscape::None);
176    env.set_undefined_behavior(undefined_behavior);
177
178    for (name, source) in named_templates {
179        env.add_template_owned(name.clone(), escape_backslash_braces(source))
180            .map_err(|e| TemplateError {
181                message: e.to_string(),
182                detail: e.display_debug_info().to_string(),
183            })?;
184    }
185
186    env.render_str(template, &context_value)
187        .map_err(|e| TemplateError {
188            message: e.to_string(),
189            detail: e.display_debug_info().to_string(),
190        })
191}
192
193// ---------------------------------------------------------------------------
194// Backslash escape pre-processing
195// ---------------------------------------------------------------------------
196
197/// Convert `\{{` and `\{%` sequences into MiniJinja raw blocks so that
198/// backslash works as an escape character for template delimiters.
199///
200/// - `\{{`  → literal `{{` (escape prevents variable interpolation)
201/// - `\{%`  → literal `{%` (escape prevents block tag interpretation)
202/// - `\\{{` → literal `\` + variable interpolation (escaped backslash)
203/// - `\\{%` → literal `\` + block tag interpretation (escaped backslash)
204fn escape_backslash_braces(template: &str) -> String {
205    let mut result = String::with_capacity(template.len());
206    let mut chars = template.chars().peekable();
207
208    while let Some(c) = chars.next() {
209        if c == '\\' {
210            match (chars.peek().copied(), chars.clone().nth(1)) {
211                // \\  → consume both, emit one literal backslash.
212                (Some('\\'), _) => {
213                    chars.next();
214                    result.push('\\');
215                }
216                // \{{ → emit a raw block that outputs literal {{
217                (Some('{'), Some('{')) => {
218                    chars.next();
219                    chars.next();
220                    result.push_str("{% raw %}{{{% endraw %}");
221                }
222                // \{% → emit a raw block that outputs literal {%
223                (Some('{'), Some('%')) => {
224                    chars.next();
225                    chars.next();
226                    result.push_str("{% raw %}{%{% endraw %}");
227                }
228                // Lone backslash — pass through.
229                _ => result.push('\\'),
230            }
231        } else {
232            result.push(c);
233        }
234    }
235
236    result
237}
238
239// ---------------------------------------------------------------------------
240// Tree builder: HashMap<String, String> → nested MiniJinja Value
241// ---------------------------------------------------------------------------
242
243/// Build a nested MiniJinja `Value` tree from a flat `HashMap<String, String>`
244/// with dotted keys.
245///
246/// When a node has its own leaf value AND children, the leaf value is used
247/// for direct rendering (e.g. `{{ profile }}`), while children remain accessible
248/// (e.g. `{{ profile.id }}`). Nodes without their own value render as the
249/// concatenation of all descendant leaf values.
250///
251/// # Examples
252///
253/// ```text
254/// Input:
255///   "profile"      → "<profile id='1' name='coder'/>"
256///   "profile.id"   → "1"
257///   "profile.name" → "coder"
258///   "profiles"     → "<profile .../><profile .../>"
259///
260/// Template access:
261///   {{ profile }}       → "<profile id='1' name='coder'/>"
262///   {{ profile.id }}    → "1"
263///   {{ profile.name }}  → "coder"
264///   {{ profiles }}      → "<profile .../><profile .../>"
265/// ```
266pub fn vars_to_value(vars: &HashMap<String, String>) -> Value {
267    if vars.is_empty() {
268        return Value::from(BTreeMap::<String, Value>::new());
269    }
270
271    let mut root = TreeNode::default();
272    for (key, value) in vars {
273        let parts: Vec<&str> = key.split('.').collect();
274        root.insert(&parts, value);
275    }
276
277    if root.children.is_empty() {
278        Value::from(BTreeMap::<String, Value>::new())
279    } else {
280        root.to_value()
281    }
282}
283
284#[derive(Default)]
285struct TreeNode {
286    children: BTreeMap<String, TreeNode>,
287    leaf_value: Option<String>,
288}
289
290impl TreeNode {
291    fn insert(&mut self, parts: &[&str], value: &str) {
292        if parts.is_empty() {
293            return;
294        }
295        if parts.len() == 1 {
296            let child = self.children.entry(parts[0].to_string()).or_default();
297            child.leaf_value = Some(value.to_string());
298        } else {
299            let child = self.children.entry(parts[0].to_string()).or_default();
300            child.insert(&parts[1..], value);
301        }
302    }
303
304    /// Collect all leaf values from descendants only (NOT this node's own value).
305    fn collect_descendant_leaves(&self) -> Vec<String> {
306        let mut leaves = Vec::new();
307        for child in self.children.values() {
308            if let Some(ref v) = child.leaf_value {
309                leaves.push(v.clone());
310            }
311            leaves.extend(child.collect_descendant_leaves());
312        }
313        leaves
314    }
315
316    fn to_value(&self) -> Value {
317        if self.children.is_empty() {
318            return Value::from(self.leaf_value.as_deref().unwrap_or(""));
319        }
320
321        let mut map = BTreeMap::new();
322        for (key, child) in &self.children {
323            map.insert(key.clone(), child.to_value());
324        }
325
326        // When this node has its own leaf value, use it for rendering.
327        // Otherwise, concatenate all descendant leaves.
328        let group_value = if let Some(ref v) = self.leaf_value {
329            v.clone()
330        } else {
331            self.collect_descendant_leaves().join("\n\n")
332        };
333
334        Value::from_object(GroupNode {
335            group_value,
336            children: map,
337        })
338    }
339}
340
341#[derive(Debug)]
342struct GroupNode {
343    group_value: String,
344    children: BTreeMap<String, Value>,
345}
346
347impl std::fmt::Display for GroupNode {
348    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
349        f.write_str(&self.group_value)
350    }
351}
352
353impl minijinja::value::Object for GroupNode {
354    fn get_value(self: &std::sync::Arc<Self>, key: &Value) -> Option<Value> {
355        let key_str = key.as_str()?;
356        self.children.get(key_str).cloned()
357    }
358
359    fn enumerate(self: &std::sync::Arc<Self>) -> minijinja::value::Enumerator {
360        minijinja::value::Enumerator::Iter(Box::new(
361            self.children
362                .keys()
363                .cloned()
364                .map(Value::from)
365                .collect::<Vec<_>>()
366                .into_iter(),
367        ))
368    }
369
370    fn render(
371        self: &std::sync::Arc<Self>,
372        f: &mut std::fmt::Formatter<'_>,
373    ) -> Result<(), std::fmt::Error> {
374        f.write_str(&self.group_value)
375    }
376}
377
378#[cfg(test)]
379mod tests {
380    use super::*;
381
382    fn vars(pairs: &[(&str, &str)]) -> HashMap<String, String> {
383        pairs
384            .iter()
385            .map(|(k, v)| (k.to_string(), v.to_string()))
386            .collect()
387    }
388
389    #[test]
390    fn render_basic_variables() {
391        let v = vars(&[("profile.name", "dev"), ("project.name", "MyProject")]);
392        let result = render_template("Profile {{ profile.name }} in {{ project.name }}", &v);
393        assert_eq!(result, "Profile dev in MyProject");
394    }
395
396    #[test]
397    fn render_dotted_keys_as_tree() {
398        let v = vars(&[
399            ("task.id", "TASK-42"),
400            ("task.title", "Fix bug"),
401            ("profile.name", "coder"),
402        ]);
403        assert_eq!(render_template("{{ task.id }}", &v), "TASK-42");
404        assert_eq!(render_template("{{ task.title }}", &v), "Fix bug");
405        assert_eq!(render_template("{{ profile.name }}", &v), "coder");
406    }
407
408    #[test]
409    fn render_singular_with_own_value_and_children() {
410        let v = vars(&[
411            ("profile", "<profile id=\"1\" name=\"coder\"/>"),
412            ("profile.id", "1"),
413            ("profile.name", "coder"),
414        ]);
415        // The root renders its own value rather than concatenating its children.
416        assert_eq!(
417            render_template("{{ profile }}", &v),
418            "<profile id=\"1\" name=\"coder\"/>"
419        );
420        assert_eq!(render_template("{{ profile.id }}", &v), "1");
421        assert_eq!(render_template("{{ profile.name }}", &v), "coder");
422    }
423
424    #[test]
425    fn render_group_without_own_value_concatenates() {
426        let v = vars(&[
427            ("custom.coding.standards", "Use snake_case."),
428            ("custom.coding.guidelines", "Write tests."),
429        ]);
430        let result = render_template("{{ custom.coding }}", &v);
431        assert!(result.contains("Use snake_case."));
432        assert!(result.contains("Write tests."));
433    }
434
435    #[test]
436    fn render_plural_collections() {
437        let v = vars(&[("agents", "<agent name=\"a\"/><agent name=\"b\"/>")]);
438        assert_eq!(
439            render_template("{{ agents }}", &v),
440            "<agent name=\"a\"/><agent name=\"b\"/>"
441        );
442    }
443
444    #[test]
445    fn render_conditional() {
446        let v = vars(&[("task.id", "TASK-001"), ("task.title", "Fix bug")]);
447        let template = "{% if task.id %}Task: {{ task.title }}{% endif %}";
448        assert_eq!(render_template(template, &v), "Task: Fix bug");
449    }
450
451    #[test]
452    fn render_conditional_empty() {
453        let v = HashMap::new();
454        let template = "{% if task.id %}Task: {{ task.title }}{% else %}No task{% endif %}";
455        assert_eq!(render_template(template, &v), "No task");
456    }
457
458    #[test]
459    fn render_preserves_raw_xml() {
460        let v = vars(&[("agents", "<agent name=\"dev\" />")]);
461        assert_eq!(
462            render_template("{{ agents }}", &v),
463            "<agent name=\"dev\" />"
464        );
465    }
466
467    #[test]
468    fn render_empty_template() {
469        assert_eq!(render_template("", &HashMap::new()), "");
470    }
471
472    #[test]
473    fn render_no_variables() {
474        assert_eq!(
475            render_template("Just plain text.", &HashMap::new()),
476            "Just plain text."
477        );
478    }
479
480    #[test]
481    fn render_undefined_variable_empty() {
482        let result = render_template("Value: {{ something.unknown }}", &HashMap::new());
483        assert_eq!(result, "Value: ");
484    }
485
486    #[test]
487    fn render_mixed_jinja_and_vars() {
488        let v = vars(&[
489            ("project.name", "Test"),
490            ("task.title", "Fix bug"),
491            ("context.nenjo.current_task", "<task>data</task>"),
492        ]);
493        let template = r#"{{ context.nenjo.current_task }}
494{% if project.name == "Test" %}
495Extra context for test project
496{% endif %}
497Task: {{ task.title }}"#;
498
499        let result = render_template(template, &v);
500        assert!(result.contains("<task>data</task>"));
501        assert!(result.contains("Extra context for test project"));
502        assert!(result.contains("Task: Fix bug"));
503    }
504
505    #[test]
506    fn try_render_success() {
507        let v = vars(&[("profile.name", "dev")]);
508        assert_eq!(
509            try_render_template("{{ profile.name }}", &v).unwrap(),
510            "dev"
511        );
512    }
513
514    #[test]
515    fn try_render_error() {
516        let result = try_render_template("{% invalid syntax %}", &HashMap::new());
517        assert!(result.is_err());
518        assert!(!result.unwrap_err().message.is_empty());
519    }
520
521    #[test]
522    fn try_render_strict_errors_on_undefined_variable() {
523        let result = try_render_template_strict("{{ vars.dummy }}", &HashMap::new());
524
525        assert!(result.is_err());
526        assert!(result.unwrap_err().message.contains("undefined"));
527    }
528
529    #[test]
530    fn try_render_empty() {
531        assert_eq!(try_render_template("", &HashMap::new()).unwrap(), "");
532    }
533
534    #[test]
535    fn render_with_named_template_include() {
536        let v = vars(&[("profile.name", "Nenji")]);
537        let templates = HashMap::from([(
538            "pkg/nenjo/core/methodology".to_string(),
539            "<methodology>{{ profile.name }}</methodology>".to_string(),
540        )]);
541
542        let rendered = render_template_with_named_templates(
543            r#"{% include "pkg/nenjo/core/methodology" %}"#,
544            &v,
545            &templates,
546        );
547
548        assert_eq!(rendered, "<methodology>Nenji</methodology>");
549    }
550
551    #[test]
552    fn render_with_named_templates_supports_nested_includes() {
553        let v = vars(&[("profile.name", "Nenji")]);
554        let templates = HashMap::from([
555            (
556                "base".to_string(),
557                "<base>{{ profile.name }}</base>".to_string(),
558            ),
559            (
560                "wrapper".to_string(),
561                "<wrapper>{% include \"base\" %}</wrapper>".to_string(),
562            ),
563        ]);
564
565        let rendered =
566            render_template_with_named_templates(r#"{% include "wrapper" %}"#, &v, &templates);
567
568        assert_eq!(rendered, "<wrapper><base>Nenji</base></wrapper>");
569    }
570
571    #[test]
572    fn try_render_with_named_templates_errors_on_missing_include() {
573        let result = try_render_template_with_named_templates(
574            r#"{% include "missing" %}"#,
575            &HashMap::new(),
576            &HashMap::new(),
577        );
578
579        assert!(result.is_err());
580        assert!(!result.unwrap_err().message.is_empty());
581    }
582
583    #[test]
584    fn try_render_with_named_templates_strict_errors_on_undefined_variable() {
585        let result = try_render_template_with_named_templates_strict(
586            "{{ vars.dummy }}",
587            &HashMap::new(),
588            &HashMap::new(),
589        );
590
591        assert!(result.is_err());
592        assert!(result.unwrap_err().message.contains("undefined"));
593    }
594
595    #[test]
596    fn try_render_with_named_templates_errors_on_include_cycle() {
597        let templates = HashMap::from([
598            ("a".to_string(), r#"{% include "b" %}"#.to_string()),
599            ("b".to_string(), r#"{% include "a" %}"#.to_string()),
600        ]);
601
602        let result = try_render_template_with_named_templates(
603            r#"{% include "a" %}"#,
604            &HashMap::new(),
605            &templates,
606        );
607
608        assert!(result.is_err());
609        assert!(!result.unwrap_err().message.is_empty());
610    }
611
612    #[test]
613    fn named_templates_preserve_literal_escaped_jinja_syntax() {
614        let templates = HashMap::from([(
615            "guide".to_string(),
616            r#"Use \{{ variable }} literally."#.to_string(),
617        )]);
618
619        let rendered = render_template_with_named_templates(
620            r#"{% include "guide" %}"#,
621            &HashMap::new(),
622            &templates,
623        );
624
625        assert_eq!(rendered, "Use {{ variable }} literally.");
626    }
627
628    #[test]
629    fn render_context_block_as_template() {
630        // Context blocks are just templates rendered with the same vars
631        let v = vars(&[
632            ("task.id", "42"),
633            ("task.title", "Fix bug"),
634            ("agents", "<agent name=\"dev\"/>"),
635        ]);
636
637        let block = r#"<current_task>
638  <id>{{ task.id }}</id>
639  <title>{{ task.title }}</title>
640</current_task>"#;
641
642        let result = render_template(block, &v);
643        assert!(result.contains("<id>42</id>"));
644        assert!(result.contains("<title>Fix bug</title>"));
645    }
646
647    #[test]
648    fn render_deeply_nested_keys() {
649        let v = vars(&[("a.b.c.d", "deep")]);
650        assert_eq!(render_template("{{ a.b.c.d }}", &v), "deep");
651    }
652
653    // -----------------------------------------------------------------------
654    // MiniJinja escaping behaviour
655    // -----------------------------------------------------------------------
656
657    #[test]
658    fn auto_escape_is_disabled() {
659        // HTML/XML special characters pass through unescaped because
660        // auto-escape is set to None — variables containing pre-built XML
661        // must be injected verbatim.
662        let v = vars(&[("val", "<b>bold & \"quoted\"</b>")]);
663        assert_eq!(render_template("{{ val }}", &v), "<b>bold & \"quoted\"</b>");
664    }
665
666    #[test]
667    fn escape_filter_html_escapes() {
668        // The |e (|escape) filter explicitly applies HTML escaping even
669        // though auto-escape is off. Useful for user-supplied values that
670        // must be safe inside XML attributes or content.
671        let v = vars(&[("val", "<script>alert('xss')</script>")]);
672        assert_eq!(
673            render_template("{{ val|e }}", &v),
674            "&lt;script&gt;alert(&#x27;xss&#x27;)&lt;&#x2f;script&gt;"
675        );
676    }
677
678    #[test]
679    fn escape_filter_ampersand_and_quotes() {
680        let v = vars(&[("val", "a & b \"c\" 'd'")]);
681        assert_eq!(
682            render_template("{{ val|escape }}", &v),
683            "a &amp; b &quot;c&quot; &#x27;d&#x27;"
684        );
685    }
686
687    #[test]
688    fn escape_filter_preserves_safe_text() {
689        let v = vars(&[("val", "plain text 123")]);
690        assert_eq!(render_template("{{ val|e }}", &v), "plain text 123");
691    }
692
693    #[test]
694    fn backslash_in_plain_text_passes_through() {
695        // A backslash NOT followed by {{ is left as-is.
696        let v = vars(&[("val", "hello")]);
697        assert_eq!(
698            render_template("before\\nafter {{ val }}", &v),
699            "before\\nafter hello"
700        );
701    }
702
703    #[test]
704    fn raw_block_preserves_delimiters() {
705        // {% raw %} prevents MiniJinja from interpreting {{ }} delimiters.
706        let v = vars(&[("val", "ignored")]);
707        assert_eq!(
708            render_template("{% raw %}{{ val }}{% endraw %}", &v),
709            "{{ val }}"
710        );
711    }
712
713    #[test]
714    fn literal_braces_via_string_expression() {
715        // To output a literal {{ in MiniJinja, use a string expression.
716        assert_eq!(
717            render_template("{{ '{{' }} content {{ '}}' }}", &HashMap::new()),
718            "{{ content }}"
719        );
720    }
721
722    #[test]
723    fn escape_filter_on_xml_fragment() {
724        // Applying |e to an XML fragment escapes all tags — useful when
725        // the value should appear as visible text, not parsed XML.
726        let v = vars(&[("xml", "<agent name=\"dev\"/>")]);
727        assert_eq!(
728            render_template("{{ xml|e }}", &v),
729            "&lt;agent name=&quot;dev&quot;&#x2f;&gt;"
730        );
731    }
732
733    #[test]
734    fn no_filter_preserves_xml_fragment() {
735        // Without |e, XML passes through raw (the default behaviour).
736        let v = vars(&[("xml", "<agent name=\"dev\"/>")]);
737        assert_eq!(render_template("{{ xml }}", &v), "<agent name=\"dev\"/>");
738    }
739
740    // -----------------------------------------------------------------------
741    // Backslash escape pre-processor (unit tests on escape_backslash_braces)
742    // -----------------------------------------------------------------------
743
744    #[test]
745    fn esc_plain_text_unchanged() {
746        assert_eq!(escape_backslash_braces("no braces here"), "no braces here");
747    }
748
749    #[test]
750    fn esc_normal_braces_unchanged() {
751        assert_eq!(escape_backslash_braces("{{ val }}"), "{{ val }}");
752    }
753
754    #[test]
755    fn esc_backslash_braces_converted() {
756        assert_eq!(
757            escape_backslash_braces(r"\{{ val }}"),
758            "{% raw %}{{{% endraw %} val }}"
759        );
760    }
761
762    #[test]
763    fn esc_double_backslash_then_braces() {
764        // \\{{ → literal \ followed by normal {{ (variable expression)
765        assert_eq!(escape_backslash_braces(r"\\{{ val }}"), r"\{{ val }}");
766    }
767
768    #[test]
769    fn esc_triple_backslash_then_braces() {
770        // \\\{{ → \\ consumes to \, then \{{ escapes the braces
771        assert_eq!(
772            escape_backslash_braces(r"\\\{{ val }}"),
773            "\\{% raw %}{{{% endraw %} val }}"
774        );
775    }
776
777    #[test]
778    fn esc_quadruple_backslash_then_braces() {
779        // \\\\{{ → two \\ pairs → two literal backslashes + normal {{
780        assert_eq!(escape_backslash_braces(r"\\\\{{ val }}"), r"\\{{ val }}");
781    }
782
783    #[test]
784    fn esc_lone_backslash_at_end() {
785        assert_eq!(escape_backslash_braces("text\\"), "text\\");
786    }
787
788    #[test]
789    fn esc_backslash_before_single_brace() {
790        // \{ is not \{{ — left as-is
791        assert_eq!(escape_backslash_braces(r"\{ nope"), r"\{ nope");
792    }
793
794    #[test]
795    fn esc_backslash_before_non_brace() {
796        assert_eq!(escape_backslash_braces(r"\n\t"), r"\n\t");
797    }
798
799    #[test]
800    fn esc_multiple_escaped_braces() {
801        assert_eq!(
802            escape_backslash_braces(r"\{{ a }} and \{{ b }}"),
803            "{% raw %}{{{% endraw %} a }} and {% raw %}{{{% endraw %} b }}"
804        );
805    }
806
807    #[test]
808    fn esc_at_start_of_string() {
809        assert_eq!(
810            escape_backslash_braces(r"\{{ start }}"),
811            "{% raw %}{{{% endraw %} start }}"
812        );
813    }
814
815    #[test]
816    fn esc_adjacent_escaped_braces() {
817        assert_eq!(
818            escape_backslash_braces(r"\{{\{{"),
819            "{% raw %}{{{% endraw %}{% raw %}{{{% endraw %}"
820        );
821    }
822
823    #[test]
824    fn esc_empty_string() {
825        assert_eq!(escape_backslash_braces(""), "");
826    }
827
828    #[test]
829    fn esc_only_backslash() {
830        assert_eq!(escape_backslash_braces("\\"), "\\");
831    }
832
833    #[test]
834    fn esc_only_double_backslash() {
835        assert_eq!(escape_backslash_braces("\\\\"), "\\");
836    }
837
838    #[test]
839    fn esc_mixed_escaped_and_normal() {
840        assert_eq!(
841            escape_backslash_braces(r"{{ a }} \{{ b }} {{ c }}"),
842            "{{ a }} {% raw %}{{{% endraw %} b }} {{ c }}"
843        );
844    }
845
846    #[test]
847    fn esc_backslash_far_from_braces() {
848        assert_eq!(
849            escape_backslash_braces(r"path\to\file {{ val }}"),
850            r"path\to\file {{ val }}"
851        );
852    }
853
854    #[test]
855    fn esc_double_backslash_without_braces() {
856        // \\ not followed by {{ → literal backslash
857        assert_eq!(escape_backslash_braces(r"a\\b"), r"a\b");
858    }
859
860    // -----------------------------------------------------------------------
861    // Backslash escape end-to-end (through render_template)
862    // -----------------------------------------------------------------------
863
864    #[test]
865    fn render_backslash_escapes_braces() {
866        let v = vars(&[("val", "replaced")]);
867        assert_eq!(render_template(r"text \{{ val }}", &v), "text {{ val }}");
868    }
869
870    #[test]
871    fn render_backslash_escape_mixed_with_variable() {
872        let v = vars(&[("name", "dev")]);
873        assert_eq!(
874            render_template(r"hello {{ name }}, use \{{ var }} for literals", &v),
875            "hello dev, use {{ var }} for literals"
876        );
877    }
878
879    #[test]
880    fn render_backslash_escape_multiple() {
881        assert_eq!(
882            render_template(r"\{{ a }} and \{{ b }}", &HashMap::new()),
883            "{{ a }} and {{ b }}"
884        );
885    }
886
887    #[test]
888    fn render_double_backslash_renders_variable() {
889        // \\{{ → literal \ + render variable
890        let v = vars(&[("val", "hello")]);
891        assert_eq!(render_template(r"\\{{ val }}", &v), r"\hello");
892    }
893
894    #[test]
895    fn render_triple_backslash_escapes_braces() {
896        // \\\{{ → literal \ + literal {{
897        assert_eq!(
898            render_template(r"\\\{{ val }}", &HashMap::new()),
899            r"\{{ val }}"
900        );
901    }
902
903    #[test]
904    fn render_no_backslash_renders_variable() {
905        let v = vars(&[("val", "hello")]);
906        assert_eq!(render_template("{{ val }}", &v), "hello");
907    }
908
909    #[test]
910    fn render_backslash_in_json_prompt() {
911        // Real-world case: prompt contains JSON with escaped braces
912        let v = vars(&[("format", "ignored")]);
913        assert_eq!(
914            render_template(r#"Respond in JSON: \{{ "key": "value" }}"#, &v,),
915            r#"Respond in JSON: {{ "key": "value" }}"#
916        );
917    }
918
919    #[test]
920    fn render_backslash_with_jinja_block() {
921        // \{{ inside a conditional block
922        let v = vars(&[("show", "yes")]);
923        assert_eq!(
924            render_template(r"{% if show %}literal: \{{ x }}{% endif %}", &v),
925            "literal: {{ x }}"
926        );
927    }
928
929    #[test]
930    fn render_backslash_only_escapes_double_brace() {
931        // \{ alone (single brace) is not special
932        let v = vars(&[("val", "hi")]);
933        assert_eq!(
934            render_template(r"\{ not escaped {{ val }}", &v),
935            r"\{ not escaped hi"
936        );
937    }
938
939    // -----------------------------------------------------------------------
940    // \{% block tag escaping — pre-processor unit tests
941    // -----------------------------------------------------------------------
942
943    #[test]
944    fn esc_block_tag_converted() {
945        assert_eq!(
946            escape_backslash_braces(r"\{% if x %}"),
947            "{% raw %}{%{% endraw %} if x %}"
948        );
949    }
950
951    #[test]
952    fn esc_block_tag_normal_unchanged() {
953        assert_eq!(escape_backslash_braces("{% if x %}"), "{% if x %}");
954    }
955
956    #[test]
957    fn esc_double_backslash_block_tag() {
958        // \\{% → literal \ + real block tag
959        assert_eq!(escape_backslash_braces(r"\\{% if x %}"), r"\{% if x %}");
960    }
961
962    #[test]
963    fn esc_mixed_var_and_block_escapes() {
964        assert_eq!(
965            escape_backslash_braces(r"\{% if ok %}\{{ val }}\{% endif %}"),
966            "{% raw %}{%{% endraw %} if ok %}{% raw %}{{{% endraw %} val }}{% raw %}{%{% endraw %} endif %}"
967        );
968    }
969
970    #[test]
971    fn esc_block_tag_at_start() {
972        assert_eq!(
973            escape_backslash_braces(r"\{% raw %}"),
974            "{% raw %}{%{% endraw %} raw %}"
975        );
976    }
977
978    #[test]
979    fn esc_block_tag_adjacent() {
980        assert_eq!(
981            escape_backslash_braces(r"\{%\{%"),
982            "{% raw %}{%{% endraw %}{% raw %}{%{% endraw %}"
983        );
984    }
985
986    // -----------------------------------------------------------------------
987    // \{% block tag escaping — end-to-end through render_template
988    // -----------------------------------------------------------------------
989
990    #[test]
991    fn render_escaped_block_tags_literal() {
992        // \{% if %} should output literal {% if %}, not be interpreted
993        assert_eq!(
994            render_template(
995                r"\{% if task.id %}\{{ task.title }}\{% endif %}",
996                &HashMap::new()
997            ),
998            "{% if task.id %}{{ task.title }}{% endif %}"
999        );
1000    }
1001
1002    #[test]
1003    fn render_escaped_block_mixed_with_real_block() {
1004        // Real {% if %} block + escaped \{{ inside it
1005        let v = vars(&[("show", "yes")]);
1006        assert_eq!(
1007            render_template(r"{% if show %}use \{{ var }} syntax{% endif %}", &v),
1008            "use {{ var }} syntax"
1009        );
1010    }
1011
1012    #[test]
1013    fn render_escaped_conditional_example() {
1014        // The exact pattern from the template_vars_guide conditional_rendering section
1015        assert_eq!(
1016            render_template(
1017                r"\{% if task.id %}Task: \{{ task.title }}\{% endif %}",
1018                &HashMap::new(),
1019            ),
1020            "{% if task.id %}Task: {{ task.title }}{% endif %}"
1021        );
1022    }
1023
1024    #[test]
1025    fn render_escaped_if_else_example() {
1026        assert_eq!(
1027            render_template(
1028                r"\{% if task.id %}...\{% else %}No task context\{% endif %}",
1029                &HashMap::new(),
1030            ),
1031            "{% if task.id %}...{% else %}No task context{% endif %}"
1032        );
1033    }
1034
1035    #[test]
1036    fn render_double_backslash_block_tag() {
1037        // \\{% → literal \ + real block tag executed
1038        let v = vars(&[("x", "yes")]);
1039        assert_eq!(render_template(r"\\{% if x %}ok{% endif %}", &v), r"\ok");
1040    }
1041
1042    // -----------------------------------------------------------------------
1043    // Multi-byte UTF-8 preservation
1044    // -----------------------------------------------------------------------
1045
1046    #[test]
1047    fn esc_preserves_em_dash() {
1048        assert_eq!(escape_backslash_braces("hello — world"), "hello — world");
1049    }
1050
1051    #[test]
1052    fn esc_preserves_emoji() {
1053        assert_eq!(
1054            escape_backslash_braces("status: ✅ done"),
1055            "status: ✅ done"
1056        );
1057    }
1058
1059    #[test]
1060    fn esc_preserves_multibyte_with_escapes() {
1061        assert_eq!(
1062            escape_backslash_braces(r"\{{ val }} — description"),
1063            "{% raw %}{{{% endraw %} val }} — description"
1064        );
1065    }
1066
1067    #[test]
1068    fn render_preserves_em_dash() {
1069        let v = vars(&[("name", "dev")]);
1070        assert_eq!(
1071            render_template(r"\{{ token }} — Literal {{ name }}", &v),
1072            "{{ token }} — Literal dev"
1073        );
1074    }
1075
1076    #[test]
1077    fn render_preserves_cjk() {
1078        assert_eq!(
1079            render_template("日本語テスト", &HashMap::new()),
1080            "日本語テスト"
1081        );
1082    }
1083
1084    #[test]
1085    fn esc_preserves_mixed_unicode_and_escapes() {
1086        assert_eq!(
1087            escape_backslash_braces(r"\{{ profile.id }} — UUID • \{{ profile.name }} — Name"),
1088            "{% raw %}{{{% endraw %} profile.id }} — UUID • {% raw %}{{{% endraw %} profile.name }} — Name"
1089        );
1090    }
1091}