Skip to main content

vs_protocol/
request.rs

1//! Request line: `<primitive> [arg]... [--flag[=val]]...`
2//!
3//! See `docs/PROTOCOL.md` § "Request line". The primitive is a lowercase
4//! identifier; positional args may be bare or `"..."`-quoted; flags use
5//! the long form (`--name` or `--name=value`). The wire format does not
6//! carry short flags — the CLI may accept them and translate before
7//! sending.
8
9use std::collections::BTreeMap;
10use std::fmt;
11
12use crate::error::{ParseError, Result};
13use crate::tokenize::strip_quotes;
14
15/// One request from the CLI to the daemon.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct Request {
18    /// Primitive name, e.g. `vs_open`.
19    pub primitive: String,
20    /// Positional arguments, in order.
21    pub args: Vec<String>,
22    /// Flags. `None` means a bare flag (e.g. `--full-page`); `Some(v)`
23    /// means `--name=v`.
24    pub flags: BTreeMap<String, Option<String>>,
25}
26
27impl Request {
28    #[must_use]
29    pub fn new(primitive: impl Into<String>) -> Self {
30        Self {
31            primitive: primitive.into(),
32            args: Vec::new(),
33            flags: BTreeMap::new(),
34        }
35    }
36
37    #[must_use]
38    pub fn arg(mut self, value: impl Into<String>) -> Self {
39        self.args.push(value.into());
40        self
41    }
42
43    #[must_use]
44    pub fn flag(mut self, name: impl Into<String>) -> Self {
45        self.flags.insert(name.into(), None);
46        self
47    }
48
49    #[must_use]
50    pub fn flag_value(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
51        self.flags.insert(name.into(), Some(value.into()));
52        self
53    }
54
55    /// Encode the request as a single wire line, including the trailing
56    /// newline.
57    ///
58    /// Args and flag values are backslash-escaped (`\` `\n` `\r` `\t`)
59    /// *before* quoting so a value that itself contains newlines —
60    /// e.g. a multiline `vs inspect eval` expression — survives the
61    /// line-framed transport instead of being split into bogus extra
62    /// request lines. `parse` reverses the escaping.
63    #[must_use]
64    pub fn encode(&self) -> String {
65        let mut out = self.primitive.clone();
66        for arg in &self.args {
67            out.push(' ');
68            out.push_str(&quote_arg(&escape_wire(arg)));
69        }
70        for (k, v) in &self.flags {
71            out.push(' ');
72            out.push_str("--");
73            out.push_str(k);
74            if let Some(value) = v {
75                out.push('=');
76                out.push_str(&quote_arg(&escape_wire(value)));
77            }
78        }
79        out.push('\n');
80        out
81    }
82
83    /// Parse one request line. Trailing newline optional.
84    pub fn parse(line: &str) -> Result<Self> {
85        let trimmed = line.trim_end_matches('\n').trim();
86        if trimmed.is_empty() {
87            return Err(ParseError::InvalidRequest {
88                detail: "empty request line",
89            });
90        }
91        let mut tokens = raw_tokens(trimmed).into_iter();
92        let primitive_tok = tokens.next().ok_or(ParseError::InvalidRequest {
93            detail: "missing primitive",
94        })?;
95        // Validate the primitive shape: lowercase identifier with
96        // optional underscores.
97        if !is_valid_primitive(primitive_tok) {
98            return Err(ParseError::InvalidRequest {
99                detail: "invalid primitive name",
100            });
101        }
102        let mut args = Vec::new();
103        let mut flags = BTreeMap::new();
104        for tok in tokens {
105            if let Some(rest) = tok.strip_prefix("--") {
106                if rest.is_empty() {
107                    return Err(ParseError::InvalidRequest {
108                        detail: "flag with no name",
109                    });
110                }
111                if let Some((name, value)) = rest.split_once('=') {
112                    if name.is_empty() {
113                        return Err(ParseError::InvalidRequest {
114                            detail: "flag with empty name",
115                        });
116                    }
117                    flags.insert(name.to_string(), Some(unescape_wire(strip_quotes(value))));
118                } else {
119                    flags.insert(rest.to_string(), None);
120                }
121            } else {
122                args.push(unescape_wire(strip_quotes(tok)));
123            }
124        }
125        Ok(Self {
126            primitive: primitive_tok.to_string(),
127            args,
128            flags,
129        })
130    }
131}
132
133impl fmt::Display for Request {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        f.write_str(self.encode().trim_end_matches('\n'))
136    }
137}
138
139/// Backslash-escape the characters that the line-framed, quote-aware
140/// wire would otherwise break on or mangle: the escape char itself, a
141/// literal double quote (so it can't prematurely close a quoted span),
142/// and the CR/LF/TAB control chars (LF/CR would split the request into
143/// extra lines). Everything else passes through untouched, so the
144/// common single-line, quote-free case is a no-op.
145///
146/// Unlike the shared `quote_value`, this is lossless: `"` survives as
147/// `\"` instead of being substituted to `'`, so `vs inspect eval` can
148/// carry JS string literals like `querySelector("a")` verbatim.
149fn escape_wire(s: &str) -> String {
150    if !s.contains(['\\', '"', '\n', '\r', '\t']) {
151        return s.to_string();
152    }
153    let mut out = String::with_capacity(s.len() + 8);
154    for c in s.chars() {
155        match c {
156            '\\' => out.push_str("\\\\"),
157            '"' => out.push_str("\\\""),
158            '\n' => out.push_str("\\n"),
159            '\r' => out.push_str("\\r"),
160            '\t' => out.push_str("\\t"),
161            other => out.push(other),
162        }
163    }
164    out
165}
166
167/// Inverse of [`escape_wire`]. An unknown escape (`\x`) is preserved
168/// verbatim — both backslash and the following char — so JS source like
169/// `/\d/` round-trips even though `\d` isn't one of our escapes.
170fn unescape_wire(s: &str) -> String {
171    if !s.contains('\\') {
172        return s.to_string();
173    }
174    let mut out = String::with_capacity(s.len());
175    let mut chars = s.chars();
176    while let Some(c) = chars.next() {
177        if c != '\\' {
178            out.push(c);
179            continue;
180        }
181        match chars.next() {
182            // `\\` → `\`; a trailing lone `\` (None) also yields `\`.
183            Some('\\') | None => out.push('\\'),
184            Some('"') => out.push('"'),
185            Some('n') => out.push('\n'),
186            Some('r') => out.push('\r'),
187            Some('t') => out.push('\t'),
188            Some(other) => {
189                out.push('\\');
190                out.push(other);
191            }
192        }
193    }
194    out
195}
196
197/// Wrap an already-[`escape_wire`]d value in `"..."` if it contains
198/// token-breaking whitespace or is empty; otherwise leave it bare.
199///
200/// Unlike the shared `quote_value`, this performs **no** `"` → `'`
201/// substitution — `escape_wire` has already turned every literal quote
202/// into `\"`, and substituting here would corrupt that back into `\'`.
203fn quote_arg(escaped: &str) -> String {
204    if escaped.is_empty() || escaped.contains([' ', '\t']) {
205        format!("\"{escaped}\"")
206    } else {
207        escaped.to_string()
208    }
209}
210
211/// Split a request line into raw tokens (quotes and escapes intact),
212/// breaking on unquoted whitespace. This is a request-local, escape-
213/// aware variant of the shared [`Tokenizer`]: a backslash escapes the
214/// following char, so an escaped quote (`\"`) inside a quoted span does
215/// not close it and an embedded space does not split the token. The
216/// shared tokenizer is intentionally left escape-unaware — the tree and
217/// delta grammars rely on its `'`-substitution contract — which is why
218/// requests get their own splitter here.
219fn raw_tokens(s: &str) -> Vec<&str> {
220    let mut tokens = Vec::new();
221    let mut rest = s;
222    loop {
223        let trimmed = rest.trim_start_matches([' ', '\t']);
224        if trimmed.is_empty() {
225            return tokens;
226        }
227        let mut in_quotes = false;
228        let mut end = trimmed.len();
229        let mut chars = trimmed.char_indices();
230        while let Some((i, c)) = chars.next() {
231            match c {
232                // Consume the escaped char too (UTF-8 safe via the
233                // iterator), so it can never be treated as a delimiter
234                // or quote toggle.
235                '\\' => {
236                    chars.next();
237                }
238                '"' => in_quotes = !in_quotes,
239                ' ' | '\t' if !in_quotes => {
240                    end = i;
241                    break;
242                }
243                _ => {}
244            }
245        }
246        tokens.push(&trimmed[..end]);
247        rest = &trimmed[end..];
248    }
249}
250
251fn is_valid_primitive(s: &str) -> bool {
252    !s.is_empty()
253        && s.chars()
254            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260
261    #[test]
262    fn primitive_only() {
263        let r = Request::new("vs_view");
264        let s = r.encode();
265        assert_eq!(s, "vs_view\n");
266        assert_eq!(Request::parse(&s).unwrap(), r);
267    }
268
269    #[test]
270    fn with_arg() {
271        let r = Request::new("vs_open").arg("https://example.com");
272        let s = r.encode();
273        assert_eq!(s, "vs_open https://example.com\n");
274        assert_eq!(Request::parse(&s).unwrap(), r);
275    }
276
277    #[test]
278    fn with_quoted_arg() {
279        let r = Request::new("vs_act")
280            .arg("2")
281            .arg("fill")
282            .arg("frane@example.com");
283        let s = r.encode();
284        assert_eq!(s, "vs_act 2 fill frane@example.com\n");
285        assert_eq!(Request::parse(&s).unwrap(), r);
286    }
287
288    #[test]
289    fn arg_with_spaces_quoted() {
290        let r = Request::new("vs_act")
291            .arg("2")
292            .arg("fill")
293            .arg("with spaces");
294        let s = r.encode();
295        assert_eq!(s, "vs_act 2 fill \"with spaces\"\n");
296        assert_eq!(Request::parse(&s).unwrap(), r);
297    }
298
299    #[test]
300    fn bare_flag() {
301        let r = Request::new("vs_capture").flag("full-page");
302        let s = r.encode();
303        assert_eq!(s, "vs_capture --full-page\n");
304        assert_eq!(Request::parse(&s).unwrap(), r);
305    }
306
307    #[test]
308    fn flag_with_value() {
309        let r = Request::new("vs_capture").flag_value("viewport", "mobile");
310        let s = r.encode();
311        assert_eq!(s, "vs_capture --viewport=mobile\n");
312        assert_eq!(Request::parse(&s).unwrap(), r);
313    }
314
315    #[test]
316    fn flag_value_with_spaces_quoted() {
317        let r = Request::new("vs_session_open").flag_value("policy", "strict mode");
318        let s = r.encode();
319        assert_eq!(s, "vs_session_open --policy=\"strict mode\"\n");
320        assert_eq!(Request::parse(&s).unwrap(), r);
321    }
322
323    #[test]
324    fn full_request() {
325        let r = Request::new("vs_capture")
326            .arg("7")
327            .flag("full-page")
328            .flag_value("viewport", "mobile");
329        let s = r.encode();
330        // Flags ordered alphabetically.
331        assert_eq!(s, "vs_capture 7 --full-page --viewport=mobile\n");
332        assert_eq!(Request::parse(&s).unwrap(), r);
333    }
334
335    #[test]
336    fn multiline_arg_survives_framing() {
337        // A multiline eval expression must not break the single-line
338        // wire framing: the encoded form has exactly one '\n' (the
339        // terminator), and parse round-trips the original newlines.
340        let expr = "const x = 1;\nconst y = 2;\nx + y";
341        let r = Request::new("vs_inspect").arg("eval").arg("3").arg(expr);
342        let s = r.encode();
343        assert_eq!(
344            s.matches('\n').count(),
345            1,
346            "encoded request must be a single wire line; got {s:?}"
347        );
348        assert_eq!(Request::parse(&s).unwrap(), r);
349    }
350
351    #[test]
352    fn backslash_and_tab_round_trip() {
353        let expr = "a\tb /\\d+/ c\\nd"; // real tab, regex backslash, literal \n
354        let r = Request::new("vs_inspect").arg("eval").arg("1").arg(expr);
355        let s = r.encode();
356        assert_eq!(s.matches('\n').count(), 1);
357        assert_eq!(Request::parse(&s).unwrap(), r);
358    }
359
360    #[test]
361    fn double_quotes_in_arg_round_trip() {
362        // The whole point of the request-local escaping: a JS string
363        // literal with double quotes survives losslessly (the shared
364        // quote_value would have mangled `"` → `'`).
365        for expr in [
366            r#"document.querySelector("a").href"#,
367            r#"x === "with space" && y"#,
368            r#"JSON.parse("{\"k\":1}")"#, // already-escaped quotes inside JS
369        ] {
370            let r = Request::new("vs_inspect").arg("eval").arg("1").arg(expr);
371            let s = r.encode();
372            assert_eq!(
373                s.matches('\n').count(),
374                1,
375                "single wire line expected for {expr:?}; got {s:?}"
376            );
377            assert_eq!(
378                Request::parse(&s).unwrap(),
379                r,
380                "round-trip failed for {expr:?} (encoded {s:?})"
381            );
382        }
383    }
384
385    #[test]
386    fn multiline_flag_value_round_trips() {
387        let r = Request::new("vs_act").flag_value("text", "line1\nline2");
388        let s = r.encode();
389        assert_eq!(s.matches('\n').count(), 1);
390        assert_eq!(Request::parse(&s).unwrap(), r);
391    }
392
393    #[test]
394    fn rejects_invalid_primitive() {
395        for bad in ["", "VS_VIEW", "--vs", "vs!", "vs-cli"] {
396            assert!(Request::parse(bad).is_err(), "{bad} should fail");
397        }
398    }
399}