Fix template string tokenization of escape sequences
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent 7c1a631 · Browse files · 5 files·+86 added−5 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+86 added−5 removed
- tests:+65 added−0 removed
- other:+21 added−5 removed
Provenance
- Commit
b67f199- Tree
39f5123- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
7c1a631
5 files changed+86 added−5 removed
modified:lib/arguments/escape.js+2 added-2 removed
65 unmodified lines66676869707170717273747513 unmodified lines65 unmodified lines '\r': '\\r', '\t': '\\t',};
// Up until that codepoint, \u notation can be used instead of \Uconst ASTRAL_START = 65_535;// Up until that code point, a character is a single UTF-16 code unit, so the \u notation can be used instead of \Uexport const ASTRAL_START = 0xFF_FF;
// Some characters are shell-specific, i.e. need to be escaped when the command is copy-pasted then run.// Escaping is shell-specific. We cannot know which shell is used: `process.platform` detection is not enough.// For example, Windows users could be using `cmd.exe`, Powershell or Bash for Windows which all use different escaping.13 unmodified linesmodified:lib/methods/template.js+19 added-3 removed
1 import {ChildProcess} from 'node:child_process';2 import isPlainObject from 'is-plain-obj';3+import {ASTRAL_START} from '../arguments/escape.js';4 import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';5 6 // Check whether the template string syntax is being used7 export const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);45 unmodified lines53 // The only way to distinguish those in JavaScript is to use a tagged template and compare:54 // - the first array argument, which does not escape backslash sequences55 // - its `raw` property, which escapes them56 const splitByWhitespaces = (template, rawTemplate) => {57+ // The template is empty either between two `${expression}`, or when it only contains escaped newlines.58+ // Neither holds any whitespace, so neither separates tokens.56- if (rawTemplate.length === 0) {59+ if (template.length === 0) {60 return {nextTokens: [], leadingWhitespaces: false, trailingWhitespaces: false};61 }62 63 const nextTokens = [];64 let templateStart = 0;62- const isLeadingWhitespaces = DELIMITERS.has(rawTemplate[0]);65+ let isLeadingWhitespaces = false;66 67 for (68 let templateIndex = 0, rawIndex = 0;69 templateIndex < template.length;70 templateIndex += 1, rawIndex += 171 ) {72 const rawCharacter = rawTemplate[rawIndex];73 if (DELIMITERS.has(rawCharacter)) {74+ // Escaped newlines are ignored, so a whitespace after them is still a leading one75+ if (templateIndex === 0) {76+ isLeadingWhitespaces = true;77+ }78+79 if (templateStart !== templateIndex) {80 nextTokens.push(template.slice(templateStart, templateIndex));81 }82 4 unmodified lines87 // Handles escaped newlines in templates88 templateIndex -= 1;89 rawIndex += 1;90 } else if (nextRawCharacter === 'u' && rawTemplate[rawIndex + 2] === '{') {83- rawIndex = rawTemplate.indexOf('}', rawIndex + 3);91+ const closingBraceIndex = rawTemplate.indexOf('}', rawIndex + 3);92+ // A code point above the BMP is a surrogate pair, i.e. two characters, in the template string93+ if (isAstralEscape(rawTemplate.slice(rawIndex + 3, closingBraceIndex))) {94+ templateIndex += 1;95+ }96+97+ rawIndex = closingBraceIndex;98 } else {99 rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;100 }101 }6 unmodified lines108 109 return {nextTokens, leadingWhitespaces: isLeadingWhitespaces, trailingWhitespaces: isTrailingWhitespaces};110 };111 112+const isAstralEscape = codePointHex => Number.parseInt(codePointHex, 16) > ASTRAL_START;113+114 const DELIMITERS = new Set([' ', '\t', '\r', '\n']);115 116 // Number of characters in backslash escape sequences: \0 \xXX or \uXXXX117 // \cX is allowed in RegExps but not in strings55 unmodified linesmodified:test/arguments/escape.js+29 added
100 unmodified lines101 test('result.escapedCommand - \\uE000', testEscapedCommand, ['\u{E000}'], '\'\\ue000\'', '"\\ue000"', '\'\u{E000}\'', '"\u{E000}"');102 test('result.escapedCommand - \\U1D172', testEscapedCommand, ['\u{1D172}'], '\'\u{1D172}\'', '"\u{1D172}"');103 test('result.escapedCommand - \\U1D173', testEscapedCommand, ['\u{1D173}'], '\'\\U1d173\'', '"\\U1d173"', '\'\u{1D173}\'', '"\u{1D173}"');104 test('result.escapedCommand - \\U10FFFD', testEscapedCommand, ['\u{10FFFD}'], '\'\\U10fffd\'', '"\\U10fffd"', '\'\u{10FFFD}\'', '"\u{10FFFD}"');105+106+/*107+`result.escapedCommand` is documented as safe to copy and paste in a terminal, so a shell must parse it back to the exact same arguments.108+Control characters are excluded, since those are intentionally escaped with a Bash-specific notation instead.109+*/110+if (!isWindows) {111+ const testShellRoundTrip = async (t, commandArguments) => {112+ const {escapedCommand} = await execa('print-arguments.js', commandArguments);113+ const {stdout} = await execa('/bin/sh', ['-c', escapedCommand]);114+ t.deepEqual(JSON.parse(stdout), commandArguments);115+ };116+117+ testShellRoundTrip.title = (message, commandArguments) => `result.escapedCommand can be pasted in a shell: ${JSON.stringify(commandArguments)}`;118+119+ test(testShellRoundTrip, ['foo', 'bar']);120+ test(testShellRoundTrip, ['foo bar']);121+ test(testShellRoundTrip, ['\'foo\'', '"bar"']);122+ test(testShellRoundTrip, ['it\'s', 'a\'\'b']);123+ test(testShellRoundTrip, ['foo\\bar', '\\', '\\\\']);124+ // eslint-disable-next-line no-template-curly-in-string125+ test(testShellRoundTrip, ['$FOO', '${FOO}', '$(echo foo)']);126+ test(testShellRoundTrip, ['`echo foo`']);127+ test(testShellRoundTrip, ['foo;bar', 'foo&&bar', 'foo|bar', 'foo>bar']);128+ test(testShellRoundTrip, ['*', '?', '[a-z]', '{a,b}']);129+ test(testShellRoundTrip, ['~', '#foo', '!foo', '-foo', '--foo=bar']);130+ test(testShellRoundTrip, ['', 'foo']);131+ test(testShellRoundTrip, ['ã', '😀']);132+ test(testShellRoundTrip, ['\'"`$\\!*&;| ']);133+}added:test/fixtures/print-arguments.js+4 added
1234#!/usr/bin/env nodeimport process from 'node:process';
process.stdout.write(JSON.stringify(process.argv.slice(2)));modified:test/methods/template.js+32 added
28 unmodified lines29 test('$ can use escaped newlines and character escaped tab indentations', testScriptStdout, () => $`echo.js foo\30 \tbar`, 'foo\tbar');31 test('$ can use escaped newlines and character escaped newlines', testScriptStdout, () => $`echo.js foo\32 \n\nbar`, 'foo\n\nbar');33+// An escaped newline is ignored, so it must not separate tokens, nor hide the whitespaces following it.34+// This must behave the same whether the tokens around it are expressions or not.35+test('$ can use escaped newlines between tokens', testScriptStdout, () => $`echo.js foo\36+bar`, 'foobar');37+test('$ can use escaped newlines between expressions', testScriptStdout, () => $`echo.js ${'foo'}\38+${'bar'}`, 'foobar');39+test('$ can use multiple escaped newlines between expressions', testScriptStdout, () => $`echo.js ${'foo'}\40+\41+${'bar'}`, 'foobar');42+test('$ can use escaped newlines and space indentations between expressions', testScriptStdout, () => $`echo.js ${'foo'}\43+ ${'bar'}`, 'foo\nbar');44+test('$ can use escaped newlines and tab indentations between expressions', testScriptStdout, () => $`echo.js ${'foo'}\45+ ${'bar'}`, 'foo\nbar');46+test('$ can use escaped newlines and space indentations after an expression', testScriptStdout, () => $`echo.js ${'foo'}\47+ bar`, 'foo\nbar');48+test('$ can use escaped newlines and tab indentations after an expression', testScriptStdout, () => $`echo.js ${'foo'}\49+ bar`, 'foo\nbar');50+test('$ can use escaped newlines before an expression', testScriptStdout, () => $`echo.js foo\51+${'bar'}`, 'foobar');52 test('$ can use Windows newlines and tab indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n\tbar'), 'foo\nbar');53 test('$ can use Windows newlines and space indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n bar'), 'foo\nbar');54 test('$ does not ignore comments in expressions', testScriptStdout, () => $`echo.js foo55 ${/* This is a comment */''}200 unmodified lines256 test('$ splits tokens - \\u{0000063}', testScriptStdout, () => $`echo.js a\u{0000063}b`, 'acb');257 test('$ splits expressions - \\u{0000063}', testScriptStdout, () => $`echo.js ${'a'}\u{0000063}${'b'}`, 'acb');258 test('$ concatenates tokens - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}a\u{0000063} b`, 'cac\nb');259 test('$ concatenates expressions - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}${'a'}\u{0000063} b`, 'cac\nb');260+261+// Code points above the BMP are a surrogate pair, i.e. two characters, in the template string but not in its raw version.262+// Miscounting them shifts every following character, which splits tokens at the wrong place and breaks the surrogate pair.263+test('$ handles tokens - \\u{1F600}', testScriptStdout, () => $`echo.js \u{1F600}`, '\u{1F600}');264+test('$ splits tokens - \\u{1F600}', testScriptStdout, () => $`echo.js a\u{1F600}b`, 'a\u{1F600}b');265+test('$ splits expressions - \\u{1F600}', testScriptStdout, () => $`echo.js ${'a'}\u{1F600}${'b'}`, 'a\u{1F600}b');266+test('$ concatenates tokens - \\u{1F600}', testScriptStdout, () => $`echo.js \u{1F600}a\u{1F600} b`, '\u{1F600}a\u{1F600}\nb');267+test('$ concatenates expressions - \\u{1F600}', testScriptStdout, () => $`echo.js \u{1F600}${'a'}\u{1F600} b`, '\u{1F600}a\u{1F600}\nb');268+test('$ handles multiple tokens - \\u{1F600}', testScriptStdout, () => $`echo.js \u{1F600}\u{1F600} b c`, '\u{1F600}\u{1F600}\nb\nc');269+test('$ handles the highest code point - \\u{10FFFF}', testScriptStdout, () => $`echo.js \u{10FFFF} b`, '\u{10FFFF}\nb');270+// The BMP boundary is the exact point where the character count changes271+test('$ handles the last BMP code point - \\u{FFFF}', testScriptStdout, () => $`echo.js \u{FFFF} b`, '\u{FFFF}\nb');272+test('$ handles the first astral code point - \\u{10000}', testScriptStdout, () => $`echo.js \u{10000} b`, '\u{10000}\nb');273 test('$ handles tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}`, 'c}');274 test('$ splits tokens - \\u{0063}}', testScriptStdout, () => $`echo.js a\u{0063}}b`, 'ac}b');275 test('$ splits expressions - \\u{0063}}', testScriptStdout, () => $`echo.js ${'a'}\u{0063}}${'b'}`, 'ac}b');276 test('$ concatenates tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}a\u{0063}} b`, 'c}ac}\nb');108 unmodified lines