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