From a92838facf9be878dd0120076b0a3fca1e22a519 Mon Sep 17 00:00:00 2001 From: Lucas Duailibe Date: Sat, 7 Apr 2018 12:03:56 -0300 Subject: [PATCH] Prevent formatting GraphQL embedded in JS if it contains invalid escape sequences (#4278) --- src/language-js/embed.js | 7 +++ .../__snapshots__/jsfmt.spec.js.snap | 49 +++++++++++++++++++ tests/multiparser_js_graphql/invalid.js | 22 +++++++++ 3 files changed, 78 insertions(+) create mode 100644 tests/multiparser_js_graphql/invalid.js diff --git a/src/language-js/embed.js b/src/language-js/embed.js index d5bd8b6d4..04fc769ca 100644 --- a/src/language-js/embed.js +++ b/src/language-js/embed.js @@ -78,6 +78,13 @@ function embed(path, print, textToDoc /*, options */) { const isFirst = i === 0; const isLast = i === numQuasis - 1; const text = templateElement.value.cooked; + + // Bail out if any of the quasis have an invalid escape sequence + // (which would make the `cooked` value be `null` or `undefined`) + if (typeof text !== "string") { + return null; + } + const lines = text.split("\n"); const numLines = lines.length; const expressionDoc = expressionDocs[i]; diff --git a/tests/multiparser_js_graphql/__snapshots__/jsfmt.spec.js.snap b/tests/multiparser_js_graphql/__snapshots__/jsfmt.spec.js.snap index 5f637b59f..4a1ccc373 100644 --- a/tests/multiparser_js_graphql/__snapshots__/jsfmt.spec.js.snap +++ b/tests/multiparser_js_graphql/__snapshots__/jsfmt.spec.js.snap @@ -409,6 +409,55 @@ gql\` `; +exports[`invalid.js 1`] = ` +// none of the embedded GraphQL should be formatted +// for they have an invalid escape sequence + +gql\` + "\\x" + type Foo { + a: string + } +\`; + +gql\` + type Foo { + a: string + } + + \${stuff} + + "\\x" + type Bar { + b : string + } +\`; +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// none of the embedded GraphQL should be formatted +// for they have an invalid escape sequence + +gql\` + "\\x" + type Foo { + a: string + } +\`; + +gql\` + type Foo { + a: string + } + + \${stuff} + + "\\x" + type Bar { + b : string + } +\`; + +`; + exports[`react-relay.js 1`] = ` const { graphql } = require("react-relay"); diff --git a/tests/multiparser_js_graphql/invalid.js b/tests/multiparser_js_graphql/invalid.js new file mode 100644 index 000000000..df6cfdeaa --- /dev/null +++ b/tests/multiparser_js_graphql/invalid.js @@ -0,0 +1,22 @@ +// none of the embedded GraphQL should be formatted +// for they have an invalid escape sequence + +gql` + "\x" + type Foo { + a: string + } +`; + +gql` + type Foo { + a: string + } + + ${stuff} + + "\x" + type Bar { + b : string + } +`;