diff --git a/tests/bootstrap.js b/tests/bootstrap.js index e0cf0115e..fb185e1e2 100644 --- a/tests/bootstrap.js +++ b/tests/bootstrap.js @@ -125,11 +125,11 @@ ' window.BlocklyMsg = window.Blockly.Msg;\n' + ' delete window.Blockly;\n' + '\n'); - const requires = options.requires.map(r => '\'' + r + '\'').join(); + const allRequires = options.requires.map(quote).join(); document.write( ''); } } + + return; // All done. Only helper functions after this point. + + /** + * Convert a string into a string literal. Strictly speaking we + * only need to escape backslash, \r, \n, \u2028 (line separator), + * \u2029 (paragraph separator) and whichever quote character we're + * using, but for simplicity we escape all the control characters. + * + * Based on https://github.com/google/CodeCity/blob/master/server/code.js + * + * @param {string} str The string to convert. + * @return {string} The value s as a eval-able string literal. + */ + function quote(str) { + /* eslint-disable no-control-regex, no-multi-spaces */ + /** Regexp for characters to be escaped in a single-quoted string. */ + const singleRE = /[\x00-\x1f\\\u2028\u2029']/g; + + /** Map of control character replacements. */ + const replacements = { + '\x00': '\\0', '\x01': '\\x01', '\x02': '\\x02', '\x03': '\\x03', + '\x04': '\\x04', '\x05': '\\x05', '\x06': '\\x06', '\x07': '\\x07', + '\x08': '\\b', '\x09': '\\t', '\x0a': '\\n', '\x0b': '\\v', + '\x0c': '\\f', '\x0d': '\\r', '\x0e': '\\x0e', '\x0f': '\\x0f', + '"': '\\"', "'": "\\'", '\\': '\\\\', + '\u2028': '\\u2028', '\u2029': '\\u2029', + }; + /* eslint-enable no-control-regex, no-multi-spaces */ + + /** + * Replacer function. + * @param {string} c Single UTF-16 code unit ("character") string to + * be replaced. + * @return {string} Multi-character string containing escaped + * representation of c. + */ + function replace(c) { + return replacements[c]; + } + + return "'" + str.replace(singleRE, replace) + "'"; + } })();