Skip to content
Myr

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 file

Take it

Improve input validation (#838)ehmickybefore adoption8ee137c

line 1why, one step back
1import isPlainObject from 'is-plain-obj';

`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562

line 2why, one step back
2import {isBinary, binaryToString, isChildProcess, isExecaChildProcess} from './utils.js';

Split files (#837)ehmickybefore adoption672c2d7

lines 3–4why, one step back
3import {execa} from './async.js';
4import {execaSync} from './sync.js';

Split files (#791)ehmickybefore adoption932fb26

line 5why, one step back
5

Split files (#837)ehmickybefore adoption672c2d7

lines 6–7why, one step back
6const create$ = options => {
7 function $(templatesOrOptions, ...expressions) {

Improve input validation (#838)ehmickybefore adoption8ee137c

line 8why, one step back
8 if (isPlainObject(templatesOrOptions)) {

Split files (#837)ehmickybefore adoption672c2d7

lines 9–10why, one step back
9 return create$({...options, ...templatesOrOptions});
10 }

Split files (#791)ehmickybefore adoption932fb26

line 11why, one step back
11

Improve input validation (#838)ehmickybefore adoption8ee137c

lines 12–15why, one step back
12 if (!Array.isArray(templatesOrOptions)) {
13 throw new TypeError('Please use either $(option) or $`command`.');14 }15

Split files (#837)ehmickybefore adoption672c2d7

line 16why, one step back
16 const [file, ...args] = parseTemplates(templatesOrOptions, expressions);

`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562

line 17why, one step back
17 const childProcess = execa(file, args, normalizeScriptOptions(options));

Fix calling script `.pipe` multiple times (#846)ehmickybefore adoptionbd547e4

line 18why, one step back
18 return scriptWithPipe(childProcess);

Split files (#791)ehmickybefore adoption932fb26

lines 19–20why, one step back
19 }
20

Split files (#837)ehmickybefore adoption672c2d7

line 21why, one step back
21 $.sync = (templates, ...expressions) => {

Improve input validation (#838)ehmickybefore adoption8ee137c

line 22why, one step back
22 if (isPlainObject(templates)) {

Split files (#837)ehmickybefore adoption672c2d7

line 23why, one step back
23 throw new TypeError('Please use $(options).sync`command` instead of $.sync(options)`command`.');

Improve input validation (#838)ehmickybefore adoption8ee137c

lines 24–27why, one step back
24 }
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 back
28 }
29

Split files (#837)ehmickybefore adoption672c2d7

lines 30–32why, one step back
30 const [file, ...args] = parseTemplates(templates, expressions);
31 return execaSync(file, args, normalizeScriptOptions(options));32 };

Split files (#791)ehmickybefore adoption932fb26

line 33why, one step back
33

Split files (#837)ehmickybefore adoption672c2d7

line 34why, one step back
34 $.s = $.sync;

Split files (#791)ehmickybefore adoption932fb26

line 35why, one step back
35

Split files (#837)ehmickybefore adoption672c2d7

line 36why, one step back
36 return $;

Split files (#791)ehmickybefore adoption932fb26

lines 37–38why, one step back
37};
38

Split files (#837)ehmickybefore adoption672c2d7

line 39why, one step back
39export const $ = create$();

Split files (#791)ehmickybefore adoption932fb26

line 40why, one step back
40

Fix calling script `.pipe` multiple times (#846)ehmickybefore adoptionbd547e4

lines 41–48why, one step back
41const 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 back
49 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 }53

Fix calling script `.pipe` multiple times (#846)ehmickybefore adoptionbd547e4

line 54why, one step back
54 return pipeMethod(firstArgument, ...args);

`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562

lines 55–57why, one step back
55 }
5657 if (isPlainObject(firstArgument)) {

Fix calling script `.pipe` multiple times (#846)ehmickybefore adoptionbd547e4

line 58why, one step back
58 return scriptPipe.bind(undefined, pipeMethod, {...options, ...firstArgument});

`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562

lines 59–65why, one step back
59 }
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 back
66 return pipeMethod(childProcess, options);

`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562

lines 67–68why, one step back
67};
68

Split files (#837)ehmickybefore adoption672c2d7

lines 69–70why, one step back
69const parseTemplates = (templates, expressions) => {
70 let tokens = [];

Split files (#791)ehmickybefore adoption932fb26

line 71why, one step back
71

Split files (#837)ehmickybefore adoption672c2d7

lines 72–75why, one step back
72 for (const [index, template] of templates.entries()) {
73 tokens = parseTemplate({templates, expressions, tokens, index, template});74 }75

Allow newlines in `$` (#843)ehmickybefore adoption1315486

lines 76–79why, one step back
76 if (tokens.length === 0) {
77 throw new TypeError('Template script must not be empty');78 }79

Split files (#837)ehmickybefore adoption672c2d7

lines 80–82why, one step back
80 return tokens;
81};82

Split files (#791)ehmickybefore adoption932fb26

line 83why, one step back
83const parseTemplate = ({templates, expressions, tokens, index, template}) => {

Allow newlines in `$` (#843)ehmickybefore adoption1315486

lines 84–86why, one step back
84 if (template === undefined) {
85 throw new TypeError(`Invalid backslash sequence: ${templates.raw[index]}`);86 }

Split files (#791)ehmickybefore adoption932fb26

line 87why, one step back
87

Allow newlines in `$` (#843)ehmickybefore adoption1315486

lines 88–90why, one step back
88 const {nextTokens, leadingWhitespaces, trailingWhitespaces} = splitByWhitespaces(template, templates.raw[index]);
89 const newTokens = concatTokens(tokens, nextTokens, leadingWhitespaces);90

Split files (#791)ehmickybefore adoption932fb26

lines 91–98why, one step back
91 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 back
99 return concatTokens(newTokens, expressionTokens, trailingWhitespaces);

Split files (#791)ehmickybefore adoption932fb26

lines 100–101why, one step back
100};
101

Allow newlines in `$` (#843)ehmickybefore adoption1315486

lines 102–111why, one step back
102// 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 back
112

Allow newlines in `$` (#843)ehmickybefore adoption1315486

lines 113–156why, one step back
113 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 === 0

Split files (#837)ehmickybefore adoption672c2d7

lines 157–168why, one step back
157 ? [...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 back
169 }
170

Split files (#837)ehmickybefore adoption672c2d7

lines 171–177why, one step back
171 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 back
178 && !isChildProcess(expression)

Split files (#837)ehmickybefore adoption672c2d7

lines 179–194why, one step back
179 && 'stdout' in expression
180 ) {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 back
195};
196

Split files (#837)ehmickybefore adoption672c2d7

lines 197–205why, one step back
197const 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 : {};