script.js
This file
Path
lib/script.js
205 lines · 6.2 KiB · JavaScript
Last changed by
Allow newlines in `$` (#843)ehmickybefore adoption1315486
History of this fileTake it
Improve input validation (#838)ehmickybefore adoption8ee137c
line 1why, one step back1import isPlainObject from 'is-plain-obj';`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562
line 2why, one step back2import {isBinary, binaryToString, isChildProcess, isExecaChildProcess} from './utils.js';Split files (#837)ehmickybefore adoption672c2d7
lines 3–4why, one step back3import {execa} from './async.js';4import {execaSync} from './sync.js';Split files (#791)ehmickybefore adoption932fb26
line 5why, one step back5Split files (#837)ehmickybefore adoption672c2d7
lines 6–7why, one step back6const create$ = options => {7 function $(templatesOrOptions, ...expressions) {Improve input validation (#838)ehmickybefore adoption8ee137c
line 8why, one step back8 if (isPlainObject(templatesOrOptions)) {Split files (#837)ehmickybefore adoption672c2d7
lines 9–10why, one step back9 return create$({...options, ...templatesOrOptions});10 }Split files (#791)ehmickybefore adoption932fb26
line 11why, one step back11Improve input validation (#838)ehmickybefore adoption8ee137c
lines 12–15why, one step back12 if (!Array.isArray(templatesOrOptions)) {13 throw new TypeError('Please use either $(option) or $`command`.');14 }15Split files (#837)ehmickybefore adoption672c2d7
line 16why, one step back16 const [file, ...args] = parseTemplates(templatesOrOptions, expressions);`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562
line 17why, one step back17 const childProcess = execa(file, args, normalizeScriptOptions(options));Fix calling script `.pipe` multiple times (#846)ehmickybefore adoptionbd547e4
line 18why, one step back18 return scriptWithPipe(childProcess);Split files (#791)ehmickybefore adoption932fb26
lines 19–20why, one step back19 }20Split files (#837)ehmickybefore adoption672c2d7
line 21why, one step back21 $.sync = (templates, ...expressions) => {Improve input validation (#838)ehmickybefore adoption8ee137c
line 22why, one step back22 if (isPlainObject(templates)) {Split files (#837)ehmickybefore adoption672c2d7
line 23why, one step back23 throw new TypeError('Please use $(options).sync`command` instead of $.sync(options)`command`.');Improve input validation (#838)ehmickybefore adoption8ee137c
lines 24–27why, one step back24 }2526 if (!Array.isArray(templates)) {27 throw new TypeError('A template string must be used: $.sync`command`.');Split files (#791)ehmickybefore adoption932fb26
lines 28–29why, one step back28 }29Split files (#837)ehmickybefore adoption672c2d7
lines 30–32why, one step back30 const [file, ...args] = parseTemplates(templates, expressions);31 return execaSync(file, args, normalizeScriptOptions(options));32 };Split files (#791)ehmickybefore adoption932fb26
line 33why, one step back33Split files (#837)ehmickybefore adoption672c2d7
line 34why, one step back34 $.s = $.sync;Split files (#791)ehmickybefore adoption932fb26
line 35why, one step back35Split files (#837)ehmickybefore adoption672c2d7
line 36why, one step back36 return $;Split files (#791)ehmickybefore adoption932fb26
lines 37–38why, one step back37};38Split files (#837)ehmickybefore adoption672c2d7
line 39why, one step back39export const $ = create$();Split files (#791)ehmickybefore adoption932fb26
line 40why, one step back40Fix calling script `.pipe` multiple times (#846)ehmickybefore adoptionbd547e4
lines 41–48why, one step back41const scriptWithPipe = returnValue => {42 const originalPipe = returnValue.pipe.bind(returnValue);43 const pipeMethod = (...args) => scriptWithPipe(originalPipe(...args));44 returnValue.pipe = scriptPipe.bind(undefined, pipeMethod, {});45 return returnValue;46};4748const scriptPipe = (pipeMethod, options, firstArgument, ...args) => {`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562
lines 49–53why, one step back49 if (isExecaChildProcess(firstArgument)) {50 if (Object.keys(options).length > 0) {51 throw new TypeError('Please use .pipe(options)`command` or .pipe($(options)`command`) instead of .pipe(options)($`command`).');52 }53Fix calling script `.pipe` multiple times (#846)ehmickybefore adoptionbd547e4
line 54why, one step back54 return pipeMethod(firstArgument, ...args);`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562
lines 55–57why, one step back55 }5657 if (isPlainObject(firstArgument)) {Fix calling script `.pipe` multiple times (#846)ehmickybefore adoptionbd547e4
line 58why, one step back58 return scriptPipe.bind(undefined, pipeMethod, {...options, ...firstArgument});`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562
lines 59–65why, one step back59 }6061 if (!Array.isArray(firstArgument)) {62 throw new TypeError('The first argument must be a template string, an options object, or an Execa child process.');63 }6465 const childProcess = create$({...options, stdin: 'pipe'})(firstArgument, ...args);Fix calling script `.pipe` multiple times (#846)ehmickybefore adoptionbd547e4
line 66why, one step back66 return pipeMethod(childProcess, options);`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562
lines 67–68why, one step back67};68Split files (#837)ehmickybefore adoption672c2d7
lines 69–70why, one step back69const parseTemplates = (templates, expressions) => {70 let tokens = [];Split files (#791)ehmickybefore adoption932fb26
line 71why, one step back71Split files (#837)ehmickybefore adoption672c2d7
lines 72–75why, one step back72 for (const [index, template] of templates.entries()) {73 tokens = parseTemplate({templates, expressions, tokens, index, template});74 }75Allow newlines in `$` (#843)ehmickybefore adoption1315486
lines 76–79why, one step back76 if (tokens.length === 0) {77 throw new TypeError('Template script must not be empty');78 }79Split files (#837)ehmickybefore adoption672c2d7
lines 80–82why, one step back80 return tokens;81};82Split files (#791)ehmickybefore adoption932fb26
line 83why, one step back83const parseTemplate = ({templates, expressions, tokens, index, template}) => {Allow newlines in `$` (#843)ehmickybefore adoption1315486
lines 84–86why, one step back84 if (template === undefined) {85 throw new TypeError(`Invalid backslash sequence: ${templates.raw[index]}`);86 }Split files (#791)ehmickybefore adoption932fb26
line 87why, one step back87Allow newlines in `$` (#843)ehmickybefore adoption1315486
lines 88–90why, one step back88 const {nextTokens, leadingWhitespaces, trailingWhitespaces} = splitByWhitespaces(template, templates.raw[index]);89 const newTokens = concatTokens(tokens, nextTokens, leadingWhitespaces);90Split files (#791)ehmickybefore adoption932fb26
lines 91–98why, one step back91 if (index === expressions.length) {92 return newTokens;93 }9495 const expression = expressions[index];96 const expressionTokens = Array.isArray(expression)97 ? expression.map(expression => parseExpression(expression))98 : [parseExpression(expression)];Allow newlines in `$` (#843)ehmickybefore adoption1315486
line 99why, one step back99 return concatTokens(newTokens, expressionTokens, trailingWhitespaces);Split files (#791)ehmickybefore adoption932fb26
lines 100–101why, one step back100};101Allow newlines in `$` (#843)ehmickybefore adoption1315486
lines 102–111why, one step back102// Like `string.split(/[ \t\r\n]+/)` except newlines and tabs are:103// - ignored when input as a backslash sequence like: `echo foo\n bar`104// - not ignored when input directly105// The only way to distinguish those in JavaScript is to use a tagged template and compare:106// - the first array argument, which does not escape backslash sequences107// - its `raw` property, which escapes them108const splitByWhitespaces = (template, rawTemplate) => {109 if (rawTemplate.length === 0) {110 return {nextTokens: [], leadingWhitespaces: false, trailingWhitespaces: false};111 }Split files (#791)ehmickybefore adoption932fb26
line 112why, one step back112Allow newlines in `$` (#843)ehmickybefore adoption1315486
lines 113–156why, one step back113 const nextTokens = [];114 let templateStart = 0;115 const leadingWhitespaces = DELIMITERS.has(rawTemplate[0]);116117 for (118 let templateIndex = 0, rawIndex = 0;119 templateIndex < template.length;120 templateIndex += 1, rawIndex += 1121 ) {122 const rawCharacter = rawTemplate[rawIndex];123 if (DELIMITERS.has(rawCharacter)) {124 if (templateStart !== templateIndex) {125 nextTokens.push(template.slice(templateStart, templateIndex));126 }127128 templateStart = templateIndex + 1;129 } else if (rawCharacter === '\\') {130 const nextRawCharacter = rawTemplate[rawIndex + 1];131 if (nextRawCharacter === 'u' && rawTemplate[rawIndex + 2] === '{') {132 rawIndex = rawTemplate.indexOf('}', rawIndex + 3);133 } else {134 rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;135 }136 }137 }138139 const trailingWhitespaces = templateStart === template.length;140 if (!trailingWhitespaces) {141 nextTokens.push(template.slice(templateStart));142 }143144 return {nextTokens, leadingWhitespaces, trailingWhitespaces};145};146147const DELIMITERS = new Set([' ', '\t', '\r', '\n']);148149// Number of characters in backslash escape sequences: \0 \xXX or \uXXXX150// \cX is allowed in RegExps but not in strings151// Octal sequences are not allowed in strict mode152const ESCAPE_LENGTH = {x: 3, u: 5};153154const concatTokens = (tokens, nextTokens, isSeparated) => isSeparated155 || tokens.length === 0156 || nextTokens.length === 0Split files (#837)ehmickybefore adoption672c2d7
lines 157–168why, one step back157 ? [...tokens, ...nextTokens]158 : [159 ...tokens.slice(0, -1),160 `${tokens.at(-1)}${nextTokens[0]}`,161 ...nextTokens.slice(1),162 ];163164const parseExpression = expression => {165 const typeOfExpression = typeof expression;166167 if (typeOfExpression === 'string') {168 return expression;Split files (#791)ehmickybefore adoption932fb26
lines 169–170why, one step back169 }170Split files (#837)ehmickybefore adoption672c2d7
lines 171–177why, one step back171 if (typeOfExpression === 'number') {172 return String(expression);173 }174175 if (176 typeOfExpression === 'object'177 && expression !== null`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562
line 178why, one step back178 && !isChildProcess(expression)Split files (#837)ehmickybefore adoption672c2d7
lines 179–194why, one step back179 && 'stdout' in expression180 ) {181 const typeOfStdout = typeof expression.stdout;182183 if (typeOfStdout === 'string') {184 return expression.stdout;185 }186187 if (isBinary(expression.stdout)) {188 return binaryToString(expression.stdout);189 }190191 throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`);192 }193194 throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);Split files (#791)ehmickybefore adoption932fb26
lines 195–196why, one step back195};196Split files (#837)ehmickybefore adoption672c2d7
lines 197–205why, one step back197const normalizeScriptOptions = (options = {}) => ({198 preferLocal: true,199 ...normalizeScriptStdin(options),200 ...options,201});202203const normalizeScriptStdin = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined204 ? {stdin: 'inherit'}205 : {};