Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

A GraphQL document that begins with a comment is still read (#386)

Alex Joaquim Pereira80cf0b8a50ef
diff --git a/crates/js/src/api_ops.rs b/crates/js/src/api_ops.rs
index 157e4ff4..700fc03a 100644
--- a/crates/js/src/api_ops.rs
+++ b/crates/js/src/api_ops.rs
@@ -60,7 +60,7 @@ pub fn read_document(text: &str, allow_shorthand: bool) -> Option<Document> {
chars.next();
} else if c == '#' {
for (_, c) in chars.by_ref() {
- if c == '\n' {
+ if c == '\n' || c == '\r' {
break;
}
}
@@ -166,7 +166,7 @@ pub fn read_document(text: &str, allow_shorthand: bool) -> Option<Document> {
}
'#' => {
for (_, d) in chars.by_ref() {
- if d == '\n' {
+ if d == '\n' || d == '\r' {
break;
}
}
@@ -216,9 +216,21 @@ fn skip_string(chars: &mut std::iter::Peekable<std::str::CharIndices<'_>>, text:
None
}
+/// Where a document may start, after the whitespace, commas, byte-order mark and `#` comments
+/// that may come first (the non-run-time part of the trivia [`read_document`] skips).
+fn document_start(text: &str) -> &str {
+ let mut rest = text;
+ loop {
+ let trimmed = rest.trim_start_matches(|c: char| c.is_whitespace() || c == ',' || c == '\u{feff}');
+ let Some(after) = trimmed.strip_prefix('#') else { return trimmed };
+ rest = after.find(['\n', '\r']).and_then(|i| after.get(i + 1..)).unwrap_or("");
+ }
+}
+
/// Could this text be a whole document? A quick test before the real read, on every string.
+/// A document may begin with a comment, as a generated client often writes one.
pub fn may_be_document(text: &str) -> bool {
- let t = text.trim_start();
+ let t = document_start(text);
(t.starts_with("query") || t.starts_with("mutation") || t.starts_with("subscription") || t.starts_with("fragment")) && t.contains('{')
}
@@ -419,6 +431,21 @@ mod tests {
assert!(read_document(&format!("{h}"), false).is_none());
}
+ #[test]
+ fn a_document_may_begin_with_a_comment() {
+ assert!(may_be_document("# note\nquery Q { a }"));
+ assert!(may_be_document(" # one\n# two\nmutation M { a }"));
+ assert!(may_be_document("# note\r\nquery Q { a }"));
+ assert!(may_be_document("# note\rquery Q { a }"), "a lone CR ends a comment too");
+ assert_eq!(read_document("# note\rquery Q { a }", false).and_then(|d| d.operations.first().and_then(|o| o.name.clone())).as_deref(), Some("Q"));
+ assert!(may_be_document("\u{feff}# c\n, query Q { a }"));
+ assert!(!may_be_document("# note\nconst a = { b: 1 }"));
+ assert!(!may_be_document("# only a comment"));
+ assert!(!may_be_document("# query Q { a }"), "no newline means the whole text is the comment");
+ let doc = read_document("query Q { a # note\r b }", false).expect("a comment in a selection set ends at a lone CR");
+ assert_eq!(doc.operations.first().and_then(|o| o.name.as_deref()), Some("Q"));
+ }
+
#[test]
fn hostile_documents_are_bounded() {
assert!(read_document(&"{".repeat(100_000), true).is_none());
diff --git a/crates/js/src/tests.rs b/crates/js/src/tests.rs
index 92ba6dcc..bcbf56db 100644
--- a/crates/js/src/tests.rs
+++ b/crates/js/src/tests.rs
@@ -322,6 +322,35 @@ fn graphql_documents_in_plain_strings_and_minified_shapes() {
assert_eq!(anon, [("graphql".to_string(), "query".to_string(), None, true)], "known to be anonymous");
}
+#[test]
+fn graphql_documents_that_begin_with_a_comment() {
+ // A comment is valid at the start of a GraphQL document, and common in generated clients.
+ let l = ops(r##"const q="# Client document\nquery Feed{items{id}}";"##);
+ assert!(has(&l, "graphql", "query", "Feed"), "{l:?}");
+ let l = ops("const q=`# Client document\nquery Feed{items{id}}`;");
+ assert!(has(&l, "graphql", "query", "Feed"), "{l:?}");
+ // A lone CR ends a comment in GraphQL, as a CRLF does. A string escape keeps the CR; a
+ // template literal would normalize it to LF.
+ let l = ops(r##"const q="# Client document\rquery Feed{items{id}}";"##);
+ assert!(has(&l, "graphql", "query", "Feed"), "{l:?}");
+ // A template with run-time text goes through the other call site.
+ let l = ops("const q=`# Client document\nquery Feed{items{id}} ${x}`;");
+ assert!(has(&l, "graphql", "query", "Feed"), "{l:?}");
+ // The same document in a request body.
+ let l = ops(r##"fetch("/graphql",{method:"POST",body:JSON.stringify({query:"# Client document\nquery Feed{items{id}}",variables:{}})})"##);
+ assert!(has(&l, "graphql", "query", "Feed"), "{l:?}");
+ // A comment doesn't make any other text a document.
+ let l = ops(r##"const s="# note\nconst a = {b:1}";"##);
+ assert!(!l.iter().any(|o| o.0 == "graphql"), "{l:?}");
+}
+
+#[test]
+fn graphql_comment_inside_a_selection_set() {
+ // A comment may sit between fields, and a lone CR ends it as a newline does.
+ let l = ops(r##"const q="query Feed{items # note\r id}";"##);
+ assert!(has(&l, "graphql", "query", "Feed"), "{l:?}");
+}
+
#[test]
fn graphql_spreads_and_computed_values_mean_unknown() {
let l = ops(r#"var d={...base,kind:"OperationDefinition",operation:"query",name:{value:"Hidden"}};"#);
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index ca6b6ad3..b40aa2c5 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -1125,6 +1125,8 @@ against what its original was recorded answering.
of runtimes; checked against about 25 installed Mac apps
- [x] A stand-in backend from a network recording (`web_standin_build`, `_start`, `_stop`, `_show`),
GraphQL and tRPC operations in app maps, and `web_walkthrough_check`
+- [x] `js_app_map` keeps a literal GraphQL document that begins with a comment, as it already
+ does without one (#260)
- [x] `app_builds_line_up` (two real builds of a 276 MB program in 42 s),
`native_source_folder_write` (resumable), `android_components_list`
- [x] CLI: `--json -` takes parameters from a pipe; `--format csv` and `tsv` write a result's rows,