Skip to main content

bnto_shell/
args.rs

1// `shell-run` argument preparation — conditional arg groups and the
2// `{{url}}` / `{{input}}` placeholders injected by input preparation.
3
4/// Placeholder in args for URL/text input injected by the CLI's input preparation.
5const URL_PLACEHOLDER: &str = "{{url}}";
6const INPUT_PLACEHOLDER: &str = "{{input}}";
7const OUTPUT_DIR_TOKEN: &str = "{{output_dir}}";
8
9/// Resolve `{{url}}` and `{{input}}` placeholders in args from injected params.
10///
11/// The CLI's input preparation injects `"url"` or `"text"` into the node's
12/// params for URL/Text mode recipes. If no placeholder exists in the args
13/// but a `url` param is present, append the URL as the last argument.
14pub(crate) fn resolve_input_placeholders(
15    args: &mut Vec<String>,
16    params: &serde_json::Map<String, serde_json::Value>,
17) -> Result<(), String> {
18    let url = params
19        .get("url")
20        .and_then(serde_json::Value::as_str)
21        .unwrap_or("");
22    let text = params
23        .get("text")
24        .and_then(serde_json::Value::as_str)
25        .unwrap_or("");
26
27    // The input value is whichever was injected (url or text).
28    let input_val = if !url.is_empty() { url } else { text };
29    // SEC-27: `{{output_dir}}` is filled after this, so input carrying it
30    // would have it filled too.
31    if input_val.contains(OUTPUT_DIR_TOKEN) {
32        return Err(format!(
33            "the input carries '{OUTPUT_DIR_TOKEN}', which shell-run fills itself"
34        ));
35    }
36
37    let has_url_placeholder = args.iter().any(|a| a.contains(URL_PLACEHOLDER));
38    let has_input_placeholder = args.iter().any(|a| a.contains(INPUT_PLACEHOLDER));
39
40    // Substitute placeholders in existing args.
41    for arg in args.iter_mut() {
42        if arg.contains(URL_PLACEHOLDER) && !url.is_empty() {
43            *arg = arg.replace(URL_PLACEHOLDER, url);
44        }
45        if arg.contains(INPUT_PLACEHOLDER) && !input_val.is_empty() {
46            *arg = arg.replace(INPUT_PLACEHOLDER, input_val);
47        }
48    }
49
50    // If no placeholder was found but a URL was injected, append it.
51    // This is the common case: `yt-dlp <args...> <url>`
52    if !has_url_placeholder && !has_input_placeholder && !url.is_empty() {
53        args.push(url.to_string());
54    }
55    Ok(())
56}
57
58/// Flatten a resolved `args` array that may contain conditional groups.
59///
60/// After template resolution, the args array can contain:
61/// - **Flat string**: included if non-empty, dropped if `""`
62/// - **Nested array**: ALL elements must be non-empty strings → flattened
63///   into parent; if ANY element is `""` → entire group dropped
64/// - **Other types**: dropped (backward compat)
65///
66/// This enables conditional flag groups in recipes:
67/// ```json
68/// "args": ["--always", ["--cookies-from-browser", "{{fields.browser}}"], "{{fields.thumbnail}}"]
69/// ```
70/// When `browser=""`: `["--always"]`
71/// When `browser="chrome"`: `["--always", "--cookies-from-browser", "chrome"]`
72pub fn flatten_conditional_args(args: &[serde_json::Value]) -> Vec<String> {
73    let mut result = Vec::new();
74    for item in args {
75        match item {
76            serde_json::Value::String(s) if !s.is_empty() => {
77                result.push(s.clone());
78            }
79            serde_json::Value::Array(group) => {
80                let strings: Vec<&str> =
81                    group.iter().filter_map(serde_json::Value::as_str).collect();
82                // All elements must be present strings AND non-empty.
83                let all_non_empty =
84                    strings.len() == group.len() && strings.iter().all(|s| !s.is_empty());
85                if all_non_empty {
86                    result.extend(strings.into_iter().map(String::from));
87                }
88            }
89            _ => {}
90        }
91    }
92    result
93}