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 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 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/// Split a `MODULE::FUNC(args)` placeholder body for call resolution
466/// outside the streaming expander. Returns `None` when the body is not
467/// call shaped, so plain keys keep their own handling. Shared with
468/// engine-side string expansion so both paths parse identically.
469pub fn parse_placeholder_call(key: &str) -> Option<(String, String, Vec<String>)> {
470    let (module, func, args) = parse_call(key.trim())?;
471    Some((module.to_string(), func.to_string(), args))
472}
473
474/// Maximum nesting for map and list literals in placeholder call args.
475const MAX_LITERAL_DEPTH: usize = 16;
476
477/// Split call args on top level commas, keeping quoted strings and
478/// `{...}` / `[...]` literals intact. Commas nested inside literals
479/// belong to the literal, not the argument list. Nested calls stay
480/// rejected: only data literals nest, never `MODULE::FUNC(...)`.
481fn split_args(src: &str) -> Vec<String> {
482    split_top_level(src, ',')
483}
484
485/// Split on a top level separator, keeping quoted strings and
486/// `{...}` / `[...]` literals intact.
487fn split_top_level(src: &str, sep: char) -> Vec<String> {
488    let mut out = Vec::new();
489    let mut current = String::new();
490    let mut in_string = false;
491    let mut escaped = false;
492    let mut depth: usize = 0;
493    for c in src.chars() {
494        if in_string {
495            current.push(c);
496            if escaped {
497                escaped = false;
498            } else if c == '\\' {
499                escaped = true;
500            } else if c == '"' {
501                in_string = false;
502            }
503            continue;
504        }
505        match c {
506            '"' => {
507                in_string = true;
508                current.push(c);
509            }
510            '{' | '[' => {
511                depth += 1;
512                current.push(c);
513            }
514            '}' | ']' => {
515                depth = depth.saturating_sub(1);
516                current.push(c);
517            }
518            _ if c == sep && depth == 0 => {
519                out.push(current.trim().to_string());
520                current.clear();
521            }
522            _ => current.push(c),
523        }
524    }
525    let last = current.trim();
526    if !(out.is_empty() && last.is_empty()) {
527        out.push(last.to_string());
528    }
529    out
530}
531
532/// Resolve one placeholder call argument against script variables for
533/// call resolution outside the streaming expander. Same grammar there:
534/// `$var.path`, string, int, float, and bool literals, plus `{...}`
535/// and `[...]` literals holding those shapes nested.
536pub fn resolve_placeholder_arg(
537    src: &str,
538    vars: &HashMap<String, oxdock_parser::Value>,
539) -> Result<oxdock_parser::Value> {
540    resolve_call_arg(src, vars)
541}
542
543/// Resolve one call argument to a value: `$var.path` from vars, a
544/// string, int, float, or bool literal, or a `{key: value}` map or
545/// `[item]` list literal holding those same shapes nested.
546fn resolve_call_arg(
547    src: &str,
548    vars: &HashMap<String, oxdock_parser::Value>,
549) -> Result<oxdock_parser::Value> {
550    resolve_call_value(src, vars, 0)
551}
552
553fn resolve_call_value(
554    src: &str,
555    vars: &HashMap<String, oxdock_parser::Value>,
556    depth: usize,
557) -> Result<oxdock_parser::Value> {
558    if depth > MAX_LITERAL_DEPTH {
559        bail!("placeholder call argument nests too deep (limit {MAX_LITERAL_DEPTH})");
560    }
561    if let Some(path) = src.strip_prefix('$') {
562        let parts: Vec<&str> = path.split('.').collect();
563        return resolve_value_path(&parts, vars);
564    }
565    if src.len() >= 2 && src.starts_with('"') && src.ends_with('"') {
566        return Ok(oxdock_parser::Value::string(unescape_literal(
567            &src[1..src.len() - 1],
568        )?));
569    }
570    if let Some(inner) = strip_wrapped(src, '{', '}') {
571        return resolve_call_map(inner, vars, depth);
572    }
573    if let Some(inner) = strip_wrapped(src, '[', ']') {
574        return resolve_call_list(inner, vars, depth);
575    }
576    match src {
577        "true" => return Ok(oxdock_parser::Value::bool(true)),
578        "false" => return Ok(oxdock_parser::Value::bool(false)),
579        _ => {}
580    }
581    if let Ok(i) = src.parse::<i64>() {
582        return Ok(oxdock_parser::Value::int(i));
583    }
584    if let Ok(f) = src.parse::<f64>() {
585        return Ok(oxdock_parser::Value::float(f));
586    }
587    bail!(
588        "invalid placeholder call argument '{src}': use $var.path, a string, int, float, or bool literal, or a {{key: value}} or [item] literal"
589    )
590}
591
592/// Strip one wrapping delimiter pair, rejecting unbalanced closers
593/// inside: the opener at 0 must match the closer at the end with no
594/// earlier top level closer.
595fn strip_wrapped(src: &str, open: char, close: char) -> Option<&str> {
596    if !src.starts_with(open) || !src.ends_with(close) || src.len() < 2 {
597        return None;
598    }
599    let mut in_string = false;
600    let mut escaped = false;
601    let mut depth: usize = 0;
602    for (idx, c) in src.char_indices() {
603        if in_string {
604            if escaped {
605                escaped = false;
606            } else if c == '\\' {
607                escaped = true;
608            } else if c == '"' {
609                in_string = false;
610            }
611            continue;
612        }
613        match c {
614            '"' => in_string = true,
615            _ if c == open => depth += 1,
616            _ if c == close => {
617                depth -= 1;
618                if depth == 0 && idx != src.len() - close.len_utf8() {
619                    return None;
620                }
621            }
622            _ => {}
623        }
624    }
625    if depth != 0 {
626        return None;
627    }
628    Some(&src[open.len_utf8()..src.len() - close.len_utf8()])
629}
630
631/// Resolve a `{key: value}` map literal. Keys are bare ASCII
632/// identifiers or double quoted strings; values recurse through
633/// [`resolve_call_value`].
634fn resolve_call_map(
635    inner: &str,
636    vars: &HashMap<String, oxdock_parser::Value>,
637    depth: usize,
638) -> Result<oxdock_parser::Value> {
639    let mut entries = std::collections::BTreeMap::new();
640    if inner.trim().is_empty() {
641        return Ok(oxdock_parser::Value::map(entries));
642    }
643    for entry in split_top_level(inner, ',') {
644        let parts = split_top_level(&entry, ':');
645        if parts.len() != 2 {
646            bail!("invalid map literal entry '{entry}': use key: value");
647        }
648        let key = resolve_call_key(&parts[0])?;
649        if entries.contains_key(&key) {
650            bail!("duplicate key '{key}' in map literal");
651        }
652        let value = resolve_call_value(&parts[1], vars, depth + 1)?;
653        entries.insert(key, value);
654    }
655    Ok(oxdock_parser::Value::map(entries))
656}
657
658/// Resolve one map literal key: a bare ASCII identifier or a double
659/// quoted string.
660fn resolve_call_key(src: &str) -> Result<String> {
661    if src.len() >= 2 && src.starts_with('"') && src.ends_with('"') {
662        return unescape_literal(&src[1..src.len() - 1]);
663    }
664    if !src.is_empty() && src.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
665        return Ok(src.to_string());
666    }
667    bail!("invalid map literal key '{src}': use name or \"name\"")
668}
669
670/// Resolve a `[item]` list literal, elements recursing through
671/// [`resolve_call_value`].
672fn resolve_call_list(
673    inner: &str,
674    vars: &HashMap<String, oxdock_parser::Value>,
675    depth: usize,
676) -> Result<oxdock_parser::Value> {
677    let mut items = Vec::new();
678    if inner.trim().is_empty() {
679        return Ok(oxdock_parser::Value::list(items));
680    }
681    for item in split_top_level(inner, ',') {
682        items.push(resolve_call_value(&item, vars, depth + 1)?);
683    }
684    Ok(oxdock_parser::Value::list(items))
685}
686
687/// Unescape a double quoted literal: `\\` and `\"` only. Anything else
688/// keeps its backslash so template text stays predictable.
689fn unescape_literal(src: &str) -> Result<String> {
690    let mut out = String::with_capacity(src.len());
691    let mut chars = src.chars();
692    while let Some(c) = chars.next() {
693        if c != '\\' {
694            out.push(c);
695            continue;
696        }
697        match chars.next() {
698            Some('\\') => out.push('\\'),
699            Some('"') => out.push('"'),
700            Some(other) => {
701                out.push('\\');
702                out.push(other);
703            }
704            None => bail!("unterminated escape in placeholder string literal"),
705        }
706    }
707    Ok(out)
708}
709
710/// Resolve a dotted path against vars, cloning the value for the caller.
711/// Mirrors `resolve_key_path_strict` but returns the value instead of
712/// its string form so calls receive typed arguments.
713fn resolve_value_path(
714    parts: &[&str],
715    vars: &HashMap<String, oxdock_parser::Value>,
716) -> Result<oxdock_parser::Value> {
717    if parts.is_empty() || parts[0].is_empty() {
718        bail!("invalid placeholder call argument: empty variable reference");
719    }
720    let root_key = parts[0];
721    let mut current = vars
722        .get(root_key)
723        .ok_or_else(|| anyhow!("undefined script variable: '${root_key}'"))?
724        .clone();
725    for &segment in &parts[1..] {
726        if segment.contains('(') || segment.contains(')') {
727            bail!("nested calls are not supported in placeholder arguments");
728        }
729        if let Some(map) = current.as_map() {
730            current = map
731                .get(segment)
732                .ok_or_else(|| anyhow!("property '{segment}' not found on object '${root_key}'"))?
733                .clone();
734        } else if let Some(list) = current.as_list() {
735            let idx: usize = segment
736                .parse()
737                .map_err(|_| anyhow!("invalid array index '{segment}' on list '${root_key}'"))?;
738            current = list
739                .get(idx)
740                .ok_or_else(|| {
741                    anyhow!(
742                        "index {idx} out of bounds for list '${root_key}' (len: {})",
743                        list.len()
744                    )
745                })?
746                .clone();
747        } else {
748            bail!("cannot access property '{segment}' on primitive value of '${root_key}'")
749        }
750    }
751    Ok(current)
752}
753
754/// Resolve nested key-paths against the vars map.
755///
756/// Fails explicitly on missing object keys, out-of-bounds array indices,
757/// or type mismatches (e.g. trying to access a property on a primitive).
758fn resolve_key_path_strict(
759    parts: &[&str],
760    vars: &HashMap<String, oxdock_parser::Value>,
761) -> Result<String> {
762    let root_key = parts[0];
763    let mut current = vars
764        .get(root_key)
765        .ok_or_else(|| anyhow!("undefined script variable: '${root_key}'"))?;
766
767    for &segment in &parts[1..] {
768        if let Some(map) = current.as_map() {
769            current = map
770                .get(segment)
771                .ok_or_else(|| anyhow!("property '{segment}' not found on object '${root_key}'"))?;
772        } else if let Some(list) = current.as_list() {
773            let idx: usize = segment
774                .parse()
775                .map_err(|_| anyhow!("invalid array index '{segment}' on list '${root_key}'"))?;
776            current = list.get(idx).ok_or_else(|| {
777                anyhow!(
778                    "index {idx} out of bounds for list '${root_key}' (len: {})",
779                    list.len()
780                )
781            })?;
782        } else {
783            bail!("cannot access property '{segment}' on primitive value of '${root_key}'")
784        }
785    }
786
787    format_value_for_string(current)
788}
789
790/// Format a Value as a string for inline interpolation.
791/// Render a script value as inline text: the single renderer behind
792/// placeholder expansion everywhere (streaming file templates and
793/// engine string expansion alike), so one value renders one way in
794/// every context. Pipes are refused: they carry streams between
795/// steps, not text, and silently rendering a handle hides a bug.
796///
797/// Float rendering is defined as `f.to_string()`: Rust's `Display` for
798/// `f64` already produces the shortest round-trip decimal (Ryū since
799/// 1.36), so `ECHO` / `{{ }}` output stays clean (`3.14`, not
800/// `3.140000`) with no extra dependency.
801pub fn format_value_for_string(val: &oxdock_parser::Value) -> anyhow::Result<String> {
802    if let Some(s) = val.as_str() {
803        return Ok(s.to_string());
804    }
805    if let Some(i) = val.as_i64() {
806        return Ok(i.to_string());
807    }
808    if let Some(f) = val.as_f64() {
809        return Ok(f.to_string());
810    }
811    if let Some(b) = val.as_bool() {
812        return Ok(b.to_string());
813    }
814    if val.as_pipe_handle().is_some() {
815        anyhow::bail!(
816            "cannot render PIPE as STRING: pipes carry streams between steps, not text. Capture the producing step's output with LET $var: STRING = ... instead."
817        );
818    }
819    if val.as_semaphore().is_some() {
820        anyhow::bail!(
821            "cannot render SEMAPHORE as STRING: semaphores coordinate task access between steps, not text."
822        );
823    }
824    if val.as_permit().is_some() {
825        anyhow::bail!(
826            "cannot render PERMIT as STRING: permits grant scoped task access, not text."
827        );
828    }
829    if let Some(d) = val.as_duration() {
830        return Ok(oxdock_parser::command::format_duration(&d));
831    }
832    if let Some(p) = val.as_path() {
833        return Ok(p.to_string_lossy().to_string());
834    }
835    if let Some(items) = val.as_list() {
836        let parts: Vec<String> = items
837            .iter()
838            .map(format_value_for_string)
839            .collect::<anyhow::Result<_>>()?;
840        return Ok(parts.join(" "));
841    }
842    if let Some(map) = val.as_map() {
843        let mut parts = Vec::with_capacity(map.len());
844        for (k, v) in map.iter() {
845            parts.push(format!("\"{}\": {}", k, format_value_for_string(v)?));
846        }
847        return Ok(parts.join(", "));
848    }
849    if let Some(id) = val.as_handle() {
850        return Ok(format!("task#{}", id));
851    }
852    Ok(format!("{}", val))
853}
854
855// Legacy functions for backward compatibility
856
857pub(crate) fn expand_with_lookup<F>(input: &str, mut lookup_fn: F) -> String
858where
859    F: FnMut(&str) -> Option<String>,
860{
861    let mut out = String::with_capacity(input.len());
862    let mut chars = input.chars().peekable();
863    while let Some(c) = chars.next() {
864        if c == '{' {
865            if let Some(&'{') = chars.peek() {
866                chars.next(); // consume second '{'
867                let mut content = String::new();
868                let mut closed = false;
869                // Look ahead for closing }}
870                let mut inner_chars = chars.clone();
871                while let Some(ch) = inner_chars.next() {
872                    if ch == '}'
873                        && let Some(&'}') = inner_chars.peek()
874                    {
875                        closed = true;
876                        break;
877                    }
878                    content.push(ch);
879                }
880
881                if closed {
882                    // Advance main iterator past content and closing braces.
883                    // Count chars, not bytes: content may contain multi-byte
884                    // UTF-8 (e.g. non-ASCII placeholder names).
885                    for _ in 0..content.chars().count() {
886                        chars.next();
887                    }
888                    chars.next(); // first }
889                    chars.next(); // second }
890
891                    let key = content.trim();
892                    if !key.is_empty() {
893                        out.push_str(&lookup_fn(key).unwrap_or_default());
894                    }
895                } else {
896                    out.push('{');
897                    out.push('{');
898                }
899            } else {
900                out.push('{');
901            }
902        } else {
903            out.push(c);
904        }
905    }
906    out
907}
908
909pub fn expand_script_env(input: &str, script_envs: &HashMap<String, String>) -> String {
910    expand_with_lookup(input, |name| {
911        if let Some(key) = name.strip_prefix("env:") {
912            script_envs
913                .get(key)
914                .cloned()
915                .or_else(|| std::env::var(key).ok())
916        } else {
917            None
918        }
919    })
920}
921
922pub fn expand_command_env(input: &str, ctx: &CommandContext) -> String {
923    expand_with_lookup(input, |name| {
924        if let Some(key) = name.strip_prefix("env:") {
925            ctx.envs().get(key).cloned()
926        } else {
927            None
928        }
929    })
930}
931
932#[cfg(test)]
933mod tests {
934    use super::*;
935    use std::collections::HashMap;
936
937    #[test]
938    fn basic_expansion() {
939        let mut env = HashMap::new();
940        env.insert("NAME".into(), "World".into());
941        let expander = StreamingExpand::new(&[], &env);
942        let result = expander.expand_string("Hello {{ env:NAME }}").unwrap();
943        assert_eq!(result, "Hello World");
944    }
945
946    #[test]
947    fn multiple_vars() {
948        let mut env = HashMap::new();
949        env.insert("A".into(), "X".into());
950        env.insert("B".into(), "Y".into());
951        let expander = StreamingExpand::new(&[], &env);
952        let result = expander
953            .expand_string("{{ env:A }} and {{ env:B }}")
954            .unwrap();
955        assert_eq!(result, "X and Y");
956    }
957
958    #[test]
959    fn missing_var() {
960        let env = HashMap::new();
961        let expander = StreamingExpand::new(&[], &env);
962        let result = expander.expand_string("{{ env:MISSING }}");
963        assert!(result.is_err());
964        assert!(
965            result
966                .unwrap_err()
967                .to_string()
968                .contains("undefined environment variable"),
969            "error should mention undefined environment variable"
970        );
971    }
972
973    #[test]
974    fn no_placeholders() {
975        let env = HashMap::new();
976        let expander = StreamingExpand::new(&[], &env);
977        let result = expander.expand_string("plain text").unwrap();
978        assert_eq!(result, "plain text");
979    }
980
981    #[test]
982    fn empty_input() {
983        let env = HashMap::new();
984        let expander = StreamingExpand::new(&[], &env);
985        let result = expander.expand_string("").unwrap();
986        assert_eq!(result, "");
987    }
988
989    #[test]
990    fn override_precedence() {
991        let mut env = HashMap::new();
992        env.insert("KEY".into(), "envval".into());
993        let overrides = vec![("KEY".into(), "override".into())];
994        let expander = StreamingExpand::new(&overrides, &env);
995        let result = expander.expand_string("{{ env:KEY }}").unwrap();
996        assert_eq!(result, "override");
997    }
998
999    #[test]
1000    fn override_with_namespace() {
1001        let mut env = HashMap::new();
1002        env.insert("CRATE".into(), "envval".into());
1003        let overrides = vec![("CRATE".into(), "override".into())];
1004        let expander = StreamingExpand::new(&overrides, &env);
1005        let result = expander.expand_string("{{ env:CRATE }}").unwrap();
1006        assert_eq!(result, "override");
1007    }
1008
1009    #[test]
1010    fn override_raw_key_match() {
1011        let mut env = HashMap::new();
1012        env.insert("CRATE".into(), "envval".into());
1013        let overrides = vec![("env:CRATE".into(), "override".into())];
1014        let expander = StreamingExpand::new(&overrides, &env);
1015        let result = expander.expand_string("{{ env:CRATE }}").unwrap();
1016        assert_eq!(result, "override");
1017    }
1018
1019    #[test]
1020    fn unclosed_placeholder() {
1021        let env = HashMap::new();
1022        let expander = StreamingExpand::new(&[], &env);
1023        let result = expander.expand_string("{{ env:KEY").unwrap();
1024        assert_eq!(result, "{{ env:KEY");
1025    }
1026
1027    #[test]
1028    fn unclosed_with_prefix() {
1029        let env = HashMap::new();
1030        let expander = StreamingExpand::new(&[], &env);
1031        let result = expander.expand_string("Hello {{ env:KEY").unwrap();
1032        assert_eq!(result, "Hello {{ env:KEY");
1033    }
1034
1035    #[test]
1036    fn buffer_limit_exceeded() {
1037        let env = HashMap::new();
1038        let expander = StreamingExpand::new(&[], &env);
1039        // Create input with `{{` followed by >1024 bytes without `}}`
1040        let mut input = b"{{ ".to_vec();
1041        input.extend(std::iter::repeat_n(b'x', 2000));
1042        let result = expander
1043            .expand_string(&String::from_utf8_lossy(&input))
1044            .unwrap();
1045        // Should flush as literal with `{{` prefix
1046        assert!(result.starts_with("{{ "));
1047        assert!(result.len() > 1024);
1048    }
1049
1050    #[test]
1051    fn escaped_opener_emits_literal() {
1052        let mut env = HashMap::new();
1053        env.insert("PROJECT".into(), "OxDock".into());
1054        let expander = StreamingExpand::new(&[], &env);
1055        let result = expander
1056            .expand_string("Built with \\{{ env:PROJECT }}")
1057            .unwrap();
1058        assert_eq!(result, "Built with {{ env:PROJECT }}");
1059    }
1060
1061    /// Stub resolver echoing `upper` over one string arg, for call tests.
1062    fn shout_resolver() -> PlaceholderCall {
1063        Arc::new(|module, func, args| {
1064            if module == "T" && func == "SHOUT" && args.len() == 1 {
1065                let s = args[0]
1066                    .as_str()
1067                    .ok_or_else(|| anyhow!("SHOUT expects a string"))?;
1068                return Ok(oxdock_parser::Value::string(s.to_uppercase()));
1069            }
1070            bail!("unknown placeholder function '{module}::{func}'")
1071        })
1072    }
1073
1074    #[test]
1075    fn placeholder_call_with_var_arg() {
1076        let env = HashMap::new();
1077        let mut vars = HashMap::new();
1078        vars.insert(
1079            "who".to_string(),
1080            oxdock_parser::Value::string("bob".to_string()),
1081        );
1082        let expander = StreamingExpand::new(&[], &env)
1083            .with_vars(&vars)
1084            .with_call_resolver(shout_resolver());
1085        let result = expander.expand_string("hi {{ T::SHOUT($who) }}!").unwrap();
1086        assert_eq!(result, "hi BOB!");
1087    }
1088
1089    #[test]
1090    fn placeholder_call_with_literal_args() {
1091        let env = HashMap::new();
1092        let expander = StreamingExpand::new(&[], &env).with_call_resolver(shout_resolver());
1093        let result = expander
1094            .expand_string("{{ T::SHOUT(\"bob\") }} {{ T::SHOUT( \"ann\" ) }}")
1095            .unwrap();
1096        assert_eq!(result, "BOB ANN");
1097    }
1098
1099    #[test]
1100    fn placeholder_call_output_stays_literal() {
1101        // Call output containing `{{ }}` is terminal text, never re-expanded.
1102        let env = HashMap::new();
1103        let mut vars = HashMap::new();
1104        vars.insert(
1105            "any".to_string(),
1106            oxdock_parser::Value::string("v".to_string()),
1107        );
1108        let resolver: PlaceholderCall = Arc::new(|_, _, _| {
1109            Ok(oxdock_parser::Value::string(
1110                "x {{ env:NOPE }} y".to_string(),
1111            ))
1112        });
1113        let expander = StreamingExpand::new(&[], &env)
1114            .with_vars(&vars)
1115            .with_call_resolver(resolver);
1116        let result = expander.expand_string("{{ T::SHOUT($any) }}").unwrap();
1117        assert_eq!(result, "x {{ env:NOPE }} y");
1118    }
1119
1120    #[test]
1121    fn placeholder_call_unknown_function_fails() {
1122        let env = HashMap::new();
1123        let expander = StreamingExpand::new(&[], &env).with_call_resolver(shout_resolver());
1124        let result = expander.expand_string("{{ T::NOPE($x) }}");
1125        assert!(result.is_err());
1126    }
1127
1128    #[test]
1129    fn placeholder_call_without_resolver_fails() {
1130        let env = HashMap::new();
1131        let expander = StreamingExpand::new(&[], &env);
1132        let result = expander.expand_string("{{ T::SHOUT($x) }}");
1133        assert!(result.is_err());
1134    }
1135
1136    #[test]
1137    fn escaped_opener_across_chunks() {
1138        let mut env = HashMap::new();
1139        env.insert("PROJECT".into(), "OxDock".into());
1140        let mut expander = StreamingExpand::new(&[], &env);
1141        let mut out = Vec::new();
1142
1143        // Split `\` / `{{ env:PROJECT }}` across chunks
1144        expander.process_bytes(b"Built with \\", &mut out).unwrap();
1145        expander
1146            .process_bytes(b"{{ env:PROJECT }}", &mut out)
1147            .unwrap();
1148        expander.flush(&mut out).unwrap();
1149
1150        assert_eq!(
1151            String::from_utf8_lossy(&out),
1152            "Built with {{ env:PROJECT }}"
1153        );
1154    }
1155
1156    #[test]
1157    fn double_backslash_then_placeholder_expands() {
1158        let mut env = HashMap::new();
1159        env.insert("PROJECT".into(), "OxDock".into());
1160        let expander = StreamingExpand::new(&[], &env);
1161        let result = expander.expand_string("\\\\{{ env:PROJECT }}").unwrap();
1162        assert_eq!(result, "\\OxDock");
1163    }
1164
1165    #[test]
1166    fn trailing_backslash_flushes_literal() {
1167        let env = HashMap::new();
1168        let expander = StreamingExpand::new(&[], &env);
1169        let result = expander.expand_string("end\\").unwrap();
1170        assert_eq!(result, "end\\");
1171    }
1172
1173    #[test]
1174    fn backslash_before_other_text_is_literal() {
1175        let env = HashMap::new();
1176        let expander = StreamingExpand::new(&[], &env);
1177        let result = expander.expand_string("a\\b \\{ once }").unwrap();
1178        assert_eq!(result, "a\\b \\{ once }");
1179    }
1180
1181    #[test]
1182    fn escaped_pair_split_across_chunks() {
1183        let mut env = HashMap::new();
1184        env.insert("PROJECT".into(), "OxDock".into());
1185        let mut expander = StreamingExpand::new(&[], &env);
1186        let mut out = Vec::new();
1187
1188        // Split `\\` / `{{ env:PROJECT }}` across chunks: the pair
1189        // completes to one backslash, then the placeholder expands
1190        expander.process_bytes(b"\\", &mut out).unwrap();
1191        expander
1192            .process_bytes(b"\\{{ env:PROJECT }}", &mut out)
1193            .unwrap();
1194        expander.flush(&mut out).unwrap();
1195
1196        assert_eq!(String::from_utf8_lossy(&out), "\\OxDock");
1197    }
1198
1199    #[test]
1200    fn partial_across_chunks() {
1201        let mut env = HashMap::new();
1202        env.insert("NAME".into(), "World".into());
1203        let mut expander = StreamingExpand::new(&[], &env);
1204        let mut out = Vec::new();
1205
1206        // Split `{{ env:NA` / `ME }}` across chunks
1207        expander.process_bytes(b"{{ env:NA", &mut out).unwrap();
1208        expander.process_bytes(b"ME }}", &mut out).unwrap();
1209        expander.flush(&mut out).unwrap();
1210
1211        assert_eq!(String::from_utf8_lossy(&out), "World");
1212    }
1213
1214    #[test]
1215    fn trailing_brace_across_chunks() {
1216        let mut env = HashMap::new();
1217        env.insert("NAME".into(), "World".into());
1218        let mut expander = StreamingExpand::new(&[], &env);
1219        let mut out = Vec::new();
1220
1221        // Split `...{` / `{env:NAME}}` across chunks
1222        expander.process_bytes(b"...", &mut out).unwrap();
1223        expander.process_bytes(b"{", &mut out).unwrap();
1224        expander.process_bytes(b"{env:NAME}}", &mut out).unwrap();
1225        expander.flush(&mut out).unwrap();
1226
1227        assert_eq!(String::from_utf8_lossy(&out), "...World");
1228    }
1229
1230    #[test]
1231    fn trailing_brace_at_eof() {
1232        let env = HashMap::new();
1233        let mut expander = StreamingExpand::new(&[], &env);
1234        let mut out = Vec::new();
1235
1236        expander.process_bytes(b"hello{", &mut out).unwrap();
1237        expander.flush(&mut out).unwrap();
1238
1239        assert_eq!(String::from_utf8_lossy(&out), "hello{");
1240    }
1241
1242    #[test]
1243    fn immediate_flush_guarantee() {
1244        let env = HashMap::new();
1245        let mut expander = StreamingExpand::new(&[], &env);
1246        let mut out = Vec::new();
1247
1248        // 1MB of plain text with no placeholders
1249        let input = std::iter::repeat_n(b'x', 1024 * 1024).collect::<Vec<_>>();
1250        expander.process_bytes(&input, &mut out).unwrap();
1251        expander.flush(&mut out).unwrap();
1252
1253        assert_eq!(out.len(), 1024 * 1024);
1254    }
1255
1256    #[test]
1257    fn nested_braces() {
1258        let mut env = HashMap::new();
1259        env.insert("KEY{1}".into(), "val".into());
1260        let expander = StreamingExpand::new(&[], &env);
1261        let result = expander.expand_string("{{ env:KEY{1} }}").unwrap();
1262        assert_eq!(result, "val");
1263    }
1264
1265    #[test]
1266    fn split_close_delimiter_across_chunks() {
1267        let mut env = HashMap::new();
1268        env.insert("NAME".into(), "World".into());
1269        let mut expander = StreamingExpand::new(&[], &env);
1270        let mut out = Vec::new();
1271
1272        // Split `}}` across chunks: `{{ env:NAME` / `}}`
1273        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
1274        expander.process_bytes(b"}}", &mut out).unwrap();
1275        expander.flush(&mut out).unwrap();
1276
1277        assert_eq!(String::from_utf8_lossy(&out), "World");
1278    }
1279
1280    #[test]
1281    fn split_close_delimiter_with_trailing_content() {
1282        let mut env = HashMap::new();
1283        env.insert("NAME".into(), "World".into());
1284        let mut expander = StreamingExpand::new(&[], &env);
1285        let mut out = Vec::new();
1286
1287        // Split `}}` across chunks with content after
1288        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
1289        expander.process_bytes(b"}} rest", &mut out).unwrap();
1290        expander.flush(&mut out).unwrap();
1291
1292        assert_eq!(String::from_utf8_lossy(&out), "World rest");
1293    }
1294
1295    #[test]
1296    fn empty_input_preserves_pending_state() {
1297        let mut env = HashMap::new();
1298        env.insert("NAME".into(), "World".into());
1299        let mut expander = StreamingExpand::new(&[], &env);
1300        let mut out = Vec::new();
1301
1302        // End chunk with closing byte, then empty input, then confirm
1303        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
1304        expander.process_bytes(b"", &mut out).unwrap(); // empty: should preserve state
1305        expander.process_bytes(b"}}", &mut out).unwrap();
1306        expander.flush(&mut out).unwrap();
1307
1308        assert_eq!(String::from_utf8_lossy(&out), "World");
1309    }
1310
1311    #[test]
1312    fn missing_env_var_errors() {
1313        let env = HashMap::new();
1314        let expander = StreamingExpand::new(&[], &env);
1315        let result = expander.expand_string("{{ env:UNDEFINED_VAR }}");
1316        assert!(result.is_err());
1317        let msg = result.unwrap_err().to_string();
1318        assert!(msg.contains("undefined environment variable"), "got: {msg}");
1319        assert!(msg.contains("UNDEFINED_VAR"), "got: {msg}");
1320    }
1321
1322    #[test]
1323    fn missing_script_var_errors() {
1324        let env = HashMap::new();
1325        let expander = StreamingExpand::new(&[], &env);
1326        let result = expander.expand_string("{{ $undefined_var }}");
1327        assert!(result.is_err());
1328        let msg = result.unwrap_err().to_string();
1329        assert!(msg.contains("undefined script variable"), "got: {msg}");
1330        assert!(msg.contains("$undefined_var"), "got: {msg}");
1331    }
1332
1333    #[test]
1334    fn missing_key_in_map_errors() {
1335        let mut vars = HashMap::new();
1336        vars.insert(
1337            "cfg".into(),
1338            oxdock_parser::Value::map(std::collections::BTreeMap::from([(
1339                "server".into(),
1340                oxdock_parser::Value::map(std::collections::BTreeMap::from([(
1341                    "port".into(),
1342                    oxdock_parser::Value::int(8080),
1343                )])),
1344            )])),
1345        );
1346        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1347        let result = expander.expand_string("{{ $cfg.missing_key }}");
1348        assert!(result.is_err());
1349        let msg = result.unwrap_err().to_string();
1350        assert!(
1351            msg.contains("property 'missing_key' not found"),
1352            "got: {msg}"
1353        );
1354    }
1355
1356    #[test]
1357    fn out_of_bounds_array_index_errors() {
1358        let mut vars = HashMap::new();
1359        vars.insert(
1360            "arr".into(),
1361            oxdock_parser::Value::list(vec![oxdock_parser::Value::string("a".into())]),
1362        );
1363        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1364        let result = expander.expand_string("{{ $arr.5 }}");
1365        assert!(result.is_err());
1366        let msg = result.unwrap_err().to_string();
1367        assert!(msg.contains("index 5 out of bounds"), "got: {msg}");
1368    }
1369
1370    #[test]
1371    fn type_mismatch_navigation_errors() {
1372        let mut vars = HashMap::new();
1373        vars.insert("name".into(), oxdock_parser::Value::string("alice".into()));
1374        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1375        let result = expander.expand_string("{{ $name.sub_field }}");
1376        assert!(result.is_err());
1377        let msg = result.unwrap_err().to_string();
1378        assert!(
1379            msg.contains("cannot access property 'sub_field' on primitive"),
1380            "got: {msg}"
1381        );
1382    }
1383
1384    #[test]
1385    fn unprefixed_identifier_errors() {
1386        let env = HashMap::new();
1387        let expander = StreamingExpand::new(&[], &env);
1388        let result = expander.expand_string("{{ bare_word }}");
1389        assert!(result.is_err());
1390        let msg = result.unwrap_err().to_string();
1391        assert!(msg.contains("missing required step override"), "got: {msg}");
1392    }
1393
1394    // ── Strict namespace isolation tests ─────────────────────────────────────
1395
1396    #[test]
1397    fn script_var_does_not_fall_back_to_env() {
1398        let mut env = HashMap::new();
1399        env.insert("WHO".into(), "from-env".into());
1400        let expander = StreamingExpand::new(&[], &env);
1401        // $WHO queries vars, NOT env : should error even though env has WHO
1402        let result = expander.expand_string("{{ $WHO }}");
1403        assert!(result.is_err());
1404        let msg = result.unwrap_err().to_string();
1405        assert!(msg.contains("undefined script variable"), "got: {msg}");
1406        assert!(
1407            msg.contains("did you mean 'env:WHO'"),
1408            "hint should suggest env: prefix, got: {msg}"
1409        );
1410    }
1411
1412    #[test]
1413    fn env_var_does_not_fall_back_to_vars() {
1414        let mut vars = HashMap::new();
1415        vars.insert(
1416            "HOST".into(),
1417            oxdock_parser::Value::string("from-var".into()),
1418        );
1419        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1420        // env:HOST queries env, NOT vars : should error even though vars has HOST
1421        let result = expander.expand_string("{{ env:HOST }}");
1422        assert!(result.is_err());
1423        let msg = result.unwrap_err().to_string();
1424        assert!(msg.contains("undefined environment variable"), "got: {msg}");
1425        assert!(
1426            msg.contains("did you mean '$HOST'"),
1427            "hint should suggest $ prefix, got: {msg}"
1428        );
1429    }
1430
1431    #[test]
1432    fn step_override_does_not_fall_back_to_vars() {
1433        let mut vars = HashMap::new();
1434        vars.insert("PORT".into(), oxdock_parser::Value::int(8080));
1435        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1436        // PORT (bare) queries overrides, NOT vars : should error
1437        let result = expander.expand_string("{{ PORT }}");
1438        assert!(result.is_err());
1439        let msg = result.unwrap_err().to_string();
1440        assert!(msg.contains("missing required step override"), "got: {msg}");
1441        assert!(
1442            msg.contains("did you mean '$PORT'"),
1443            "hint should suggest $ prefix, got: {msg}"
1444        );
1445    }
1446
1447    #[test]
1448    fn env_prefix_isolated_from_script_vars() {
1449        let mut vars = HashMap::new();
1450        vars.insert("MODE".into(), oxdock_parser::Value::string("dev".into()));
1451        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1452        // env:MODE looks in env, not vars : should error
1453        let result = expander.expand_string("{{ env:MODE }}");
1454        assert!(result.is_err());
1455        let msg = result.unwrap_err().to_string();
1456        assert!(msg.contains("undefined environment variable"), "got: {msg}");
1457        assert!(
1458            msg.contains("did you mean '$MODE'"),
1459            "hint should suggest $ prefix, got: {msg}"
1460        );
1461    }
1462
1463    #[test]
1464    fn dollar_prefix_isolated_from_env() {
1465        let mut env = HashMap::new();
1466        env.insert("PORT".into(), "3000".into());
1467        let expander = StreamingExpand::new(&[], &env);
1468        // $PORT looks in vars, not env : should error
1469        let result = expander.expand_string("{{ $PORT }}");
1470        assert!(result.is_err());
1471        let msg = result.unwrap_err().to_string();
1472        assert!(msg.contains("undefined script variable"), "got: {msg}");
1473        assert!(
1474            msg.contains("did you mean 'env:PORT'"),
1475            "hint should suggest env: prefix, got: {msg}"
1476        );
1477    }
1478
1479    #[test]
1480    fn empty_placeholder_errors() {
1481        let expander = StreamingExpand::new(&[], &HashMap::new());
1482        let result = expander.expand_string("{{ }}");
1483        assert!(result.is_err());
1484        let msg = result.unwrap_err().to_string();
1485        assert!(msg.contains("invalid placeholder format"), "got: {msg}");
1486    }
1487
1488    #[test]
1489    fn malformed_symbol_placeholder_errors() {
1490        let expander = StreamingExpand::new(&[], &HashMap::new());
1491        let result = expander.expand_string("{{ @invalid! }}");
1492        assert!(result.is_err());
1493        let msg = result.unwrap_err().to_string();
1494        assert!(msg.contains("invalid placeholder format"), "got: {msg}");
1495    }
1496
1497    /// Feed input in fixed-size chunks, then flush: exercises every
1498    /// chunk-boundary alignment for the given split size.
1499    fn render_split(
1500        input: &[u8],
1501        size: usize,
1502        env: &HashMap<String, String>,
1503    ) -> Result<String, anyhow::Error> {
1504        let mut expander = StreamingExpand::new(&[], env);
1505        let mut out = Vec::new();
1506        for chunk in input.chunks(size) {
1507            expander.process_bytes(chunk, &mut out)?;
1508        }
1509        expander.flush(&mut out)?;
1510        Ok(String::from_utf8_lossy(&out).into_owned())
1511    }
1512
1513    #[test]
1514    fn escaped_opener_one_byte_chunks_stays_literal() {
1515        let mut env = HashMap::new();
1516        env.insert("NAME".into(), "World".into());
1517        // Every byte arrives alone: `\` | `{` | `{` | ... must still
1518        // resolve to a literal opener, never an expansion.
1519        let out = render_split(b"\\{{ env:NAME }}", 1, &env).unwrap();
1520        assert_eq!(out, "{{ env:NAME }}");
1521    }
1522
1523    #[test]
1524    fn escaped_opener_two_byte_chunks_stays_literal() {
1525        let mut env = HashMap::new();
1526        env.insert("NAME".into(), "World".into());
1527        // Two-byte splits land `\{` and lone `{` at chunk ends.
1528        let out = render_split(b"a\\{{ env:NAME }}b", 2, &env).unwrap();
1529        assert_eq!(out, "a{{ env:NAME }}b");
1530    }
1531
1532    #[test]
1533    fn escaped_opener_split_variants_stay_literal() {
1534        let mut env = HashMap::new();
1535        env.insert("NAME".into(), "World".into());
1536        for chunks in [
1537            vec![b"\\".as_slice(), b"{", b"{ env:NAME }}"],
1538            vec![b"\\{".as_slice(), b"{ env:NAME }}"],
1539            vec![b"\\{{ env:NAME ".as_slice(), b"}}"],
1540        ] {
1541            let mut expander = StreamingExpand::new(&[], &env);
1542            let mut out = Vec::new();
1543            for chunk in chunks {
1544                expander.process_bytes(chunk, &mut out).unwrap();
1545            }
1546            expander.flush(&mut out).unwrap();
1547            assert_eq!(
1548                String::from_utf8_lossy(&out),
1549                "{{ env:NAME }}",
1550                "chunks must not corrupt the escape"
1551            );
1552        }
1553    }
1554
1555    #[test]
1556    fn plain_opener_split_chunks_still_expands() {
1557        let mut env = HashMap::new();
1558        env.insert("NAME".into(), "World".into());
1559        // The fix must not swallow genuine openers fragmented the
1560        // same way: `{` | `{` opens, then the key resolves.
1561        let out = render_split(b"{{ env:NAME }}", 1, &env).unwrap();
1562        assert_eq!(out, "World");
1563    }
1564
1565    #[test]
1566    fn double_backslash_split_chunks_still_expands() {
1567        let mut env = HashMap::new();
1568        env.insert("NAME".into(), "World".into());
1569        // `\\` completes to one backslash; the opener after it expands.
1570        let out = render_split(b"\\\\{{ env:NAME }}", 1, &env).unwrap();
1571        assert_eq!(out, "\\World");
1572    }
1573
1574    #[test]
1575    fn trailing_escape_brace_flushes_literal() {
1576        let env = HashMap::new();
1577        let expander = StreamingExpand::new(&[], &env);
1578        let result = expander.expand_string("end\\{").unwrap();
1579        assert_eq!(result, "end\\{");
1580    }
1581
1582    // ── Single-pass substitution tests ────────────────────────────────────
1583    // Substituted values are emitted verbatim and never re-scanned for
1584    // `{{ ... }}`. These pin the top-level-only behavior: a value that
1585    // itself contains a placeholder stays literal instead of expanding.
1586
1587    #[test]
1588    fn substituted_override_value_is_not_rescanned() {
1589        let mut env = HashMap::new();
1590        env.insert("OTHER".into(), "world".into());
1591        let overrides = vec![("NAME".into(), "{{ env:OTHER }}".into())];
1592        let expander = StreamingExpand::new(&overrides, &env);
1593        let result = expander.expand_string("Hello {{ NAME }}").unwrap();
1594        assert_eq!(result, "Hello {{ env:OTHER }}");
1595    }
1596
1597    #[test]
1598    fn substituted_env_value_is_not_rescanned() {
1599        let mut env = HashMap::new();
1600        env.insert("NAME".into(), "{{ env:OTHER }}".into());
1601        env.insert("OTHER".into(), "world".into());
1602        let expander = StreamingExpand::new(&[], &env);
1603        let result = expander.expand_string("Hello {{ env:NAME }}").unwrap();
1604        assert_eq!(result, "Hello {{ env:OTHER }}");
1605    }
1606
1607    #[test]
1608    fn substituted_script_var_value_is_not_rescanned() {
1609        let mut vars = HashMap::new();
1610        vars.insert(
1611            "inner".into(),
1612            oxdock_parser::Value::string("{{ env:OTHER }}".into()),
1613        );
1614        let mut env = HashMap::new();
1615        env.insert("OTHER".into(), "world".into());
1616        let expander = StreamingExpand::new(&[], &env).with_vars(&vars);
1617        let result = expander.expand_string("Hello {{ $inner }}").unwrap();
1618        assert_eq!(result, "Hello {{ env:OTHER }}");
1619    }
1620
1621    /// Echo resolver returning the debug shape of each argument, so
1622    /// literal parsing asserts on values instead of formatting.
1623    fn shape_resolver() -> PlaceholderCall {
1624        Arc::new(|module, func, args| {
1625            if module == "T" && func == "SHAPE" {
1626                let shape = args
1627                    .iter()
1628                    .map(|arg| arg.type_name().to_string())
1629                    .collect::<Vec<_>>()
1630                    .join(",");
1631                return Ok(oxdock_parser::Value::string(shape));
1632            }
1633            bail!("unknown placeholder function '{module}::{func}'")
1634        })
1635    }
1636
1637    #[test]
1638    fn placeholder_call_with_empty_map_literal() {
1639        let expander =
1640            StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1641        let result = expander.expand_string("{{ T::SHAPE({}) }}").unwrap();
1642        assert_eq!(result, "MAP");
1643    }
1644
1645    #[test]
1646    fn placeholder_call_with_map_and_list_literals() {
1647        let expander =
1648            StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1649        let result = expander
1650            .expand_string("{{ T::SHAPE({a: 1, b: \"x\"}, [1, true]) }}")
1651            .unwrap();
1652        assert_eq!(result, "MAP,LIST");
1653    }
1654
1655    #[test]
1656    fn placeholder_call_map_commas_nest_inside_literals() {
1657        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1658            let map = args[0].as_map().expect("map");
1659            let format = map
1660                .get("format")
1661                .and_then(|v| v.as_str())
1662                .expect("format string");
1663            Ok(oxdock_parser::Value::string(format.to_string()))
1664        });
1665        let expander = StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(resolver);
1666        let result = expander
1667            .expand_string("{{ T::SHAPE({min_level: 2, format: \"a,b\"}) }}")
1668            .unwrap();
1669        assert_eq!(result, "a,b");
1670    }
1671
1672    #[test]
1673    fn placeholder_call_map_values_accept_var_refs_and_nesting() {
1674        let mut vars = HashMap::new();
1675        vars.insert("depth".into(), oxdock_parser::Value::int(2));
1676        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1677            let map = args[0].as_map().expect("map");
1678            let depth = map.get("n").and_then(|v| v.as_i64()).expect("int");
1679            let tags = map.get("tags").and_then(|v| v.as_list()).expect("list");
1680            Ok(oxdock_parser::Value::string(format!(
1681                "{depth}:{}",
1682                tags.len()
1683            )))
1684        });
1685        let expander = StreamingExpand::new(&[], &HashMap::new())
1686            .with_vars(&vars)
1687            .with_call_resolver(resolver);
1688        let result = expander
1689            .expand_string("{{ T::SHAPE({n: $depth, tags: [\"a\", \"b\"]}) }}")
1690            .unwrap();
1691        assert_eq!(result, "2:2");
1692    }
1693
1694    #[test]
1695    fn placeholder_call_rejects_malformed_literals() {
1696        for bad in [
1697            "{{ T::SHAPE({a}) }}",
1698            "{{ T::SHAPE({a: 1, a: 2}) }}",
1699            "{{ T::SHAPE({\"a\": 1: 2}) }}",
1700            "{{ T::SHAPE([1) }}",
1701            "{{ T::SHAPE({a: 1) }}",
1702        ] {
1703            let expander =
1704                StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1705            assert!(expander.expand_string(bad).is_err(), "must fail: {bad}");
1706        }
1707    }
1708}