Skip to main content

oxdock_process/
expand.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3
4use anyhow::{Result, anyhow, bail};
5
6use crate::contract::CommandContext;
7
8/// Maximum bytes to buffer while scanning for closing delimiter.
9/// If exceeded without finding closing delimiter, buffered bytes are flushed as literals.
10const MAX_PLACEHOLDER_SCAN: usize = 1024;
11
12/// Configurable delimiter syntax for template expansion.
13pub struct TemplateDelimiters {
14    pub open: &'static [u8],
15    pub close: &'static [u8],
16}
17
18impl Default for TemplateDelimiters {
19    fn default() -> Self {
20        Self {
21            open: b"{{",
22            close: b"}}",
23        }
24    }
25}
26
27/// Resolver for `{{ MODULE::FUNC(args) }}` placeholder calls.
28///
29/// Receives the module name, function name, and already resolved argument
30/// values, and returns the call result. Only pure value returning host
31/// functions may back this: no handles, no pipes, no I/O. The resolver
32/// carries no formatting logic; formatting lives with the function.
33pub type PlaceholderCall = Arc<
34    dyn Fn(&str, &str, Vec<oxdock_parser::Value>) -> Result<oxdock_parser::Value> + Send + Sync,
35>;
36
37/// Streaming template expansion state machine.
38///
39/// Processes input bytes incrementally, expanding `{{ env:KEY }}` placeholders.
40/// At most `MAX_PLACEHOLDER_SCAN` bytes are held in buffer. Plain text streams
41/// flush immediately with zero buffering.
42pub struct StreamingExpand {
43    /// Bytes accumulated as key payload inside `{{ ... }}` (no open delimiter prefix).
44    buffer: Vec<u8>,
45    /// Explicit key=value overrides (take precedence over env).
46    overrides: HashMap<String, String>,
47    /// Environment variable lookup.
48    env: HashMap<String, String>,
49    /// Structured variable lookup (for key-path evaluation).
50    vars: HashMap<String, oxdock_parser::Value>,
51    /// Optional dispatcher for `{{ MODULE::FUNC(args) }}` calls. When set,
52    /// placeholders holding a call expression are evaluated through it.
53    /// Carries dispatch only; formatting stays with the callee.
54    call_resolver: Option<PlaceholderCall>,
55    /// State: are we currently inside a placeholder?
56    in_placeholder: bool,
57    /// Trailing opening byte from previous chunk : deferred across chunks.
58    pending_brace: bool,
59    /// Trailing closing byte from previous chunk : deferred across chunks.
60    pending_close_brace: bool,
61    /// Trailing backslash from previous chunk : deferred across chunks so
62    /// `\{{` split across a boundary still emits a literal opener.
63    pending_escape: bool,
64    /// Trailing `\` + `{` from previous chunk : deferred across chunks so
65    /// a `\{` split across a boundary still resolves as an escape pair.
66    pending_escape_brace: bool,
67    /// Configurable delimiter syntax.
68    delimiters: TemplateDelimiters,
69}
70
71impl StreamingExpand {
72    /// Create with env vars and optional explicit overrides.
73    /// Overrides take precedence over env vars.
74    pub fn new(overrides: &[(String, String)], env: &HashMap<String, String>) -> Self {
75        Self {
76            buffer: Vec::with_capacity(256),
77            overrides: overrides.iter().cloned().collect(),
78            env: env.clone(),
79            vars: HashMap::new(),
80            call_resolver: None,
81            in_placeholder: false,
82            pending_brace: false,
83            pending_close_brace: false,
84            pending_escape: false,
85            pending_escape_brace: false,
86            delimiters: TemplateDelimiters::default(),
87        }
88    }
89
90    /// Create with env vars, structured variables, and optional explicit overrides.
91    /// Enables key-path evaluation in template tags (e.g., `{{ pkg.package.name }}`).
92    pub fn with_vars(mut self, vars: &HashMap<String, oxdock_parser::Value>) -> Self {
93        self.vars = vars.clone();
94        self
95    }
96
97    /// Enable `{{ MODULE::FUNC(args) }}` calls, dispatched through `resolver`.
98    /// Args are `$var.path` references, string, int, float, and bool
99    /// literals, or `{key: value}` and `[item]` literals nesting those
100    /// same shapes. Unknown functions and bad arity fail strict at expansion.
101    pub fn with_call_resolver(mut self, resolver: PlaceholderCall) -> Self {
102        self.call_resolver = Some(resolver);
103        self
104    }
105
106    /// Process a chunk of input bytes, writing expanded output to `out`.
107    /// Returns early on empty input to preserve pending boundary state.
108    pub fn process_bytes(&mut self, input: &[u8], out: &mut Vec<u8>) -> Result<usize> {
109        if input.is_empty() {
110            return Ok(0);
111        }
112
113        let start_len = out.len();
114        let mut i = 0;
115
116        // Handle pending close brace from previous chunk
117        if self.pending_close_brace {
118            self.pending_close_brace = false;
119            if input[0] == self.delimiters.close[1] {
120                // Confirmed close delimiter across boundary : extract key, lookup, emit
121                let key = extract_key(&self.buffer);
122                let value = lookup(
123                    &key,
124                    &self.overrides,
125                    &self.env,
126                    &self.vars,
127                    self.call_resolver.as_ref(),
128                )?;
129                out.extend_from_slice(value.as_bytes());
130                self.buffer.clear();
131                self.in_placeholder = false;
132                i = self.delimiters.close.len() - 1; // Skip input[0] (the second byte)
133            } else {
134                // Lone closing byte : treat as literal part of key
135                // Push it to buffer, then let scan_placeholder process input[0]
136                self.buffer.push(self.delimiters.close[0]);
137                i = 0; // Do NOT skip input[0]: let scan_placeholder handle it
138            }
139        }
140
141        // Handle pending open brace from previous chunk
142        if self.pending_brace {
143            self.pending_brace = false;
144            if input[0] == self.delimiters.open[1] {
145                // Confirmed `{{` across boundary : enter PlaceholderScan
146                self.in_placeholder = true;
147                self.buffer.clear();
148                i = 1; // Skip the second open byte
149            } else {
150                // Single open byte was just a literal : flush it
151                out.push(self.delimiters.open[0]);
152            }
153        }
154
155        // Handle pending escape pair from previous chunk: a trailing `\{`
156        // combines with a leading `{` into a literal opener. Anything
157        // else means both bytes were literal; re-emit them, then let the
158        // scan below handle this chunk from the start.
159        if self.pending_escape_brace {
160            self.pending_escape_brace = false;
161            if !input.is_empty() && input[0] == self.delimiters.open[1] {
162                out.extend_from_slice(b"{{");
163                i = 1;
164            } else {
165                out.push(b'\\');
166                out.push(self.delimiters.open[0]);
167            }
168        }
169
170        // Handle pending escape from previous chunk: a lone trailing `\`
171        // combines with a leading `{{` into a literal opener, or with a
172        // leading `\` into a literal backslash (the pair is complete, so
173        // whatever follows processes normally). A lone trailing `{`
174        // cannot decide yet, so it joins the deferred pair above.
175        if self.pending_escape {
176            self.pending_escape = false;
177            if input.len() >= 2 && input[0] == b'{' && input[1] == b'{' {
178                out.extend_from_slice(b"{{");
179                i = 2;
180            } else if input.len() == 1 && input[0] == self.delimiters.open[0] {
181                self.pending_escape_brace = true;
182                i = 1;
183            } else if !input.is_empty() && input[0] == b'\\' {
184                out.push(b'\\');
185                i = 1;
186            } else {
187                // Not an escape : the backslash was literal; reprocess
188                // this chunk from the start (a lone `{` still defers via
189                // the pending_brace path below).
190                out.push(b'\\');
191            }
192        }
193
194        if self.in_placeholder {
195            // We're inside a placeholder : scan for closing delimiter
196            i = self.scan_placeholder(input, i, out)?;
197        }
198
199        // Normal state : scan for opening byte or flush literals
200        while i < input.len() {
201            if input[i] == b'\\' {
202                if i + 2 < input.len() && input[i + 1] == b'{' && input[i + 2] == b'{' {
203                    // Escaped opener : emit a literal `{{`, consume all three
204                    out.extend_from_slice(b"{{");
205                    i += 3;
206                } else if i + 2 == input.len() && input[i + 1] == self.delimiters.open[0] {
207                    // `\{` ends the chunk : defer the pair; the next
208                    // chunk decides literal `{{` vs literal `\` + `{`.
209                    self.pending_escape_brace = true;
210                    i += 2;
211                } else if i + 1 < input.len() && input[i + 1] == b'\\' {
212                    // Escaped backslash : emit one `\`, consume both (this
213                    // keeps `\\{{ ... }}` expanding, matching the lenient
214                    // interpolator used for command arguments)
215                    out.push(b'\\');
216                    i += 2;
217                } else if i + 1 == input.len() {
218                    // Trailing backslash : defer across the chunk boundary
219                    self.pending_escape = true;
220                    i += 1;
221                } else {
222                    // Ordinary backslash : literal, reprocess what follows
223                    out.push(b'\\');
224                    i += 1;
225                }
226            } else if input[i] == self.delimiters.open[0] {
227                if i + 1 < input.len() && input[i + 1] == self.delimiters.open[1] {
228                    // Found open delimiter : enter PlaceholderScan
229                    self.in_placeholder = true;
230                    self.buffer.clear();
231                    i += 2;
232                    i = self.scan_placeholder(input, i, out)?;
233                } else if i + 1 == input.len() {
234                    // Opening byte is the LAST byte of chunk : defer
235                    self.pending_brace = true;
236                    i += 1;
237                } else {
238                    // Single opening byte in the middle : flush as literal
239                    out.push(self.delimiters.open[0]);
240                    i += 1;
241                }
242            } else {
243                // Flush literal bytes until we find an opening byte, a
244                // backslash (potential `\{{` escape), or end of chunk
245                let start = i;
246                while i < input.len() && input[i] != self.delimiters.open[0] && input[i] != b'\\' {
247                    i += 1;
248                }
249                out.extend_from_slice(&input[start..i]);
250            }
251        }
252
253        Ok(out.len() - start_len)
254    }
255
256    /// Flush remaining buffer. Incomplete placeholders are treated as literals.
257    pub fn flush(mut self, out: &mut Vec<u8>) -> Result<()> {
258        // Emit deferred closing byte if present
259        if self.pending_close_brace {
260            self.buffer.push(self.delimiters.close[0]);
261            self.pending_close_brace = false;
262        }
263        // Emit deferred opening byte if present
264        if self.pending_brace {
265            out.push(self.delimiters.open[0]);
266            self.pending_brace = false;
267        }
268        // Emit deferred backslash if present
269        if self.pending_escape {
270            out.push(b'\\');
271            self.pending_escape = false;
272        }
273        // Emit deferred escape pair if present
274        if self.pending_escape_brace {
275            out.push(b'\\');
276            out.push(self.delimiters.open[0]);
277            self.pending_escape_brace = false;
278        }
279        // If inside placeholder, emit open delimiter prefix ONCE before buffer
280        if self.in_placeholder {
281            out.extend_from_slice(self.delimiters.open);
282            self.in_placeholder = false;
283        }
284        // Flush remaining buffer as literal text
285        out.extend_from_slice(&self.buffer);
286        self.buffer.clear();
287        Ok(())
288    }
289
290    /// Process a complete string (convenience for short command arguments).
291    pub fn expand_string(self, input: &str) -> Result<String> {
292        let mut out = Vec::with_capacity(input.len());
293        let mut expander = self;
294        expander.process_bytes(input.as_bytes(), &mut out)?;
295        expander.flush(&mut out)?;
296        Ok(String::from_utf8(out).unwrap_or_default())
297    }
298
299    /// Scan for closing delimiter starting at position `i`.
300    /// Returns the next position to process after the placeholder.
301    fn scan_placeholder(&mut self, input: &[u8], mut i: usize, out: &mut Vec<u8>) -> Result<usize> {
302        while i < input.len() {
303            if input[i] == self.delimiters.close[0] {
304                if i + 1 < input.len() && input[i + 1] == self.delimiters.close[1] {
305                    // Found closing delimiter : extract key, lookup, emit expansion
306                    let key = extract_key(&self.buffer);
307                    let value = lookup(
308                        &key,
309                        &self.overrides,
310                        &self.env,
311                        &self.vars,
312                        self.call_resolver.as_ref(),
313                    )?;
314                    out.extend_from_slice(value.as_bytes());
315                    self.buffer.clear();
316                    self.in_placeholder = false;
317                    return Ok(i + 2);
318                }
319                if i + 1 == input.len() {
320                    // Closing byte is the LAST byte : defer to next chunk
321                    self.pending_close_brace = true;
322                    return Ok(i + 1);
323                }
324            }
325            self.buffer.push(input[i]);
326            i += 1;
327
328            // Buffer limit exceeded : flush as literal
329            if self.buffer.len() > MAX_PLACEHOLDER_SCAN {
330                out.extend_from_slice(self.delimiters.open);
331                out.extend_from_slice(&self.buffer);
332                self.buffer.clear();
333                self.in_placeholder = false;
334                return Ok(i);
335            }
336        }
337        Ok(i)
338    }
339}
340
341/// Extract and trim key from buffer content (the bytes between delimiters).
342fn extract_key(buffer: &[u8]) -> String {
343    String::from_utf8_lossy(buffer).trim().to_string()
344}
345
346/// Lookup a key in overrides and env, stripping namespace prefixes.
347///
348/// Strict resolution contract:
349/// - `{{ KEY }}` (bare) → overrides only
350/// - `{{ env:KEY }}` → overrides then env
351/// - `{{ $var }}` → script vars
352/// - `{{ $var.field }}` → script var key-path
353/// - `{{ MODULE::FUNC(args) }}` → placeholder call via `calls`
354///
355/// All missing or invalid references return an error.
356fn lookup(
357    raw_key: &str,
358    overrides: &HashMap<String, String>,
359    env: &HashMap<String, String>,
360    vars: &HashMap<String, oxdock_parser::Value>,
361    calls: Option<&PlaceholderCall>,
362) -> Result<String> {
363    let key = raw_key.trim();
364
365    // 1. Explicit overrides (command-level CLI flags: KEY=val)
366    if let Some(val) = overrides.get(key) {
367        return Ok(val.clone());
368    }
369
370    // 2. Environment variables: must be prefixed with "env:"
371    if let Some(env_key) = key.strip_prefix("env:") {
372        if let Some(val) = overrides.get(env_key).or_else(|| env.get(env_key)) {
373            return Ok(val.clone());
374        }
375        let hint = if vars.contains_key(env_key) {
376            format!("; did you mean '${env_key}' (script variable)?")
377        } else {
378            String::new()
379        };
380        bail!("undefined environment variable: '{env_key}'{hint}");
381    }
382
383    // 3. Script variables: must be prefixed with "$"
384    if let Some(var_key) = key.strip_prefix('$') {
385        if var_key.contains('.') {
386            let parts: Vec<&str> = var_key.split('.').collect();
387            return resolve_key_path_strict(&parts, vars);
388        }
389        if let Some(val) = vars.get(var_key) {
390            return Ok(format_value_for_string(val));
391        }
392        let hint = if env.contains_key(var_key) {
393            format!("; did you mean 'env:{var_key}' (environment variable)?")
394        } else if overrides.contains_key(var_key) {
395            format!("; did you mean '{var_key}' (step override)?")
396        } else {
397            String::new()
398        };
399        bail!("undefined script variable: '${var_key}'{hint}");
400    }
401
402    // 4. Placeholder calls: `MODULE::FUNC(args)` dispatches through the
403    // registered resolver. Without one, the shape falls through to the
404    // invalid placeholder error below.
405    if let Some((module, func, args_src)) = parse_call(key) {
406        let Some(resolver) = calls else {
407            bail!(
408                "placeholder call '{module}::{func}' has no function registry; register one with with_call_resolver"
409            );
410        };
411        let mut args = Vec::with_capacity(args_src.len());
412        for src in args_src {
413            args.push(resolve_call_arg(&src, vars)?);
414        }
415        let result = resolver(module, func, args)?;
416        return Ok(format_value_for_string(&result));
417    }
418
419    // 5. Unprefixed key: could be a missing step override or invalid syntax
420    if !key.is_empty()
421        && key
422            .chars()
423            .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
424    {
425        let hint = if vars.contains_key(key) {
426            format!("; did you mean '${key}' (script variable)?")
427        } else if env.contains_key(key) {
428            format!("; did you mean 'env:{key}' (environment variable)?")
429        } else {
430            String::new()
431        };
432        bail!("missing required step override argument: '{key}'{hint}");
433    }
434    bail!(
435        "invalid placeholder format '{key}': script variables must start with '$' and environment variables with 'env:'"
436    );
437}
438
439/// Split a placeholder call body into module, function, and raw args.
440///
441/// Accepts `MODULE::FUNC()` and `MODULE::FUNC(a, b)`. Returns `None` when
442/// the body is not call shaped, so plain key paths keep their own errors.
443fn parse_call(key: &str) -> Option<(&str, &str, Vec<String>)> {
444    let (module, rest) = key.split_once("::")?;
445    if module.is_empty()
446        || !module
447            .chars()
448            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
449    {
450        return None;
451    }
452    let (func, args_src) = rest.split_once('(')?;
453    let func = func.trim();
454    if func.is_empty()
455        || !func
456            .chars()
457            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
458    {
459        return None;
460    }
461    let args_src = args_src.strip_suffix(')')?;
462    Some((module, func, split_args(args_src)))
463}
464
465/// Maximum nesting for map and list literals in placeholder call args.
466const MAX_LITERAL_DEPTH: usize = 16;
467
468/// Split call args on top level commas, keeping quoted strings and
469/// `{...}` / `[...]` literals intact. Commas nested inside literals
470/// belong to the literal, not the argument list. Nested calls stay
471/// rejected: only data literals nest, never `MODULE::FUNC(...)`.
472fn split_args(src: &str) -> Vec<String> {
473    split_top_level(src, ',')
474}
475
476/// Split on a top level separator, keeping quoted strings and
477/// `{...}` / `[...]` literals intact.
478fn split_top_level(src: &str, sep: char) -> Vec<String> {
479    let mut out = Vec::new();
480    let mut current = String::new();
481    let mut in_string = false;
482    let mut escaped = false;
483    let mut depth: usize = 0;
484    for c in src.chars() {
485        if in_string {
486            current.push(c);
487            if escaped {
488                escaped = false;
489            } else if c == '\\' {
490                escaped = true;
491            } else if c == '"' {
492                in_string = false;
493            }
494            continue;
495        }
496        match c {
497            '"' => {
498                in_string = true;
499                current.push(c);
500            }
501            '{' | '[' => {
502                depth += 1;
503                current.push(c);
504            }
505            '}' | ']' => {
506                depth = depth.saturating_sub(1);
507                current.push(c);
508            }
509            _ if c == sep && depth == 0 => {
510                out.push(current.trim().to_string());
511                current.clear();
512            }
513            _ => current.push(c),
514        }
515    }
516    let last = current.trim();
517    if !(out.is_empty() && last.is_empty()) {
518        out.push(last.to_string());
519    }
520    out
521}
522
523/// Resolve one call argument to a value: `$var.path` from vars, a
524/// string, int, float, or bool literal, or a `{key: value}` map or
525/// `[item]` list literal holding those same shapes nested.
526fn resolve_call_arg(
527    src: &str,
528    vars: &HashMap<String, oxdock_parser::Value>,
529) -> Result<oxdock_parser::Value> {
530    resolve_call_value(src, vars, 0)
531}
532
533fn resolve_call_value(
534    src: &str,
535    vars: &HashMap<String, oxdock_parser::Value>,
536    depth: usize,
537) -> Result<oxdock_parser::Value> {
538    if depth > MAX_LITERAL_DEPTH {
539        bail!("placeholder call argument nests too deep (limit {MAX_LITERAL_DEPTH})");
540    }
541    if let Some(path) = src.strip_prefix('$') {
542        let parts: Vec<&str> = path.split('.').collect();
543        return resolve_value_path(&parts, vars);
544    }
545    if src.len() >= 2 && src.starts_with('"') && src.ends_with('"') {
546        return Ok(oxdock_parser::Value::string(unescape_literal(
547            &src[1..src.len() - 1],
548        )?));
549    }
550    if let Some(inner) = strip_wrapped(src, '{', '}') {
551        return resolve_call_map(inner, vars, depth);
552    }
553    if let Some(inner) = strip_wrapped(src, '[', ']') {
554        return resolve_call_list(inner, vars, depth);
555    }
556    match src {
557        "true" => return Ok(oxdock_parser::Value::bool(true)),
558        "false" => return Ok(oxdock_parser::Value::bool(false)),
559        _ => {}
560    }
561    if let Ok(i) = src.parse::<i64>() {
562        return Ok(oxdock_parser::Value::int(i));
563    }
564    if let Ok(f) = src.parse::<f64>() {
565        return Ok(oxdock_parser::Value::float(f));
566    }
567    bail!(
568        "invalid placeholder call argument '{src}': use $var.path, a string, int, float, or bool literal, or a {{key: value}} or [item] literal"
569    )
570}
571
572/// Strip one wrapping delimiter pair, rejecting unbalanced closers
573/// inside: the opener at 0 must match the closer at the end with no
574/// earlier top level closer.
575fn strip_wrapped(src: &str, open: char, close: char) -> Option<&str> {
576    if !src.starts_with(open) || !src.ends_with(close) || src.len() < 2 {
577        return None;
578    }
579    let mut in_string = false;
580    let mut escaped = false;
581    let mut depth: usize = 0;
582    for (idx, c) in src.char_indices() {
583        if in_string {
584            if escaped {
585                escaped = false;
586            } else if c == '\\' {
587                escaped = true;
588            } else if c == '"' {
589                in_string = false;
590            }
591            continue;
592        }
593        match c {
594            '"' => in_string = true,
595            _ if c == open => depth += 1,
596            _ if c == close => {
597                depth -= 1;
598                if depth == 0 && idx != src.len() - close.len_utf8() {
599                    return None;
600                }
601            }
602            _ => {}
603        }
604    }
605    if depth != 0 {
606        return None;
607    }
608    Some(&src[open.len_utf8()..src.len() - close.len_utf8()])
609}
610
611/// Resolve a `{key: value}` map literal. Keys are bare ASCII
612/// identifiers or double quoted strings; values recurse through
613/// [`resolve_call_value`].
614fn resolve_call_map(
615    inner: &str,
616    vars: &HashMap<String, oxdock_parser::Value>,
617    depth: usize,
618) -> Result<oxdock_parser::Value> {
619    let mut entries = std::collections::BTreeMap::new();
620    if inner.trim().is_empty() {
621        return Ok(oxdock_parser::Value::map(entries));
622    }
623    for entry in split_top_level(inner, ',') {
624        let parts = split_top_level(&entry, ':');
625        if parts.len() != 2 {
626            bail!("invalid map literal entry '{entry}': use key: value");
627        }
628        let key = resolve_call_key(&parts[0])?;
629        if entries.contains_key(&key) {
630            bail!("duplicate key '{key}' in map literal");
631        }
632        let value = resolve_call_value(&parts[1], vars, depth + 1)?;
633        entries.insert(key, value);
634    }
635    Ok(oxdock_parser::Value::map(entries))
636}
637
638/// Resolve one map literal key: a bare ASCII identifier or a double
639/// quoted string.
640fn resolve_call_key(src: &str) -> Result<String> {
641    if src.len() >= 2 && src.starts_with('"') && src.ends_with('"') {
642        return unescape_literal(&src[1..src.len() - 1]);
643    }
644    if !src.is_empty() && src.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
645        return Ok(src.to_string());
646    }
647    bail!("invalid map literal key '{src}': use name or \"name\"")
648}
649
650/// Resolve a `[item]` list literal, elements recursing through
651/// [`resolve_call_value`].
652fn resolve_call_list(
653    inner: &str,
654    vars: &HashMap<String, oxdock_parser::Value>,
655    depth: usize,
656) -> Result<oxdock_parser::Value> {
657    let mut items = Vec::new();
658    if inner.trim().is_empty() {
659        return Ok(oxdock_parser::Value::list(items));
660    }
661    for item in split_top_level(inner, ',') {
662        items.push(resolve_call_value(&item, vars, depth + 1)?);
663    }
664    Ok(oxdock_parser::Value::list(items))
665}
666
667/// Unescape a double quoted literal: `\\` and `\"` only. Anything else
668/// keeps its backslash so template text stays predictable.
669fn unescape_literal(src: &str) -> Result<String> {
670    let mut out = String::with_capacity(src.len());
671    let mut chars = src.chars();
672    while let Some(c) = chars.next() {
673        if c != '\\' {
674            out.push(c);
675            continue;
676        }
677        match chars.next() {
678            Some('\\') => out.push('\\'),
679            Some('"') => out.push('"'),
680            Some(other) => {
681                out.push('\\');
682                out.push(other);
683            }
684            None => bail!("unterminated escape in placeholder string literal"),
685        }
686    }
687    Ok(out)
688}
689
690/// Resolve a dotted path against vars, cloning the value for the caller.
691/// Mirrors `resolve_key_path_strict` but returns the value instead of
692/// its string form so calls receive typed arguments.
693fn resolve_value_path(
694    parts: &[&str],
695    vars: &HashMap<String, oxdock_parser::Value>,
696) -> Result<oxdock_parser::Value> {
697    if parts.is_empty() || parts[0].is_empty() {
698        bail!("invalid placeholder call argument: empty variable reference");
699    }
700    let root_key = parts[0];
701    let mut current = vars
702        .get(root_key)
703        .ok_or_else(|| anyhow!("undefined script variable: '${root_key}'"))?
704        .clone();
705    for &segment in &parts[1..] {
706        if segment.contains('(') || segment.contains(')') {
707            bail!("nested calls are not supported in placeholder arguments");
708        }
709        if let Some(map) = current.as_map() {
710            current = map
711                .get(segment)
712                .ok_or_else(|| anyhow!("property '{segment}' not found on object '${root_key}'"))?
713                .clone();
714        } else if let Some(list) = current.as_list() {
715            let idx: usize = segment
716                .parse()
717                .map_err(|_| anyhow!("invalid array index '{segment}' on list '${root_key}'"))?;
718            current = list
719                .get(idx)
720                .ok_or_else(|| {
721                    anyhow!(
722                        "index {idx} out of bounds for list '${root_key}' (len: {})",
723                        list.len()
724                    )
725                })?
726                .clone();
727        } else {
728            bail!("cannot access property '{segment}' on primitive value of '${root_key}'")
729        }
730    }
731    Ok(current)
732}
733
734/// Resolve nested key-paths against the vars map.
735///
736/// Fails explicitly on missing object keys, out-of-bounds array indices,
737/// or type mismatches (e.g. trying to access a property on a primitive).
738fn resolve_key_path_strict(
739    parts: &[&str],
740    vars: &HashMap<String, oxdock_parser::Value>,
741) -> Result<String> {
742    let root_key = parts[0];
743    let mut current = vars
744        .get(root_key)
745        .ok_or_else(|| anyhow!("undefined script variable: '${root_key}'"))?;
746
747    for &segment in &parts[1..] {
748        if let Some(map) = current.as_map() {
749            current = map
750                .get(segment)
751                .ok_or_else(|| anyhow!("property '{segment}' not found on object '${root_key}'"))?;
752        } else if let Some(list) = current.as_list() {
753            let idx: usize = segment
754                .parse()
755                .map_err(|_| anyhow!("invalid array index '{segment}' on list '${root_key}'"))?;
756            current = list.get(idx).ok_or_else(|| {
757                anyhow!(
758                    "index {idx} out of bounds for list '${root_key}' (len: {})",
759                    list.len()
760                )
761            })?;
762        } else {
763            bail!("cannot access property '{segment}' on primitive value of '${root_key}'")
764        }
765    }
766
767    Ok(format_value_for_string(current))
768}
769
770/// Format a Value as a string for inline interpolation.
771fn format_value_for_string(val: &oxdock_parser::Value) -> String {
772    if let Some(s) = val.as_str() {
773        return s.to_string();
774    }
775    if let Some(i) = val.as_i64() {
776        return i.to_string();
777    }
778    if let Some(f) = val.as_f64() {
779        return f.to_string();
780    }
781    if let Some(b) = val.as_bool() {
782        return b.to_string();
783    }
784    // Pipes render through `Display` (`<pipe>`) via the fallthrough below;
785    // handles are opaque and have no string form to spell.
786    if let Some(d) = val.as_duration() {
787        return oxdock_parser::command::format_duration(&d);
788    }
789    if let Some(p) = val.as_path() {
790        return p.to_string_lossy().to_string();
791    }
792    if let Some(items) = val.as_list() {
793        return items
794            .iter()
795            .map(format_value_for_string)
796            .collect::<Vec<_>>()
797            .join(" ");
798    }
799    if let Some(map) = val.as_map() {
800        return map
801            .iter()
802            .map(|(k, v)| format!("\"{}\": {}", k, format_value_for_string(v)))
803            .collect::<Vec<_>>()
804            .join(", ");
805    }
806    if let Some(id) = val.as_handle() {
807        return format!("task#{}", id);
808    }
809    format!("{}", val)
810}
811
812// Legacy functions for backward compatibility
813
814pub(crate) fn expand_with_lookup<F>(input: &str, mut lookup_fn: F) -> String
815where
816    F: FnMut(&str) -> Option<String>,
817{
818    let mut out = String::with_capacity(input.len());
819    let mut chars = input.chars().peekable();
820    while let Some(c) = chars.next() {
821        if c == '{' {
822            if let Some(&'{') = chars.peek() {
823                chars.next(); // consume second '{'
824                let mut content = String::new();
825                let mut closed = false;
826                // Look ahead for closing }}
827                let mut inner_chars = chars.clone();
828                while let Some(ch) = inner_chars.next() {
829                    if ch == '}'
830                        && let Some(&'}') = inner_chars.peek()
831                    {
832                        closed = true;
833                        break;
834                    }
835                    content.push(ch);
836                }
837
838                if closed {
839                    // Advance main iterator past content and closing braces.
840                    // Count chars, not bytes: content may contain multi-byte
841                    // UTF-8 (e.g. non-ASCII placeholder names).
842                    for _ in 0..content.chars().count() {
843                        chars.next();
844                    }
845                    chars.next(); // first }
846                    chars.next(); // second }
847
848                    let key = content.trim();
849                    if !key.is_empty() {
850                        out.push_str(&lookup_fn(key).unwrap_or_default());
851                    }
852                } else {
853                    out.push('{');
854                    out.push('{');
855                }
856            } else {
857                out.push('{');
858            }
859        } else {
860            out.push(c);
861        }
862    }
863    out
864}
865
866pub fn expand_script_env(input: &str, script_envs: &HashMap<String, String>) -> String {
867    expand_with_lookup(input, |name| {
868        if let Some(key) = name.strip_prefix("env:") {
869            script_envs
870                .get(key)
871                .cloned()
872                .or_else(|| std::env::var(key).ok())
873        } else {
874            None
875        }
876    })
877}
878
879pub fn expand_command_env(input: &str, ctx: &CommandContext) -> String {
880    expand_with_lookup(input, |name| {
881        if let Some(key) = name.strip_prefix("env:") {
882            ctx.envs().get(key).cloned()
883        } else {
884            None
885        }
886    })
887}
888
889#[cfg(test)]
890mod tests {
891    use super::*;
892    use std::collections::HashMap;
893
894    #[test]
895    fn basic_expansion() {
896        let mut env = HashMap::new();
897        env.insert("NAME".into(), "World".into());
898        let expander = StreamingExpand::new(&[], &env);
899        let result = expander.expand_string("Hello {{ env:NAME }}").unwrap();
900        assert_eq!(result, "Hello World");
901    }
902
903    #[test]
904    fn multiple_vars() {
905        let mut env = HashMap::new();
906        env.insert("A".into(), "X".into());
907        env.insert("B".into(), "Y".into());
908        let expander = StreamingExpand::new(&[], &env);
909        let result = expander
910            .expand_string("{{ env:A }} and {{ env:B }}")
911            .unwrap();
912        assert_eq!(result, "X and Y");
913    }
914
915    #[test]
916    fn missing_var() {
917        let env = HashMap::new();
918        let expander = StreamingExpand::new(&[], &env);
919        let result = expander.expand_string("{{ env:MISSING }}");
920        assert!(result.is_err());
921        assert!(
922            result
923                .unwrap_err()
924                .to_string()
925                .contains("undefined environment variable"),
926            "error should mention undefined environment variable"
927        );
928    }
929
930    #[test]
931    fn no_placeholders() {
932        let env = HashMap::new();
933        let expander = StreamingExpand::new(&[], &env);
934        let result = expander.expand_string("plain text").unwrap();
935        assert_eq!(result, "plain text");
936    }
937
938    #[test]
939    fn empty_input() {
940        let env = HashMap::new();
941        let expander = StreamingExpand::new(&[], &env);
942        let result = expander.expand_string("").unwrap();
943        assert_eq!(result, "");
944    }
945
946    #[test]
947    fn override_precedence() {
948        let mut env = HashMap::new();
949        env.insert("KEY".into(), "envval".into());
950        let overrides = vec![("KEY".into(), "override".into())];
951        let expander = StreamingExpand::new(&overrides, &env);
952        let result = expander.expand_string("{{ env:KEY }}").unwrap();
953        assert_eq!(result, "override");
954    }
955
956    #[test]
957    fn override_with_namespace() {
958        let mut env = HashMap::new();
959        env.insert("CRATE".into(), "envval".into());
960        let overrides = vec![("CRATE".into(), "override".into())];
961        let expander = StreamingExpand::new(&overrides, &env);
962        let result = expander.expand_string("{{ env:CRATE }}").unwrap();
963        assert_eq!(result, "override");
964    }
965
966    #[test]
967    fn override_raw_key_match() {
968        let mut env = HashMap::new();
969        env.insert("CRATE".into(), "envval".into());
970        let overrides = vec![("env:CRATE".into(), "override".into())];
971        let expander = StreamingExpand::new(&overrides, &env);
972        let result = expander.expand_string("{{ env:CRATE }}").unwrap();
973        assert_eq!(result, "override");
974    }
975
976    #[test]
977    fn unclosed_placeholder() {
978        let env = HashMap::new();
979        let expander = StreamingExpand::new(&[], &env);
980        let result = expander.expand_string("{{ env:KEY").unwrap();
981        assert_eq!(result, "{{ env:KEY");
982    }
983
984    #[test]
985    fn unclosed_with_prefix() {
986        let env = HashMap::new();
987        let expander = StreamingExpand::new(&[], &env);
988        let result = expander.expand_string("Hello {{ env:KEY").unwrap();
989        assert_eq!(result, "Hello {{ env:KEY");
990    }
991
992    #[test]
993    fn buffer_limit_exceeded() {
994        let env = HashMap::new();
995        let expander = StreamingExpand::new(&[], &env);
996        // Create input with `{{` followed by >1024 bytes without `}}`
997        let mut input = b"{{ ".to_vec();
998        input.extend(std::iter::repeat_n(b'x', 2000));
999        let result = expander
1000            .expand_string(&String::from_utf8_lossy(&input))
1001            .unwrap();
1002        // Should flush as literal with `{{` prefix
1003        assert!(result.starts_with("{{ "));
1004        assert!(result.len() > 1024);
1005    }
1006
1007    #[test]
1008    fn escaped_opener_emits_literal() {
1009        let mut env = HashMap::new();
1010        env.insert("PROJECT".into(), "OxDock".into());
1011        let expander = StreamingExpand::new(&[], &env);
1012        let result = expander
1013            .expand_string("Built with \\{{ env:PROJECT }}")
1014            .unwrap();
1015        assert_eq!(result, "Built with {{ env:PROJECT }}");
1016    }
1017
1018    /// Stub resolver echoing `upper` over one string arg, for call tests.
1019    fn shout_resolver() -> PlaceholderCall {
1020        Arc::new(|module, func, args| {
1021            if module == "T" && func == "SHOUT" && args.len() == 1 {
1022                let s = args[0]
1023                    .as_str()
1024                    .ok_or_else(|| anyhow!("SHOUT expects a string"))?;
1025                return Ok(oxdock_parser::Value::string(s.to_uppercase()));
1026            }
1027            bail!("unknown placeholder function '{module}::{func}'")
1028        })
1029    }
1030
1031    #[test]
1032    fn placeholder_call_with_var_arg() {
1033        let env = HashMap::new();
1034        let mut vars = HashMap::new();
1035        vars.insert(
1036            "who".to_string(),
1037            oxdock_parser::Value::string("bob".to_string()),
1038        );
1039        let expander = StreamingExpand::new(&[], &env)
1040            .with_vars(&vars)
1041            .with_call_resolver(shout_resolver());
1042        let result = expander.expand_string("hi {{ T::SHOUT($who) }}!").unwrap();
1043        assert_eq!(result, "hi BOB!");
1044    }
1045
1046    #[test]
1047    fn placeholder_call_with_literal_args() {
1048        let env = HashMap::new();
1049        let expander = StreamingExpand::new(&[], &env).with_call_resolver(shout_resolver());
1050        let result = expander
1051            .expand_string("{{ T::SHOUT(\"bob\") }} {{ T::SHOUT( \"ann\" ) }}")
1052            .unwrap();
1053        assert_eq!(result, "BOB ANN");
1054    }
1055
1056    #[test]
1057    fn placeholder_call_output_stays_literal() {
1058        // Call output containing `{{ }}` is terminal text, never re-expanded.
1059        let env = HashMap::new();
1060        let mut vars = HashMap::new();
1061        vars.insert(
1062            "any".to_string(),
1063            oxdock_parser::Value::string("v".to_string()),
1064        );
1065        let resolver: PlaceholderCall = Arc::new(|_, _, _| {
1066            Ok(oxdock_parser::Value::string(
1067                "x {{ env:NOPE }} y".to_string(),
1068            ))
1069        });
1070        let expander = StreamingExpand::new(&[], &env)
1071            .with_vars(&vars)
1072            .with_call_resolver(resolver);
1073        let result = expander.expand_string("{{ T::SHOUT($any) }}").unwrap();
1074        assert_eq!(result, "x {{ env:NOPE }} y");
1075    }
1076
1077    #[test]
1078    fn placeholder_call_unknown_function_fails() {
1079        let env = HashMap::new();
1080        let expander = StreamingExpand::new(&[], &env).with_call_resolver(shout_resolver());
1081        let result = expander.expand_string("{{ T::NOPE($x) }}");
1082        assert!(result.is_err());
1083    }
1084
1085    #[test]
1086    fn placeholder_call_without_resolver_fails() {
1087        let env = HashMap::new();
1088        let expander = StreamingExpand::new(&[], &env);
1089        let result = expander.expand_string("{{ T::SHOUT($x) }}");
1090        assert!(result.is_err());
1091    }
1092
1093    #[test]
1094    fn escaped_opener_across_chunks() {
1095        let mut env = HashMap::new();
1096        env.insert("PROJECT".into(), "OxDock".into());
1097        let mut expander = StreamingExpand::new(&[], &env);
1098        let mut out = Vec::new();
1099
1100        // Split `\` / `{{ env:PROJECT }}` across chunks
1101        expander.process_bytes(b"Built with \\", &mut out).unwrap();
1102        expander
1103            .process_bytes(b"{{ env:PROJECT }}", &mut out)
1104            .unwrap();
1105        expander.flush(&mut out).unwrap();
1106
1107        assert_eq!(
1108            String::from_utf8_lossy(&out),
1109            "Built with {{ env:PROJECT }}"
1110        );
1111    }
1112
1113    #[test]
1114    fn double_backslash_then_placeholder_expands() {
1115        let mut env = HashMap::new();
1116        env.insert("PROJECT".into(), "OxDock".into());
1117        let expander = StreamingExpand::new(&[], &env);
1118        let result = expander.expand_string("\\\\{{ env:PROJECT }}").unwrap();
1119        assert_eq!(result, "\\OxDock");
1120    }
1121
1122    #[test]
1123    fn trailing_backslash_flushes_literal() {
1124        let env = HashMap::new();
1125        let expander = StreamingExpand::new(&[], &env);
1126        let result = expander.expand_string("end\\").unwrap();
1127        assert_eq!(result, "end\\");
1128    }
1129
1130    #[test]
1131    fn backslash_before_other_text_is_literal() {
1132        let env = HashMap::new();
1133        let expander = StreamingExpand::new(&[], &env);
1134        let result = expander.expand_string("a\\b \\{ once }").unwrap();
1135        assert_eq!(result, "a\\b \\{ once }");
1136    }
1137
1138    #[test]
1139    fn escaped_pair_split_across_chunks() {
1140        let mut env = HashMap::new();
1141        env.insert("PROJECT".into(), "OxDock".into());
1142        let mut expander = StreamingExpand::new(&[], &env);
1143        let mut out = Vec::new();
1144
1145        // Split `\\` / `{{ env:PROJECT }}` across chunks: the pair
1146        // completes to one backslash, then the placeholder expands
1147        expander.process_bytes(b"\\", &mut out).unwrap();
1148        expander
1149            .process_bytes(b"\\{{ env:PROJECT }}", &mut out)
1150            .unwrap();
1151        expander.flush(&mut out).unwrap();
1152
1153        assert_eq!(String::from_utf8_lossy(&out), "\\OxDock");
1154    }
1155
1156    #[test]
1157    fn partial_across_chunks() {
1158        let mut env = HashMap::new();
1159        env.insert("NAME".into(), "World".into());
1160        let mut expander = StreamingExpand::new(&[], &env);
1161        let mut out = Vec::new();
1162
1163        // Split `{{ env:NA` / `ME }}` across chunks
1164        expander.process_bytes(b"{{ env:NA", &mut out).unwrap();
1165        expander.process_bytes(b"ME }}", &mut out).unwrap();
1166        expander.flush(&mut out).unwrap();
1167
1168        assert_eq!(String::from_utf8_lossy(&out), "World");
1169    }
1170
1171    #[test]
1172    fn trailing_brace_across_chunks() {
1173        let mut env = HashMap::new();
1174        env.insert("NAME".into(), "World".into());
1175        let mut expander = StreamingExpand::new(&[], &env);
1176        let mut out = Vec::new();
1177
1178        // Split `...{` / `{env:NAME}}` across chunks
1179        expander.process_bytes(b"...", &mut out).unwrap();
1180        expander.process_bytes(b"{", &mut out).unwrap();
1181        expander.process_bytes(b"{env:NAME}}", &mut out).unwrap();
1182        expander.flush(&mut out).unwrap();
1183
1184        assert_eq!(String::from_utf8_lossy(&out), "...World");
1185    }
1186
1187    #[test]
1188    fn trailing_brace_at_eof() {
1189        let env = HashMap::new();
1190        let mut expander = StreamingExpand::new(&[], &env);
1191        let mut out = Vec::new();
1192
1193        expander.process_bytes(b"hello{", &mut out).unwrap();
1194        expander.flush(&mut out).unwrap();
1195
1196        assert_eq!(String::from_utf8_lossy(&out), "hello{");
1197    }
1198
1199    #[test]
1200    fn immediate_flush_guarantee() {
1201        let env = HashMap::new();
1202        let mut expander = StreamingExpand::new(&[], &env);
1203        let mut out = Vec::new();
1204
1205        // 1MB of plain text with no placeholders
1206        let input = std::iter::repeat_n(b'x', 1024 * 1024).collect::<Vec<_>>();
1207        expander.process_bytes(&input, &mut out).unwrap();
1208        expander.flush(&mut out).unwrap();
1209
1210        assert_eq!(out.len(), 1024 * 1024);
1211    }
1212
1213    #[test]
1214    fn nested_braces() {
1215        let mut env = HashMap::new();
1216        env.insert("KEY{1}".into(), "val".into());
1217        let expander = StreamingExpand::new(&[], &env);
1218        let result = expander.expand_string("{{ env:KEY{1} }}").unwrap();
1219        assert_eq!(result, "val");
1220    }
1221
1222    #[test]
1223    fn split_close_delimiter_across_chunks() {
1224        let mut env = HashMap::new();
1225        env.insert("NAME".into(), "World".into());
1226        let mut expander = StreamingExpand::new(&[], &env);
1227        let mut out = Vec::new();
1228
1229        // Split `}}` across chunks: `{{ env:NAME` / `}}`
1230        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
1231        expander.process_bytes(b"}}", &mut out).unwrap();
1232        expander.flush(&mut out).unwrap();
1233
1234        assert_eq!(String::from_utf8_lossy(&out), "World");
1235    }
1236
1237    #[test]
1238    fn split_close_delimiter_with_trailing_content() {
1239        let mut env = HashMap::new();
1240        env.insert("NAME".into(), "World".into());
1241        let mut expander = StreamingExpand::new(&[], &env);
1242        let mut out = Vec::new();
1243
1244        // Split `}}` across chunks with content after
1245        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
1246        expander.process_bytes(b"}} rest", &mut out).unwrap();
1247        expander.flush(&mut out).unwrap();
1248
1249        assert_eq!(String::from_utf8_lossy(&out), "World rest");
1250    }
1251
1252    #[test]
1253    fn empty_input_preserves_pending_state() {
1254        let mut env = HashMap::new();
1255        env.insert("NAME".into(), "World".into());
1256        let mut expander = StreamingExpand::new(&[], &env);
1257        let mut out = Vec::new();
1258
1259        // End chunk with closing byte, then empty input, then confirm
1260        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
1261        expander.process_bytes(b"", &mut out).unwrap(); // empty: should preserve state
1262        expander.process_bytes(b"}}", &mut out).unwrap();
1263        expander.flush(&mut out).unwrap();
1264
1265        assert_eq!(String::from_utf8_lossy(&out), "World");
1266    }
1267
1268    #[test]
1269    fn missing_env_var_errors() {
1270        let env = HashMap::new();
1271        let expander = StreamingExpand::new(&[], &env);
1272        let result = expander.expand_string("{{ env:UNDEFINED_VAR }}");
1273        assert!(result.is_err());
1274        let msg = result.unwrap_err().to_string();
1275        assert!(msg.contains("undefined environment variable"), "got: {msg}");
1276        assert!(msg.contains("UNDEFINED_VAR"), "got: {msg}");
1277    }
1278
1279    #[test]
1280    fn missing_script_var_errors() {
1281        let env = HashMap::new();
1282        let expander = StreamingExpand::new(&[], &env);
1283        let result = expander.expand_string("{{ $undefined_var }}");
1284        assert!(result.is_err());
1285        let msg = result.unwrap_err().to_string();
1286        assert!(msg.contains("undefined script variable"), "got: {msg}");
1287        assert!(msg.contains("$undefined_var"), "got: {msg}");
1288    }
1289
1290    #[test]
1291    fn missing_key_in_map_errors() {
1292        let mut vars = HashMap::new();
1293        vars.insert(
1294            "cfg".into(),
1295            oxdock_parser::Value::map(std::collections::BTreeMap::from([(
1296                "server".into(),
1297                oxdock_parser::Value::map(std::collections::BTreeMap::from([(
1298                    "port".into(),
1299                    oxdock_parser::Value::int(8080),
1300                )])),
1301            )])),
1302        );
1303        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1304        let result = expander.expand_string("{{ $cfg.missing_key }}");
1305        assert!(result.is_err());
1306        let msg = result.unwrap_err().to_string();
1307        assert!(
1308            msg.contains("property 'missing_key' not found"),
1309            "got: {msg}"
1310        );
1311    }
1312
1313    #[test]
1314    fn out_of_bounds_array_index_errors() {
1315        let mut vars = HashMap::new();
1316        vars.insert(
1317            "arr".into(),
1318            oxdock_parser::Value::list(vec![oxdock_parser::Value::string("a".into())]),
1319        );
1320        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1321        let result = expander.expand_string("{{ $arr.5 }}");
1322        assert!(result.is_err());
1323        let msg = result.unwrap_err().to_string();
1324        assert!(msg.contains("index 5 out of bounds"), "got: {msg}");
1325    }
1326
1327    #[test]
1328    fn type_mismatch_navigation_errors() {
1329        let mut vars = HashMap::new();
1330        vars.insert("name".into(), oxdock_parser::Value::string("alice".into()));
1331        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1332        let result = expander.expand_string("{{ $name.sub_field }}");
1333        assert!(result.is_err());
1334        let msg = result.unwrap_err().to_string();
1335        assert!(
1336            msg.contains("cannot access property 'sub_field' on primitive"),
1337            "got: {msg}"
1338        );
1339    }
1340
1341    #[test]
1342    fn unprefixed_identifier_errors() {
1343        let env = HashMap::new();
1344        let expander = StreamingExpand::new(&[], &env);
1345        let result = expander.expand_string("{{ bare_word }}");
1346        assert!(result.is_err());
1347        let msg = result.unwrap_err().to_string();
1348        assert!(msg.contains("missing required step override"), "got: {msg}");
1349    }
1350
1351    // ── Strict namespace isolation tests ─────────────────────────────────────
1352
1353    #[test]
1354    fn script_var_does_not_fall_back_to_env() {
1355        let mut env = HashMap::new();
1356        env.insert("WHO".into(), "from-env".into());
1357        let expander = StreamingExpand::new(&[], &env);
1358        // $WHO queries vars, NOT env : should error even though env has WHO
1359        let result = expander.expand_string("{{ $WHO }}");
1360        assert!(result.is_err());
1361        let msg = result.unwrap_err().to_string();
1362        assert!(msg.contains("undefined script variable"), "got: {msg}");
1363        assert!(
1364            msg.contains("did you mean 'env:WHO'"),
1365            "hint should suggest env: prefix, got: {msg}"
1366        );
1367    }
1368
1369    #[test]
1370    fn env_var_does_not_fall_back_to_vars() {
1371        let mut vars = HashMap::new();
1372        vars.insert(
1373            "HOST".into(),
1374            oxdock_parser::Value::string("from-var".into()),
1375        );
1376        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1377        // env:HOST queries env, NOT vars : should error even though vars has HOST
1378        let result = expander.expand_string("{{ env:HOST }}");
1379        assert!(result.is_err());
1380        let msg = result.unwrap_err().to_string();
1381        assert!(msg.contains("undefined environment variable"), "got: {msg}");
1382        assert!(
1383            msg.contains("did you mean '$HOST'"),
1384            "hint should suggest $ prefix, got: {msg}"
1385        );
1386    }
1387
1388    #[test]
1389    fn step_override_does_not_fall_back_to_vars() {
1390        let mut vars = HashMap::new();
1391        vars.insert("PORT".into(), oxdock_parser::Value::int(8080));
1392        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1393        // PORT (bare) queries overrides, NOT vars : should error
1394        let result = expander.expand_string("{{ PORT }}");
1395        assert!(result.is_err());
1396        let msg = result.unwrap_err().to_string();
1397        assert!(msg.contains("missing required step override"), "got: {msg}");
1398        assert!(
1399            msg.contains("did you mean '$PORT'"),
1400            "hint should suggest $ prefix, got: {msg}"
1401        );
1402    }
1403
1404    #[test]
1405    fn env_prefix_isolated_from_script_vars() {
1406        let mut vars = HashMap::new();
1407        vars.insert("MODE".into(), oxdock_parser::Value::string("dev".into()));
1408        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1409        // env:MODE looks in env, not vars : should error
1410        let result = expander.expand_string("{{ env:MODE }}");
1411        assert!(result.is_err());
1412        let msg = result.unwrap_err().to_string();
1413        assert!(msg.contains("undefined environment variable"), "got: {msg}");
1414        assert!(
1415            msg.contains("did you mean '$MODE'"),
1416            "hint should suggest $ prefix, got: {msg}"
1417        );
1418    }
1419
1420    #[test]
1421    fn dollar_prefix_isolated_from_env() {
1422        let mut env = HashMap::new();
1423        env.insert("PORT".into(), "3000".into());
1424        let expander = StreamingExpand::new(&[], &env);
1425        // $PORT looks in vars, not env : should error
1426        let result = expander.expand_string("{{ $PORT }}");
1427        assert!(result.is_err());
1428        let msg = result.unwrap_err().to_string();
1429        assert!(msg.contains("undefined script variable"), "got: {msg}");
1430        assert!(
1431            msg.contains("did you mean 'env:PORT'"),
1432            "hint should suggest env: prefix, got: {msg}"
1433        );
1434    }
1435
1436    #[test]
1437    fn empty_placeholder_errors() {
1438        let expander = StreamingExpand::new(&[], &HashMap::new());
1439        let result = expander.expand_string("{{ }}");
1440        assert!(result.is_err());
1441        let msg = result.unwrap_err().to_string();
1442        assert!(msg.contains("invalid placeholder format"), "got: {msg}");
1443    }
1444
1445    #[test]
1446    fn malformed_symbol_placeholder_errors() {
1447        let expander = StreamingExpand::new(&[], &HashMap::new());
1448        let result = expander.expand_string("{{ @invalid! }}");
1449        assert!(result.is_err());
1450        let msg = result.unwrap_err().to_string();
1451        assert!(msg.contains("invalid placeholder format"), "got: {msg}");
1452    }
1453
1454    /// Feed input in fixed-size chunks, then flush: exercises every
1455    /// chunk-boundary alignment for the given split size.
1456    fn render_split(
1457        input: &[u8],
1458        size: usize,
1459        env: &HashMap<String, String>,
1460    ) -> Result<String, anyhow::Error> {
1461        let mut expander = StreamingExpand::new(&[], env);
1462        let mut out = Vec::new();
1463        for chunk in input.chunks(size) {
1464            expander.process_bytes(chunk, &mut out)?;
1465        }
1466        expander.flush(&mut out)?;
1467        Ok(String::from_utf8_lossy(&out).into_owned())
1468    }
1469
1470    #[test]
1471    fn escaped_opener_one_byte_chunks_stays_literal() {
1472        let mut env = HashMap::new();
1473        env.insert("NAME".into(), "World".into());
1474        // Every byte arrives alone: `\` | `{` | `{` | ... must still
1475        // resolve to a literal opener, never an expansion.
1476        let out = render_split(b"\\{{ env:NAME }}", 1, &env).unwrap();
1477        assert_eq!(out, "{{ env:NAME }}");
1478    }
1479
1480    #[test]
1481    fn escaped_opener_two_byte_chunks_stays_literal() {
1482        let mut env = HashMap::new();
1483        env.insert("NAME".into(), "World".into());
1484        // Two-byte splits land `\{` and lone `{` at chunk ends.
1485        let out = render_split(b"a\\{{ env:NAME }}b", 2, &env).unwrap();
1486        assert_eq!(out, "a{{ env:NAME }}b");
1487    }
1488
1489    #[test]
1490    fn escaped_opener_split_variants_stay_literal() {
1491        let mut env = HashMap::new();
1492        env.insert("NAME".into(), "World".into());
1493        for chunks in [
1494            vec![b"\\".as_slice(), b"{", b"{ env:NAME }}"],
1495            vec![b"\\{".as_slice(), b"{ env:NAME }}"],
1496            vec![b"\\{{ env:NAME ".as_slice(), b"}}"],
1497        ] {
1498            let mut expander = StreamingExpand::new(&[], &env);
1499            let mut out = Vec::new();
1500            for chunk in chunks {
1501                expander.process_bytes(chunk, &mut out).unwrap();
1502            }
1503            expander.flush(&mut out).unwrap();
1504            assert_eq!(
1505                String::from_utf8_lossy(&out),
1506                "{{ env:NAME }}",
1507                "chunks must not corrupt the escape"
1508            );
1509        }
1510    }
1511
1512    #[test]
1513    fn plain_opener_split_chunks_still_expands() {
1514        let mut env = HashMap::new();
1515        env.insert("NAME".into(), "World".into());
1516        // The fix must not swallow genuine openers fragmented the
1517        // same way: `{` | `{` opens, then the key resolves.
1518        let out = render_split(b"{{ env:NAME }}", 1, &env).unwrap();
1519        assert_eq!(out, "World");
1520    }
1521
1522    #[test]
1523    fn double_backslash_split_chunks_still_expands() {
1524        let mut env = HashMap::new();
1525        env.insert("NAME".into(), "World".into());
1526        // `\\` completes to one backslash; the opener after it expands.
1527        let out = render_split(b"\\\\{{ env:NAME }}", 1, &env).unwrap();
1528        assert_eq!(out, "\\World");
1529    }
1530
1531    #[test]
1532    fn trailing_escape_brace_flushes_literal() {
1533        let env = HashMap::new();
1534        let expander = StreamingExpand::new(&[], &env);
1535        let result = expander.expand_string("end\\{").unwrap();
1536        assert_eq!(result, "end\\{");
1537    }
1538
1539    // ── Single-pass substitution tests ────────────────────────────────────
1540    // Substituted values are emitted verbatim and never re-scanned for
1541    // `{{ ... }}`. These pin the top-level-only behavior: a value that
1542    // itself contains a placeholder stays literal instead of expanding.
1543
1544    #[test]
1545    fn substituted_override_value_is_not_rescanned() {
1546        let mut env = HashMap::new();
1547        env.insert("OTHER".into(), "world".into());
1548        let overrides = vec![("NAME".into(), "{{ env:OTHER }}".into())];
1549        let expander = StreamingExpand::new(&overrides, &env);
1550        let result = expander.expand_string("Hello {{ NAME }}").unwrap();
1551        assert_eq!(result, "Hello {{ env:OTHER }}");
1552    }
1553
1554    #[test]
1555    fn substituted_env_value_is_not_rescanned() {
1556        let mut env = HashMap::new();
1557        env.insert("NAME".into(), "{{ env:OTHER }}".into());
1558        env.insert("OTHER".into(), "world".into());
1559        let expander = StreamingExpand::new(&[], &env);
1560        let result = expander.expand_string("Hello {{ env:NAME }}").unwrap();
1561        assert_eq!(result, "Hello {{ env:OTHER }}");
1562    }
1563
1564    #[test]
1565    fn substituted_script_var_value_is_not_rescanned() {
1566        let mut vars = HashMap::new();
1567        vars.insert(
1568            "inner".into(),
1569            oxdock_parser::Value::string("{{ env:OTHER }}".into()),
1570        );
1571        let mut env = HashMap::new();
1572        env.insert("OTHER".into(), "world".into());
1573        let expander = StreamingExpand::new(&[], &env).with_vars(&vars);
1574        let result = expander.expand_string("Hello {{ $inner }}").unwrap();
1575        assert_eq!(result, "Hello {{ env:OTHER }}");
1576    }
1577
1578    /// Echo resolver returning the debug shape of each argument, so
1579    /// literal parsing asserts on values instead of formatting.
1580    fn shape_resolver() -> PlaceholderCall {
1581        Arc::new(|module, func, args| {
1582            if module == "T" && func == "SHAPE" {
1583                let shape = args
1584                    .iter()
1585                    .map(|arg| arg.type_name().to_string())
1586                    .collect::<Vec<_>>()
1587                    .join(",");
1588                return Ok(oxdock_parser::Value::string(shape));
1589            }
1590            bail!("unknown placeholder function '{module}::{func}'")
1591        })
1592    }
1593
1594    #[test]
1595    fn placeholder_call_with_empty_map_literal() {
1596        let expander =
1597            StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1598        let result = expander.expand_string("{{ T::SHAPE({}) }}").unwrap();
1599        assert_eq!(result, "MAP");
1600    }
1601
1602    #[test]
1603    fn placeholder_call_with_map_and_list_literals() {
1604        let expander =
1605            StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1606        let result = expander
1607            .expand_string("{{ T::SHAPE({a: 1, b: \"x\"}, [1, true]) }}")
1608            .unwrap();
1609        assert_eq!(result, "MAP,LIST");
1610    }
1611
1612    #[test]
1613    fn placeholder_call_map_commas_nest_inside_literals() {
1614        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1615            let map = args[0].as_map().expect("map");
1616            let format = map
1617                .get("format")
1618                .and_then(|v| v.as_str())
1619                .expect("format string");
1620            Ok(oxdock_parser::Value::string(format.to_string()))
1621        });
1622        let expander = StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(resolver);
1623        let result = expander
1624            .expand_string("{{ T::SHAPE({min_level: 2, format: \"a,b\"}) }}")
1625            .unwrap();
1626        assert_eq!(result, "a,b");
1627    }
1628
1629    #[test]
1630    fn placeholder_call_map_values_accept_var_refs_and_nesting() {
1631        let mut vars = HashMap::new();
1632        vars.insert("depth".into(), oxdock_parser::Value::int(2));
1633        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1634            let map = args[0].as_map().expect("map");
1635            let depth = map.get("n").and_then(|v| v.as_i64()).expect("int");
1636            let tags = map.get("tags").and_then(|v| v.as_list()).expect("list");
1637            Ok(oxdock_parser::Value::string(format!(
1638                "{depth}:{}",
1639                tags.len()
1640            )))
1641        });
1642        let expander = StreamingExpand::new(&[], &HashMap::new())
1643            .with_vars(&vars)
1644            .with_call_resolver(resolver);
1645        let result = expander
1646            .expand_string("{{ T::SHAPE({n: $depth, tags: [\"a\", \"b\"]}) }}")
1647            .unwrap();
1648        assert_eq!(result, "2:2");
1649    }
1650
1651    #[test]
1652    fn placeholder_call_rejects_malformed_literals() {
1653        for bad in [
1654            "{{ T::SHAPE({a}) }}",
1655            "{{ T::SHAPE({a: 1, a: 2}) }}",
1656            "{{ T::SHAPE({\"a\": 1: 2}) }}",
1657            "{{ T::SHAPE([1) }}",
1658            "{{ T::SHAPE({a: 1) }}",
1659        ] {
1660            let expander =
1661                StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1662            assert!(expander.expand_string(bad).is_err(), "must fail: {bad}");
1663        }
1664    }
1665}