template.js
This file
Path
lib/methods/template.js
183 lines · 6.6 KiB · JavaScript
Last changed by
Fix wrong-typed options and arguments being silently ignored or coercedSindre Sorhusbefore adoptionb57d643
History of this fileTake it
The walk stopped after 200 commits: lines older than 9f65b86 point at it.
100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 1–2why, one step back1import {ChildProcess} from 'node:child_process';2import isPlainObject from 'is-plain-obj';Fix template string tokenization of escape sequencesSindre Sorhusbefore adoptionb67f199
line 3why, one step back3import {ASTRAL_START} from '../arguments/escape.js';100% test coverage (#1018)ehmickybefore adoption9f65b86
line 4why, one step back4import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
line 5why, one step back5import {isExecaError} from '../return/final-error.js';Fix wrong-typed options and arguments being silently ignored or coercedSindre Sorhusbefore adoptionb57d643
line 6why, one step back6import {getTypeName} from '../utils/type-name.js';100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 7–13why, one step back78// Check whether the template string syntax is being used9export const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);1011// Convert execa`file ...commandArguments` to execa(file, commandArguments)12export const parseTemplates = (templates, expressions) => {13 let tokens = [];Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
lines 14–15why, one step back14 // Whether whitespaces separate the last token from the next one15 let isSeparated = false;100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 16–17why, one step back1617 for (const [index, template] of templates.entries()) {Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
line 18why, one step back18 ({tokens, isSeparated} = parseTemplate({100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 19–21why, one step back19 templates,20 expressions,21 tokens,Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
line 22why, one step back22 isSeparated,100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 23–24why, one step back23 index,24 template,Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
line 25why, one step back25 }));100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 26–35why, one step back26 }2728 if (tokens.length === 0) {29 throw new TypeError('Template script must not be empty');30 }3132 const [file, ...commandArguments] = tokens;33 return [file, commandArguments, {}];34};35Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
line 36why, one step back36const parseTemplate = ({templates, expressions, tokens, isSeparated, index, template}) => {100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 37–41why, one step back37 if (template === undefined) {38 throw new TypeError(`Invalid backslash sequence: ${templates.raw[index]}`);39 }4041 const {nextTokens, leadingWhitespaces, trailingWhitespaces} = splitByWhitespaces(template, templates.raw[index]);Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
lines 42–44why, one step back42 const newTokens = concatTokens(tokens, nextTokens, isSeparated || leadingWhitespaces);43 // When the template has no tokens, the whitespaces before it still separate the next token, e.g. after an empty array expression44 const isTemplateSeparated = trailingWhitespaces || (nextTokens.length === 0 && isSeparated);100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 45–46why, one step back4546 if (index === expressions.length) {Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
line 47why, one step back47 return {tokens: newTokens, isSeparated: isTemplateSeparated};100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 48–53why, one step back48 }4950 const expression = expressions[index];51 const expressionTokens = Array.isArray(expression)52 ? expression.map(expression => parseExpression(expression))53 : [parseExpression(expression)];Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
lines 54–57why, one step back54 return {55 tokens: concatTokens(newTokens, expressionTokens, isTemplateSeparated),56 isSeparated: expressionTokens.length === 0 && isTemplateSeparated,57 };100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 58–66why, one step back58};5960// Like `string.split(/[ \t\r\n]+/)` except newlines and tabs are:61// - ignored when input as a backslash sequence like: `echo foo\n bar`62// - not ignored when input directly63// The only way to distinguish those in JavaScript is to use a tagged template and compare:64// - the first array argument, which does not escape backslash sequences65// - its `raw` property, which escapes them66const splitByWhitespaces = (template, rawTemplate) => {Fix template string tokenization of escape sequencesSindre Sorhusbefore adoptionb67f199
lines 67–69why, one step back67 // The template is empty either between two `${expression}`, or when it only contains escaped newlines.68 // Neither holds any whitespace, so neither separates tokens.69 if (template.length === 0) {100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 70–74why, one step back70 return {nextTokens: [], leadingWhitespaces: false, trailingWhitespaces: false};71 }7273 const nextTokens = [];74 let templateStart = 0;Fix template string tokenization of escape sequencesSindre Sorhusbefore adoptionb67f199
line 75why, one step back75 let isLeadingWhitespaces = false;100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 76–83why, one step back7677 for (78 let templateIndex = 0, rawIndex = 0;79 templateIndex < template.length;80 templateIndex += 1, rawIndex += 181 ) {82 const rawCharacter = rawTemplate[rawIndex];83 if (DELIMITERS.has(rawCharacter)) {Fix template string tokenization of escape sequencesSindre Sorhusbefore adoptionb67f199
lines 84–88why, one step back84 // Escaped newlines are ignored, so a whitespace after them is still a leading one85 if (templateIndex === 0) {86 isLeadingWhitespaces = true;87 }88100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 89–95why, one step back89 if (templateStart !== templateIndex) {90 nextTokens.push(template.slice(templateStart, templateIndex));91 }9293 templateStart = templateIndex + 1;94 } else if (rawCharacter === '\\') {95 const nextRawCharacter = rawTemplate[rawIndex + 1];Fixes argument parsing for escaped newlines (#1176)Aaron Dandybefore adoption2aa3b0c
lines 96–100why, one step back96 if (nextRawCharacter === '\n') {97 // Handles escaped newlines in templates98 templateIndex -= 1;99 rawIndex += 1;100 } else if (nextRawCharacter === 'u' && rawTemplate[rawIndex + 2] === '{') {Fix template string tokenization of escape sequencesSindre Sorhusbefore adoptionb67f199
lines 101–107why, one step back101 const closingBraceIndex = rawTemplate.indexOf('}', rawIndex + 3);102 // A code point above the BMP is a surrogate pair, i.e. two characters, in the template string103 if (isAstralEscape(rawTemplate.slice(rawIndex + 3, closingBraceIndex))) {104 templateIndex += 1;105 }106107 rawIndex = closingBraceIndex;100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 108–113why, one step back108 } else {109 rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;110 }111 }112 }113Update dev dependencies (#1257)Sindre Sorhusbefore adoption5944b2d
lines 114–115why, one step back114 const isTrailingWhitespaces = templateStart === template.length;115 if (!isTrailingWhitespaces) {100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 116–118why, one step back116 nextTokens.push(template.slice(templateStart));117 }118Update dev dependencies (#1257)Sindre Sorhusbefore adoption5944b2d
line 119why, one step back119 return {nextTokens, leadingWhitespaces: isLeadingWhitespaces, trailingWhitespaces: isTrailingWhitespaces};100% test coverage (#1018)ehmickybefore adoption9f65b86
line 120why, one step back120};Fix template string tokenization of escape sequencesSindre Sorhusbefore adoptionb67f199
lines 121–122why, one step back121122const isAstralEscape = codePointHex => Number.parseInt(codePointHex, 16) > ASTRAL_START;100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 123–142why, one step back123124const DELIMITERS = new Set([' ', '\t', '\r', '\n']);125126// Number of characters in backslash escape sequences: \0 \xXX or \uXXXX127// \cX is allowed in RegExps but not in strings128// Octal sequences are not allowed in strict mode129const ESCAPE_LENGTH = {x: 3, u: 5};130131const concatTokens = (tokens, nextTokens, isSeparated) => isSeparated132 || tokens.length === 0133 || nextTokens.length === 0134 ? [...tokens, ...nextTokens]135 : [136 ...tokens.slice(0, -1),137 `${tokens.at(-1)}${nextTokens[0]}`,138 ...nextTokens.slice(1),139 ];140141// Handle `${expression}` inside the template string syntax142const parseExpression = expression => {Fix wrong-typed options and arguments being silently ignored or coercedSindre Sorhusbefore adoptionb57d643
line 143why, one step back143 const typeOfExpression = getTypeName(expression);100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 144–152why, one step back144145 if (typeOfExpression === 'string') {146 return expression;147 }148149 if (typeOfExpression === 'number') {150 return String(expression);151 }152Fix template strings, `parseCommandString()` and `execaNode()` edge casesSindre Sorhusbefore adoptionfb92da1
lines 153–155why, one step back153 // Only own properties are checked: a polluted `Object.prototype.stdout` must not turn any plain object into a subprocess result.154 // A failed subprocess result is an error instance instead.155 if ((isPlainObject(expression) || isExecaError(expression)) && (Object.hasOwn(expression, 'stdout') || Object.hasOwn(expression, 'isMaxBuffer'))) {100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 156–166why, one step back156 return getSubprocessResult(expression);157 }158159 if (expression instanceof ChildProcess || Object.prototype.toString.call(expression) === '[object Promise]') {160 // eslint-disable-next-line no-template-curly-in-string161 throw new TypeError('Unexpected subprocess in template expression. Please use ${await subprocess} instead of ${subprocess}.');162 }163164 throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);165};166Harden some thingsSindre Sorhusbefore adoption4a0a121
lines 167–169why, one step back167const getSubprocessResult = result => {168 // Read the own property only: results with `stdout: 'ignore'` have no `stdout` property, which must not be read from a polluted prototype169 const stdout = Object.hasOwn(result, 'stdout') ? result.stdout : undefined;100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 170–181why, one step back170 if (typeof stdout === 'string') {171 return stdout;172 }173174 if (isUint8Array(stdout)) {175 return uint8ArrayToString(stdout);176 }177178 if (stdout === undefined) {179 throw new TypeError('Missing result.stdout in template expression. This is probably due to the previous subprocess\' "stdout" option.');180 }181Fix wrong-typed options and arguments being silently ignored or coercedSindre Sorhusbefore adoptionb57d643
line 182why, one step back182 throw new TypeError(`Unexpected "${getTypeName(stdout)}" stdout in template expression`);100% test coverage (#1018)ehmickybefore adoption9f65b86
line 183why, one step back183};