Skip to content
Myr

script.js

This file

Path

lib/script.js

206 lines · 6.2 KiB · JavaScript

Last changed by

Fix errors thrown by `.pipe()` (#854)ehmickybefore adoption46ba4b4

History of this file

Take it

Improve input validation (#838)ehmickybefore adoption8ee137c

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

Fix errors thrown by `.pipe()` (#854)ehmickybefore adoption46ba4b4

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

Split files (#837)ehmickybefore adoption672c2d7

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

Fix errors thrown by `.pipe()` (#854)ehmickybefore adoption46ba4b4

line 5why, one step back
5import {PROCESS_OPTIONS} from './pipe/validate.js';

Split files (#791)ehmickybefore adoption932fb26

line 6why, one step back
6

Split files (#837)ehmickybefore adoption672c2d7

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

Improve input validation (#838)ehmickybefore adoption8ee137c

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

Split files (#837)ehmickybefore adoption672c2d7

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

Split files (#791)ehmickybefore adoption932fb26

line 12why, one step back
12

Improve input validation (#838)ehmickybefore adoption8ee137c

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

Split files (#837)ehmickybefore adoption672c2d7

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

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

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

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

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

Split files (#791)ehmickybefore adoption932fb26

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

Split files (#837)ehmickybefore adoption672c2d7

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

Improve input validation (#838)ehmickybefore adoption8ee137c

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

Split files (#837)ehmickybefore adoption672c2d7

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

Improve input validation (#838)ehmickybefore adoption8ee137c

lines 25–28why, one step back
25 }
2627 if (!Array.isArray(templates)) {28 throw new TypeError('A template string must be used: $.sync`command`.');

Split files (#791)ehmickybefore adoption932fb26

lines 29–30why, one step back
29 }
30

Split files (#837)ehmickybefore adoption672c2d7

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

Split files (#791)ehmickybefore adoption932fb26

line 34why, one step back
34

Split files (#837)ehmickybefore adoption672c2d7

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

Split files (#791)ehmickybefore adoption932fb26

line 36why, one step back
36

Split files (#837)ehmickybefore adoption672c2d7

line 37why, one step back
37 return $;

Split files (#791)ehmickybefore adoption932fb26

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

Split files (#837)ehmickybefore adoption672c2d7

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

Split files (#791)ehmickybefore adoption932fb26

line 41why, one step back
41

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

lines 42–49why, one step back
42const scriptWithPipe = returnValue => {
43 const originalPipe = returnValue.pipe.bind(returnValue);44 const pipeMethod = (...args) => scriptWithPipe(originalPipe(...args));45 returnValue.pipe = scriptPipe.bind(undefined, pipeMethod, {});46 return returnValue;47};4849const scriptPipe = (pipeMethod, options, firstArgument, ...args) => {

Fix errors thrown by `.pipe()` (#854)ehmickybefore adoption46ba4b4

line 50why, one step back
50 if (PROCESS_OPTIONS.has(firstArgument)) {

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

lines 51–54why, one step back
51 if (Object.keys(options).length > 0) {
52 throw new TypeError('Please use .pipe(options)`command` or .pipe($(options)`command`) instead of .pipe(options)($`command`).');53 }54

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

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

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

lines 56–58why, one step back
56 }
5758 if (isPlainObject(firstArgument)) {

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

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

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

lines 60–66why, one step back
60 }
6162 if (!Array.isArray(firstArgument)) {63 throw new TypeError('The first argument must be a template string, an options object, or an Execa child process.');64 }6566 const childProcess = create$({...options, stdin: 'pipe'})(firstArgument, ...args);

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

line 67why, one step back
67 return pipeMethod(childProcess, options);

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

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

Split files (#837)ehmickybefore adoption672c2d7

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

Split files (#791)ehmickybefore adoption932fb26

line 72why, one step back
72

Split files (#837)ehmickybefore adoption672c2d7

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

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

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

Split files (#837)ehmickybefore adoption672c2d7

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

Split files (#791)ehmickybefore adoption932fb26

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

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

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

Split files (#791)ehmickybefore adoption932fb26

line 88why, one step back
88

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

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

Split files (#791)ehmickybefore adoption932fb26

lines 92–99why, one step back
92 if (index === expressions.length) {
93 return newTokens;94 }9596 const expression = expressions[index];97 const expressionTokens = Array.isArray(expression)98 ? expression.map(expression => parseExpression(expression))99 : [parseExpression(expression)];

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

line 100why, one step back
100 return concatTokens(newTokens, expressionTokens, trailingWhitespaces);

Split files (#791)ehmickybefore adoption932fb26

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

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

lines 103–112why, one step back
103// Like `string.split(/[ \t\r\n]+/)` except newlines and tabs are:
104// - ignored when input as a backslash sequence like: `echo foo\n bar`105// - not ignored when input directly106// The only way to distinguish those in JavaScript is to use a tagged template and compare:107// - the first array argument, which does not escape backslash sequences108// - its `raw` property, which escapes them109const splitByWhitespaces = (template, rawTemplate) => {110 if (rawTemplate.length === 0) {111 return {nextTokens: [], leadingWhitespaces: false, trailingWhitespaces: false};112 }

Split files (#791)ehmickybefore adoption932fb26

line 113why, one step back
113

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

lines 114–157why, one step back
114 const nextTokens = [];
115 let templateStart = 0;116 const leadingWhitespaces = DELIMITERS.has(rawTemplate[0]);117118 for (119 let templateIndex = 0, rawIndex = 0;120 templateIndex < template.length;121 templateIndex += 1, rawIndex += 1122 ) {123 const rawCharacter = rawTemplate[rawIndex];124 if (DELIMITERS.has(rawCharacter)) {125 if (templateStart !== templateIndex) {126 nextTokens.push(template.slice(templateStart, templateIndex));127 }128129 templateStart = templateIndex + 1;130 } else if (rawCharacter === '\\') {131 const nextRawCharacter = rawTemplate[rawIndex + 1];132 if (nextRawCharacter === 'u' && rawTemplate[rawIndex + 2] === '{') {133 rawIndex = rawTemplate.indexOf('}', rawIndex + 3);134 } else {135 rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;136 }137 }138 }139140 const trailingWhitespaces = templateStart === template.length;141 if (!trailingWhitespaces) {142 nextTokens.push(template.slice(templateStart));143 }144145 return {nextTokens, leadingWhitespaces, trailingWhitespaces};146};147148const DELIMITERS = new Set([' ', '\t', '\r', '\n']);149150// Number of characters in backslash escape sequences: \0 \xXX or \uXXXX151// \cX is allowed in RegExps but not in strings152// Octal sequences are not allowed in strict mode153const ESCAPE_LENGTH = {x: 3, u: 5};154155const concatTokens = (tokens, nextTokens, isSeparated) => isSeparated156 || tokens.length === 0157 || nextTokens.length === 0

Split files (#837)ehmickybefore adoption672c2d7

lines 158–169why, one step back
158 ? [...tokens, ...nextTokens]
159 : [160 ...tokens.slice(0, -1),161 `${tokens.at(-1)}${nextTokens[0]}`,162 ...nextTokens.slice(1),163 ];164165const parseExpression = expression => {166 const typeOfExpression = typeof expression;167168 if (typeOfExpression === 'string') {169 return expression;

Split files (#791)ehmickybefore adoption932fb26

lines 170–171why, one step back
170 }
171

Split files (#837)ehmickybefore adoption672c2d7

lines 172–178why, one step back
172 if (typeOfExpression === 'number') {
173 return String(expression);174 }175176 if (177 typeOfExpression === 'object'178 && expression !== null

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

line 179why, one step back
179 && !isChildProcess(expression)

Split files (#837)ehmickybefore adoption672c2d7

lines 180–195why, one step back
180 && 'stdout' in expression
181 ) {182 const typeOfStdout = typeof expression.stdout;183184 if (typeOfStdout === 'string') {185 return expression.stdout;186 }187188 if (isBinary(expression.stdout)) {189 return binaryToString(expression.stdout);190 }191192 throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`);193 }194195 throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);

Split files (#791)ehmickybefore adoption932fb26

lines 196–197why, one step back
196};
197

Split files (#837)ehmickybefore adoption672c2d7

lines 198–206why, one step back
198const normalizeScriptOptions = (options = {}) => ({
199 preferLocal: true,200 ...normalizeScriptStdin(options),201 ...options,202});203204const normalizeScriptStdin = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined205 ? {stdin: 'inherit'}206 : {};