Socket
Socket
Sign inDemoInstall

npm-run-all2

Package Overview
Dependencies
Maintainers
2
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

npm-run-all2 - npm Package Compare versions

Comparing version 6.0.5 to 6.0.6

74

bin/common/bootstrap.js

@@ -6,47 +6,47 @@ /**

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/*eslint-disable no-process-exit */
// ------------------------------------------------------------------------------
/* eslint-disable no-process-exit */
module.exports = function bootstrap(name) {
const argv = process.argv.slice(2)
module.exports = function bootstrap (name) {
const argv = process.argv.slice(2)
switch (argv[0]) {
case undefined:
case "-h":
case "--help":
return require(`../${name}/help`)(process.stdout)
switch (argv[0]) {
case undefined:
case '-h':
case '--help':
return require(`../${name}/help`)(process.stdout)
case "-v":
case "--version":
return require("./version")(process.stdout)
case '-v':
case '--version':
return require('./version')(process.stdout)
default:
// https://github.com/mysticatea/npm-run-all/issues/105
// Avoid MaxListenersExceededWarnings.
process.stdout.setMaxListeners(0)
process.stderr.setMaxListeners(0)
process.stdin.setMaxListeners(0)
default:
// https://github.com/mysticatea/npm-run-all/issues/105
// Avoid MaxListenersExceededWarnings.
process.stdout.setMaxListeners(0)
process.stderr.setMaxListeners(0)
process.stdin.setMaxListeners(0)
// Main
return require(`../${name}/main`)(
argv,
process.stdout,
process.stderr
).then(
() => {
// I'm not sure why, but maybe the process never exits
// on Git Bash (MINGW64)
process.exit(0)
},
() => {
process.exit(1)
}
)
}
// Main
return require(`../${name}/main`)(
argv,
process.stdout,
process.stderr
).then(
() => {
// I'm not sure why, but maybe the process never exits
// on Git Bash (MINGW64)
process.exit(0)
},
() => {
process.exit(1)
}
)
}
}
/*eslint-enable */
/* eslint-enable */

@@ -6,9 +6,9 @@ /**

*/
"use strict"
'use strict'
/*eslint-disable no-process-env */
/* eslint-disable no-process-env */
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -29,5 +29,5 @@ const OVERWRITE_OPTION = /^--([^:]+?):([^=]+?)(?:=(.+))?$/

*/
function overwriteConfig(config, packageName, variable, value) {
const scope = config[packageName] || (config[packageName] = {})
scope[variable] = value
function overwriteConfig (config, packageName, variable, value) {
const scope = config[packageName] || (config[packageName] = {})
scope[variable] = value
}

@@ -41,17 +41,17 @@

*/
function createPackageConfig() {
const retv = {}
const packageName = process.env.npm_package_name
if (!packageName) {
return retv
}
function createPackageConfig () {
const retv = {}
const packageName = process.env.npm_package_name
if (!packageName) {
return retv
}
for (const key of Object.keys(process.env)) {
const m = PACKAGE_CONFIG_PATTERN.exec(key)
if (m != null) {
overwriteConfig(retv, packageName, m[1], process.env[key])
}
for (const key of Object.keys(process.env)) {
const m = PACKAGE_CONFIG_PATTERN.exec(key)
if (m != null) {
overwriteConfig(retv, packageName, m[1], process.env[key])
}
}
return retv
return retv
}

@@ -66,7 +66,7 @@

*/
function addGroup(groups, initialValues) {
groups.push(Object.assign(
{ parallel: false, patterns: [] },
initialValues || {}
))
function addGroup (groups, initialValues) {
groups.push(Object.assign(
{ parallel: false, patterns: [] },
initialValues || {}
))
}

@@ -79,36 +79,36 @@

class ArgumentSet {
/**
/**
* @param {object} initialValues - A key-value map for the default of new value.
* @param {object} options - A key-value map for the options.
*/
constructor(initialValues, options) {
this.config = {}
this.continueOnError = false
this.groups = []
this.maxParallel = 0
this.npmPath = null
this.packageConfig = createPackageConfig()
this.printLabel = false
this.printName = false
this.race = false
this.rest = []
this.silent = process.env.npm_config_loglevel === "silent"
this.singleMode = Boolean(options && options.singleMode)
constructor (initialValues, options) {
this.config = {}
this.continueOnError = false
this.groups = []
this.maxParallel = 0
this.npmPath = null
this.packageConfig = createPackageConfig()
this.printLabel = false
this.printName = false
this.race = false
this.rest = []
this.silent = process.env.npm_config_loglevel === 'silent'
this.singleMode = Boolean(options && options.singleMode)
addGroup(this.groups, initialValues)
}
addGroup(this.groups, initialValues)
}
/**
/**
* Gets the last group.
*/
get lastGroup() {
return this.groups[this.groups.length - 1]
}
get lastGroup () {
return this.groups[this.groups.length - 1]
}
/**
/**
* Gets "parallel" flag.
*/
get parallel() {
return this.groups.some(g => g.parallel)
}
get parallel () {
return this.groups.some(g => g.parallel)
}
}

@@ -123,120 +123,116 @@

*/
function parseCLIArgsCore(set, args) { // eslint-disable-line complexity
LOOP:
for (let i = 0; i < args.length; ++i) {
const arg = args[i]
function parseCLIArgsCore (set, args) {
LOOP: // eslint-disable-line no-labels
for (let i = 0; i < args.length; ++i) {
const arg = args[i]
switch (arg) {
case "--":
set.rest = args.slice(1 + i)
break LOOP
switch (arg) {
case '--':
set.rest = args.slice(1 + i)
break LOOP // eslint-disable-line no-labels
case "--color":
case "--no-color":
// do nothing.
break
case '--color':
case '--no-color':
// do nothing.
break
case "-c":
case "--continue-on-error":
set.continueOnError = true
break
case '-c':
case '--continue-on-error':
set.continueOnError = true
break
case "-l":
case "--print-label":
set.printLabel = true
break
case '-l':
case '--print-label':
set.printLabel = true
break
case "-n":
case "--print-name":
set.printName = true
break
case '-n':
case '--print-name':
set.printName = true
break
case "-r":
case "--race":
set.race = true
break
case '-r':
case '--race':
set.race = true
break
case "--silent":
set.silent = true
break
case '--silent':
set.silent = true
break
case "--max-parallel":
set.maxParallel = parseInt(args[++i], 10)
if (!Number.isFinite(set.maxParallel) || set.maxParallel <= 0) {
throw new Error(`Invalid Option: --max-parallel ${args[i]}`)
}
break
case '--max-parallel':
set.maxParallel = parseInt(args[++i], 10)
if (!Number.isFinite(set.maxParallel) || set.maxParallel <= 0) {
throw new Error(`Invalid Option: --max-parallel ${args[i]}`)
}
break
case "-s":
case "--sequential":
case "--serial":
if (set.singleMode && arg === "-s") {
set.silent = true
break
}
if (set.singleMode) {
throw new Error(`Invalid Option: ${arg}`)
}
addGroup(set.groups)
break
case '-s':
case '--sequential':
case '--serial':
if (set.singleMode && arg === '-s') {
set.silent = true
break
}
if (set.singleMode) {
throw new Error(`Invalid Option: ${arg}`)
}
addGroup(set.groups)
break
case "--aggregate-output":
set.aggregateOutput = true
break
case '--aggregate-output':
set.aggregateOutput = true
break
case "-p":
case "--parallel":
if (set.singleMode) {
throw new Error(`Invalid Option: ${arg}`)
}
addGroup(set.groups, { parallel: true })
break
case '-p':
case '--parallel':
if (set.singleMode) {
throw new Error(`Invalid Option: ${arg}`)
}
addGroup(set.groups, { parallel: true })
break
case "--npm-path":
set.npmPath = args[++i] || null
break
case '--npm-path':
set.npmPath = args[++i] || null
break
default: {
let matched = null
if ((matched = OVERWRITE_OPTION.exec(arg))) {
overwriteConfig(
set.packageConfig,
matched[1],
matched[2],
matched[3] || args[++i]
)
}
else if ((matched = CONFIG_OPTION.exec(arg))) {
set.config[matched[1]] = matched[2]
}
else if (CONCAT_OPTIONS.test(arg)) {
parseCLIArgsCore(
set,
arg.slice(1).split("").map(c => `-${c}`)
)
}
else if (arg[0] === "-") {
throw new Error(`Invalid Option: ${arg}`)
}
else {
set.lastGroup.patterns.push(arg)
}
break
}
default: {
let matched = null
if ((matched = OVERWRITE_OPTION.exec(arg))) {
overwriteConfig(
set.packageConfig,
matched[1],
matched[2],
matched[3] || args[++i]
)
} else if ((matched = CONFIG_OPTION.exec(arg))) {
set.config[matched[1]] = matched[2]
} else if (CONCAT_OPTIONS.test(arg)) {
parseCLIArgsCore(
set,
arg.slice(1).split('').map(c => `-${c}`)
)
} else if (arg[0] === '-') {
throw new Error(`Invalid Option: ${arg}`)
} else {
set.lastGroup.patterns.push(arg)
}
}
if (!set.parallel && set.aggregateOutput) {
throw new Error("Invalid Option: --aggregate-output (without parallel)")
break
}
}
if (!set.parallel && set.race) {
const race = args.indexOf("--race") !== -1 ? "--race" : "-r"
throw new Error(`Invalid Option: ${race} (without parallel)`)
}
if (!set.parallel && set.maxParallel !== 0) {
throw new Error("Invalid Option: --max-parallel (without parallel)")
}
}
return set
if (!set.parallel && set.aggregateOutput) {
throw new Error('Invalid Option: --aggregate-output (without parallel)')
}
if (!set.parallel && set.race) {
const race = args.indexOf('--race') !== -1 ? '--race' : '-r'
throw new Error(`Invalid Option: ${race} (without parallel)`)
}
if (!set.parallel && set.maxParallel !== 0) {
throw new Error('Invalid Option: --max-parallel (without parallel)')
}
return set
}

@@ -253,6 +249,6 @@

*/
module.exports = function parseCLIArgs(args, initialValues, options) {
return parseCLIArgsCore(new ArgumentSet(initialValues, options), args)
module.exports = function parseCLIArgs (args, initialValues, options) {
return parseCLIArgsCore(new ArgumentSet(initialValues, options), args)
}
/*eslint-enable */
/* eslint-enable */

@@ -6,7 +6,7 @@ /**

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -20,8 +20,8 @@ /**

*/
module.exports = function printVersion(output) {
const version = require("../../package.json").version
module.exports = function printVersion (output) {
const version = require('../../package.json').version
output.write(`v${version}\n`)
output.write(`v${version}\n`)
return Promise.resolve(null)
return Promise.resolve(null)
}

@@ -6,7 +6,7 @@ /**

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -20,4 +20,4 @@ /**

*/
module.exports = function printHelp(output) {
output.write(`
module.exports = function printHelp (output) {
output.write(`
Usage:

@@ -72,3 +72,3 @@ $ npm-run-all [--help | -h | --version | -v]

return Promise.resolve(null)
return Promise.resolve(null)
}

@@ -7,8 +7,8 @@ #!/usr/bin/env node

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Main
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
require("../common/bootstrap")("npm-run-all")
require('../common/bootstrap')('npm-run-all')

@@ -6,14 +6,14 @@ /**

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
const runAll = require("../../lib")
const parseCLIArgs = require("../common/parse-cli-args")
const runAll = require('../../lib')
const parseCLIArgs = require('../common/parse-cli-args')
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -29,51 +29,50 @@ /**

*/
module.exports = function npmRunAll(args, stdout, stderr) {
try {
const stdin = process.stdin
const argv = parseCLIArgs(args)
module.exports = function npmRunAll (args, stdout, stderr) {
try {
const stdin = process.stdin
const argv = parseCLIArgs(args)
const promise = argv.groups.reduce(
(prev, group) => {
if (group.patterns.length === 0) {
return prev
}
return prev.then(() => runAll(
group.patterns,
{
stdout,
stderr,
stdin,
parallel: group.parallel,
maxParallel: group.parallel ? argv.maxParallel : 1,
continueOnError: argv.continueOnError,
printLabel: argv.printLabel,
printName: argv.printName,
config: argv.config,
packageConfig: argv.packageConfig,
silent: argv.silent,
arguments: argv.rest,
race: group.parallel && argv.race,
npmPath: argv.npmPath,
aggregateOutput: group.parallel && argv.aggregateOutput,
}
))
},
Promise.resolve(null)
)
if (!argv.silent) {
promise.catch(err => {
//eslint-disable-next-line no-console
console.error("ERROR:", err.message)
})
const promise = argv.groups.reduce(
(prev, group) => {
if (group.patterns.length === 0) {
return prev
}
return prev.then(() => runAll(
group.patterns,
{
stdout,
stderr,
stdin,
parallel: group.parallel,
maxParallel: group.parallel ? argv.maxParallel : 1,
continueOnError: argv.continueOnError,
printLabel: argv.printLabel,
printName: argv.printName,
config: argv.config,
packageConfig: argv.packageConfig,
silent: argv.silent,
arguments: argv.rest,
race: group.parallel && argv.race,
npmPath: argv.npmPath,
aggregateOutput: group.parallel && argv.aggregateOutput
}
))
},
Promise.resolve(null)
)
return promise
if (!argv.silent) {
promise.catch(err => {
// eslint-disable-next-line no-console
console.error('ERROR:', err.message)
})
}
catch (err) {
//eslint-disable-next-line no-console
console.error("ERROR:", err.message)
return Promise.reject(err)
}
return promise
} catch (err) {
// eslint-disable-next-line no-console
console.error('ERROR:', err.message)
return Promise.reject(err)
}
}

@@ -6,7 +6,7 @@ /**

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -20,4 +20,4 @@ /**

*/
module.exports = function printHelp(output) {
output.write(`
module.exports = function printHelp (output) {
output.write(`
Usage:

@@ -67,3 +67,3 @@ $ run-p [--help | -h | --version | -v]

return Promise.resolve(null)
return Promise.resolve(null)
}

@@ -7,8 +7,8 @@ #!/usr/bin/env node

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Main
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
require("../common/bootstrap")("run-p")
require('../common/bootstrap')('run-p')

@@ -6,14 +6,14 @@ /**

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
const runAll = require("../../lib")
const parseCLIArgs = require("../common/parse-cli-args")
const runAll = require('../../lib')
const parseCLIArgs = require('../common/parse-cli-args')
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -29,48 +29,47 @@ /**

*/
module.exports = function npmRunAll(args, stdout, stderr) {
try {
const stdin = process.stdin
const argv = parseCLIArgs(args, { parallel: true }, { singleMode: true })
const group = argv.lastGroup
module.exports = function npmRunAll (args, stdout, stderr) {
try {
const stdin = process.stdin
const argv = parseCLIArgs(args, { parallel: true }, { singleMode: true })
const group = argv.lastGroup
if (group.patterns.length === 0) {
return Promise.resolve(null)
}
if (group.patterns.length === 0) {
return Promise.resolve(null)
}
const promise = runAll(
group.patterns,
{
stdout,
stderr,
stdin,
parallel: group.parallel,
maxParallel: argv.maxParallel,
continueOnError: argv.continueOnError,
printLabel: argv.printLabel,
printName: argv.printName,
config: argv.config,
packageConfig: argv.packageConfig,
silent: argv.silent,
arguments: argv.rest,
race: argv.race,
npmPath: argv.npmPath,
aggregateOutput: argv.aggregateOutput,
}
)
const promise = runAll(
group.patterns,
{
stdout,
stderr,
stdin,
parallel: group.parallel,
maxParallel: argv.maxParallel,
continueOnError: argv.continueOnError,
printLabel: argv.printLabel,
printName: argv.printName,
config: argv.config,
packageConfig: argv.packageConfig,
silent: argv.silent,
arguments: argv.rest,
race: argv.race,
npmPath: argv.npmPath,
aggregateOutput: argv.aggregateOutput
}
)
if (!argv.silent) {
promise.catch(err => {
//eslint-disable-next-line no-console
console.error("ERROR:", err.message)
})
}
return promise
if (!argv.silent) {
promise.catch(err => {
// eslint-disable-next-line no-console
console.error('ERROR:', err.message)
})
}
catch (err) {
//eslint-disable-next-line no-console
console.error("ERROR:", err.message)
return Promise.reject(err)
}
return promise
} catch (err) {
// eslint-disable-next-line no-console
console.error('ERROR:', err.message)
return Promise.reject(err)
}
}

@@ -6,7 +6,7 @@ /**

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -20,4 +20,4 @@ /**

*/
module.exports = function printHelp(output) {
output.write(`
module.exports = function printHelp (output) {
output.write(`
Usage:

@@ -61,3 +61,3 @@ $ run-s [--help | -h | --version | -v]

return Promise.resolve(null)
return Promise.resolve(null)
}

@@ -7,8 +7,8 @@ #!/usr/bin/env node

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Main
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
require("../common/bootstrap")("run-s")
require('../common/bootstrap')('run-s')

@@ -6,14 +6,14 @@ /**

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
const runAll = require("../../lib")
const parseCLIArgs = require("../common/parse-cli-args")
const runAll = require('../../lib')
const parseCLIArgs = require('../common/parse-cli-args')
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -29,45 +29,44 @@ /**

*/
module.exports = function npmRunAll(args, stdout, stderr) {
try {
const stdin = process.stdin
const argv = parseCLIArgs(args, { parallel: false }, { singleMode: true })
const group = argv.lastGroup
module.exports = function npmRunAll (args, stdout, stderr) {
try {
const stdin = process.stdin
const argv = parseCLIArgs(args, { parallel: false }, { singleMode: true })
const group = argv.lastGroup
if (group.patterns.length === 0) {
return Promise.resolve(null)
}
if (group.patterns.length === 0) {
return Promise.resolve(null)
}
const promise = runAll(
group.patterns,
{
stdout,
stderr,
stdin,
parallel: group.parallel,
continueOnError: argv.continueOnError,
printLabel: argv.printLabel,
printName: argv.printName,
config: argv.config,
packageConfig: argv.packageConfig,
silent: argv.silent,
arguments: argv.rest,
npmPath: argv.npmPath,
}
)
const promise = runAll(
group.patterns,
{
stdout,
stderr,
stdin,
parallel: group.parallel,
continueOnError: argv.continueOnError,
printLabel: argv.printLabel,
printName: argv.printName,
config: argv.config,
packageConfig: argv.packageConfig,
silent: argv.silent,
arguments: argv.rest,
npmPath: argv.npmPath
}
)
if (!argv.silent) {
promise.catch(err => {
//eslint-disable-next-line no-console
console.error("ERROR:", err.message)
})
}
return promise
if (!argv.silent) {
promise.catch(err => {
// eslint-disable-next-line no-console
console.error('ERROR:', err.message)
})
}
catch (err) {
//eslint-disable-next-line no-console
console.error("ERROR:", err.message)
return Promise.reject(err)
}
return promise
} catch (err) {
// eslint-disable-next-line no-console
console.error('ERROR:', err.message)
return Promise.reject(err)
}
}

@@ -7,13 +7,7 @@ /**

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const ansiStyles = require("ansi-styles")
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -30,17 +24,17 @@ /**

*/
module.exports = function createHeader(nameAndArgs, packageInfo, isTTY) {
if (!packageInfo) {
return `\n> ${nameAndArgs}\n\n`
}
module.exports = function createHeader (nameAndArgs, packageInfo, isTTY, ansiStyles) {
if (!packageInfo) {
return `\n> ${nameAndArgs}\n\n`
}
const index = nameAndArgs.indexOf(" ")
const name = (index === -1) ? nameAndArgs : nameAndArgs.slice(0, index)
const args = (index === -1) ? "" : nameAndArgs.slice(index + 1)
const packageName = packageInfo.body.name
const packageVersion = packageInfo.body.version
const scriptBody = packageInfo.body.scripts[name]
const packagePath = packageInfo.path
const color = isTTY ? ansiStyles.gray : { open: "", close: "" }
const index = nameAndArgs.indexOf(' ')
const name = (index === -1) ? nameAndArgs : nameAndArgs.slice(0, index)
const args = (index === -1) ? '' : nameAndArgs.slice(index + 1)
const packageName = packageInfo.body.name
const packageVersion = packageInfo.body.version
const scriptBody = packageInfo.body.scripts[name]
const packagePath = packageInfo.path
const color = isTTY ? ansiStyles.gray : { open: '', close: '' }
return `
return `
${color.open}> ${packageName}@${packageVersion} ${name} ${packagePath}${color.close}

@@ -47,0 +41,0 @@ ${color.open}> ${scriptBody} ${args}${color.close}

@@ -7,13 +7,13 @@ /**

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
const stream = require("stream")
const stream = require('stream')
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -32,3 +32,3 @@ const ALL_BR = /\n/g

class PrefixTransform extends stream.Transform {
/**
/**
* @param {string} prefix - A prefix text to be inserted.

@@ -39,10 +39,10 @@ * @param {object} state - A state object.

*/
constructor(prefix, state) {
super()
constructor (prefix, state) {
super()
this.prefix = prefix
this.state = state
}
this.prefix = prefix
this.state = state
}
/**
/**
* Transforms the output chunk.

@@ -55,23 +55,25 @@ *

*/
_transform(chunk, _encoding, callback) {
const prefix = this.prefix
const nPrefix = `\n${prefix}`
const state = this.state
const firstPrefix =
state.lastIsLinebreak ? prefix :
(state.lastPrefix !== prefix) ? "\n" :
/* otherwise */ ""
const prefixed = `${firstPrefix}${chunk}`.replace(ALL_BR, nPrefix)
const index = prefixed.indexOf(prefix, Math.max(0, prefixed.length - prefix.length))
_transform (chunk, _encoding, callback) {
const prefix = this.prefix
const nPrefix = `\n${prefix}`
const state = this.state
const firstPrefix =
state.lastIsLinebreak
? prefix
: (state.lastPrefix !== prefix)
? '\n'
: ''
const prefixed = `${firstPrefix}${chunk}`.replace(ALL_BR, nPrefix)
const index = prefixed.indexOf(prefix, Math.max(0, prefixed.length - prefix.length))
state.lastPrefix = prefix
state.lastIsLinebreak = (index !== -1)
state.lastPrefix = prefix
state.lastIsLinebreak = (index !== -1)
callback(null, (index !== -1) ? prefixed.slice(0, index) : prefixed)
}
callback(null, (index !== -1) ? prefixed.slice(0, index) : prefixed)
}
}
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Public API
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -91,4 +93,4 @@ /**

*/
module.exports = function createPrefixTransform(prefix, state) {
return new PrefixTransform(prefix, state)
module.exports = function createPrefixTransform (prefix, state) {
return new PrefixTransform(prefix, state)
}

@@ -7,16 +7,16 @@ /**

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
const shellQuote = require("shell-quote")
const matchTasks = require("./match-tasks")
const readPackageJson = require("./read-package-json")
const runTasks = require("./run-tasks")
const shellQuote = require('shell-quote')
const matchTasks = require('./match-tasks')
const readPackageJson = require('./read-package-json')
const runTasks = require('./run-tasks')
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -31,7 +31,7 @@ const ARGS_PATTERN = /\{(!)?([*@]|\d+)([^}]+)?}/g

*/
function toArray(x) {
if (x == null) {
return []
}
return Array.isArray(x) ? x : [x]
function toArray (x) {
if (x == null) {
return []
}
return Array.isArray(x) ? x : [x]
}

@@ -46,41 +46,41 @@

*/
function applyArguments(patterns, args) {
const defaults = Object.create(null)
function applyArguments (patterns, args) {
const defaults = Object.create(null)
return patterns.map(pattern => pattern.replace(ARGS_PATTERN, (whole, indirectionMark, id, options) => {
if (indirectionMark != null) {
throw Error(`Invalid Placeholder: ${whole}`)
}
if (id === "@") {
return shellQuote.quote(args)
}
if (id === "*") {
return shellQuote.quote([args.join(" ")])
}
return patterns.map(pattern => pattern.replace(ARGS_PATTERN, (whole, indirectionMark, id, options) => {
if (indirectionMark != null) {
throw Error(`Invalid Placeholder: ${whole}`)
}
if (id === '@') {
return shellQuote.quote(args)
}
if (id === '*') {
return shellQuote.quote([args.join(' ')])
}
const position = parseInt(id, 10)
if (position >= 1 && position <= args.length) {
return shellQuote.quote([args[position - 1]])
}
const position = parseInt(id, 10)
if (position >= 1 && position <= args.length) {
return shellQuote.quote([args[position - 1]])
}
// Address default values
if (options != null) {
const prefix = options.slice(0, 2)
// Address default values
if (options != null) {
const prefix = options.slice(0, 2)
if (prefix === ":=") {
defaults[id] = shellQuote.quote([options.slice(2)])
return defaults[id]
}
if (prefix === ":-") {
return shellQuote.quote([options.slice(2)])
}
if (prefix === ':=') {
defaults[id] = shellQuote.quote([options.slice(2)])
return defaults[id]
}
if (prefix === ':-') {
return shellQuote.quote([options.slice(2)])
}
throw Error(`Invalid Placeholder: ${whole}`)
}
if (defaults[id] != null) {
return defaults[id]
}
throw Error(`Invalid Placeholder: ${whole}`)
}
if (defaults[id] != null) {
return defaults[id]
}
return ""
}))
return ''
}))
}

@@ -97,7 +97,7 @@

*/
function parsePatterns(patternOrPatterns, args) {
const patterns = toArray(patternOrPatterns)
const hasPlaceholder = patterns.some(pattern => ARGS_PATTERN.test(pattern))
function parsePatterns (patternOrPatterns, args) {
const patterns = toArray(patternOrPatterns)
const hasPlaceholder = patterns.some(pattern => ARGS_PATTERN.test(pattern))
return hasPlaceholder ? applyArguments(patterns, args) : patterns
return hasPlaceholder ? applyArguments(patterns, args) : patterns
}

@@ -114,16 +114,16 @@

*/
function toOverwriteOptions(config) {
const options = []
function toOverwriteOptions (config) {
const options = []
for (const packageName of Object.keys(config)) {
const packageConfig = config[packageName]
for (const packageName of Object.keys(config)) {
const packageConfig = config[packageName]
for (const variableName of Object.keys(packageConfig)) {
const value = packageConfig[variableName]
for (const variableName of Object.keys(packageConfig)) {
const value = packageConfig[variableName]
options.push(`--${packageName}:${variableName}=${value}`)
}
options.push(`--${packageName}:${variableName}=${value}`)
}
}
return options
return options
}

@@ -138,4 +138,4 @@

*/
function toConfigOptions(config) {
return Object.keys(config).map(key => `--${key}=${config[key]}`)
function toConfigOptions (config) {
return Object.keys(config).map(key => `--${key}=${config[key]}`)
}

@@ -150,9 +150,9 @@

*/
function maxLength(length, name) {
return Math.max(name.length, length)
function maxLength (length, name) {
return Math.max(name.length, length)
}
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -218,78 +218,77 @@ /**

*/
module.exports = function npmRunAll(patternOrPatterns, options) { //eslint-disable-line complexity
const stdin = (options && options.stdin) || null
const stdout = (options && options.stdout) || null
const stderr = (options && options.stderr) || null
const taskList = (options && options.taskList) || null
const config = (options && options.config) || null
const packageConfig = (options && options.packageConfig) || null
const args = (options && options.arguments) || []
const parallel = Boolean(options && options.parallel)
const silent = Boolean(options && options.silent)
const continueOnError = Boolean(options && options.continueOnError)
const printLabel = Boolean(options && options.printLabel)
const printName = Boolean(options && options.printName)
const race = Boolean(options && options.race)
const maxParallel = parallel ? ((options && options.maxParallel) || 0) : 1
const aggregateOutput = Boolean(options && options.aggregateOutput)
const npmPath = options && options.npmPath
try {
const patterns = parsePatterns(patternOrPatterns, args)
if (patterns.length === 0) {
return Promise.resolve(null)
}
if (taskList != null && Array.isArray(taskList) === false) {
throw new Error("Invalid options.taskList")
}
if (typeof maxParallel !== "number" || !(maxParallel >= 0)) {
throw new Error("Invalid options.maxParallel")
}
if (!parallel && aggregateOutput) {
throw new Error("Invalid options.aggregateOutput; It requires options.parallel")
}
if (!parallel && race) {
throw new Error("Invalid options.race; It requires options.parallel")
}
module.exports = function npmRunAll (patternOrPatterns, options) { // eslint-disable-line complexity
const stdin = (options && options.stdin) || null
const stdout = (options && options.stdout) || null
const stderr = (options && options.stderr) || null
const taskList = (options && options.taskList) || null
const config = (options && options.config) || null
const packageConfig = (options && options.packageConfig) || null
const args = (options && options.arguments) || []
const parallel = Boolean(options && options.parallel)
const silent = Boolean(options && options.silent)
const continueOnError = Boolean(options && options.continueOnError)
const printLabel = Boolean(options && options.printLabel)
const printName = Boolean(options && options.printName)
const race = Boolean(options && options.race)
const maxParallel = parallel ? ((options && options.maxParallel) || 0) : 1
const aggregateOutput = Boolean(options && options.aggregateOutput)
const npmPath = options && options.npmPath
try {
const patterns = parsePatterns(patternOrPatterns, args)
if (patterns.length === 0) {
return Promise.resolve(null)
}
if (taskList != null && Array.isArray(taskList) === false) {
throw new Error('Invalid options.taskList')
}
if (typeof maxParallel !== 'number' || !(maxParallel >= 0)) {
throw new Error('Invalid options.maxParallel')
}
if (!parallel && aggregateOutput) {
throw new Error('Invalid options.aggregateOutput; It requires options.parallel')
}
if (!parallel && race) {
throw new Error('Invalid options.race; It requires options.parallel')
}
const prefixOptions = [].concat(
silent ? ["--silent"] : [],
packageConfig ? toOverwriteOptions(packageConfig) : [],
config ? toConfigOptions(config) : []
)
const prefixOptions = [].concat(
silent ? ['--silent'] : [],
packageConfig ? toOverwriteOptions(packageConfig) : [],
config ? toConfigOptions(config) : []
)
return Promise.resolve()
.then(() => {
if (taskList != null) {
return { taskList, packageInfo: null }
}
return readPackageJson()
})
.then(x => {
const tasks = matchTasks(x.taskList, patterns)
const labelWidth = tasks.reduce(maxLength, 0)
return Promise.resolve()
.then(() => {
if (taskList != null) {
return { taskList, packageInfo: null }
}
return readPackageJson()
})
.then(x => {
const tasks = matchTasks(x.taskList, patterns)
const labelWidth = tasks.reduce(maxLength, 0)
return runTasks(tasks, {
stdin,
stdout,
stderr,
prefixOptions,
continueOnError,
labelState: {
enabled: printLabel,
width: labelWidth,
lastPrefix: null,
lastIsLinebreak: true,
},
printName,
packageInfo: x.packageInfo,
race,
maxParallel,
npmPath,
aggregateOutput,
})
})
}
catch (err) {
return Promise.reject(new Error(err.message))
}
return runTasks(tasks, {
stdin,
stdout,
stderr,
prefixOptions,
continueOnError,
labelState: {
enabled: printLabel,
width: labelWidth,
lastPrefix: null,
lastIsLinebreak: true
},
printName,
packageInfo: x.packageInfo,
race,
maxParallel,
npmPath,
aggregateOutput
})
})
} catch (err) {
return Promise.reject(new Error(err.message))
}
}

@@ -7,16 +7,17 @@ /**

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
const Minimatch = require("minimatch").Minimatch
const { minimatch } = require('minimatch')
const Minimatch = minimatch.Minimatch
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
const COLON_OR_SLASH = /[:/]/g
const CONVERT_MAP = { ":": "/", "/": ":" }
const CONVERT_MAP = { ':': '/', '/': ':' }

@@ -29,4 +30,4 @@ /**

*/
function swapColonAndSlash(s) {
return s.replace(COLON_OR_SLASH, (matched) => CONVERT_MAP[matched])
function swapColonAndSlash (s) {
return s.replace(COLON_OR_SLASH, (matched) => CONVERT_MAP[matched])
}

@@ -43,11 +44,11 @@

*/
function createFilter(pattern) {
const trimmed = pattern.trim()
const spacePos = trimmed.indexOf(" ")
const task = spacePos < 0 ? trimmed : trimmed.slice(0, spacePos)
const args = spacePos < 0 ? "" : trimmed.slice(spacePos)
const matcher = new Minimatch(swapColonAndSlash(task), { nonegate: true })
const match = matcher.match.bind(matcher)
function createFilter (pattern) {
const trimmed = pattern.trim()
const spacePos = trimmed.indexOf(' ')
const task = spacePos < 0 ? trimmed : trimmed.slice(0, spacePos)
const args = spacePos < 0 ? '' : trimmed.slice(spacePos)
const matcher = new Minimatch(swapColonAndSlash(task), { nonegate: true })
const match = matcher.match.bind(matcher)
return { match, task, args }
return { match, task, args }
}

@@ -59,11 +60,11 @@

class TaskSet {
/**
/**
* Creates a instance.
*/
constructor() {
this.result = []
this.sourceMap = Object.create(null)
}
constructor () {
this.result = []
this.sourceMap = Object.create(null)
}
/**
/**
* Adds a command (a pattern) into this set if it's not overlapped.

@@ -76,14 +77,14 @@ * "Overlapped" is meaning that the command was added from a different source.

*/
add(command, source) {
const sourceList = this.sourceMap[command] || (this.sourceMap[command] = [])
if (sourceList.length === 0 || sourceList.indexOf(source) !== -1) {
this.result.push(command)
}
sourceList.push(source)
add (command, source) {
const sourceList = this.sourceMap[command] || (this.sourceMap[command] = [])
if (sourceList.length === 0 || sourceList.indexOf(source) !== -1) {
this.result.push(command)
}
sourceList.push(source)
}
}
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -98,37 +99,37 @@ /**

*/
module.exports = function matchTasks(taskList, patterns) {
const filters = patterns.map(createFilter)
const candidates = taskList.map(swapColonAndSlash)
const taskSet = new TaskSet()
const unknownSet = Object.create(null)
module.exports = function matchTasks (taskList, patterns) {
const filters = patterns.map(createFilter)
const candidates = taskList.map(swapColonAndSlash)
const taskSet = new TaskSet()
const unknownSet = Object.create(null)
// Take tasks while keep the order of patterns.
for (const filter of filters) {
let found = false
// Take tasks while keep the order of patterns.
for (const filter of filters) {
let found = false
for (const candidate of candidates) {
if (filter.match(candidate)) {
found = true
taskSet.add(
swapColonAndSlash(candidate) + filter.args,
filter.task
)
}
}
for (const candidate of candidates) {
if (filter.match(candidate)) {
found = true
taskSet.add(
swapColonAndSlash(candidate) + filter.args,
filter.task
)
}
}
// Built-in tasks should be allowed.
if (!found && (filter.task === "restart" || filter.task === "env")) {
taskSet.add(filter.task + filter.args, filter.task)
found = true
}
if (!found) {
unknownSet[filter.task] = true
}
// Built-in tasks should be allowed.
if (!found && (filter.task === 'restart' || filter.task === 'env')) {
taskSet.add(filter.task + filter.args, filter.task)
found = true
}
if (!found) {
unknownSet[filter.task] = true
}
}
const unknownTasks = Object.keys(unknownSet)
if (unknownTasks.length > 0) {
throw new Error(`Task not found: "${unknownTasks.join("\", ")}"`)
}
return taskSet.result
const unknownTasks = Object.keys(unknownSet)
if (unknownTasks.length > 0) {
throw new Error(`Task not found: "${unknownTasks.join('", ')}"`)
}
return taskSet.result
}

@@ -7,7 +7,7 @@ /**

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -18,3 +18,3 @@ /**

module.exports = class NpmRunAllError extends Error {
/**
/**
* Constructor.

@@ -27,12 +27,12 @@ *

*/
constructor(causeResult, allResults) {
super(`"${causeResult.task}" exited with ${causeResult.code}.`)
constructor (causeResult, allResults) {
super(`"${causeResult.task}" exited with ${causeResult.code}.`)
/**
/**
* The name of a npm-script which exited with a non-zero code.
* @type {string}
*/
this.name = causeResult.name
this.name = causeResult.name
/**
/**
* The code of a npm-script which exited with a non-zero code.

@@ -42,10 +42,10 @@ * This can be `undefined`.

*/
this.code = causeResult.code
this.code = causeResult.code
/**
/**
* All result items of npm-scripts.
* @type {Array.<{name: string, code: (number|undefined)}>}
*/
this.results = allResults
}
this.results = allResults
}
}

@@ -7,14 +7,13 @@ /**

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
const joinPath = require("path").join
const readPkg = require("read-pkg")
const joinPath = require('path').join
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -26,8 +25,8 @@ /**

*/
module.exports = function readPackageJson() {
const path = joinPath(process.cwd(), "package.json")
return readPkg(path).then(body => ({
taskList: Object.keys(body.scripts || {}),
packageInfo: { path, body },
}))
module.exports = function readPackageJson () {
const path = joinPath(process.cwd(), 'package.json')
return import('read-pkg').then(({ readPackage }) => readPackage(path)).then(body => ({
taskList: Object.keys(body.scripts || {}),
packageInfo: { path, body }
}))
}

@@ -7,20 +7,20 @@ /**

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
const path = require("path")
const ansiStyles = require("ansi-styles")
const parseArgs = require("shell-quote").parse
const createHeader = require("./create-header")
const createPrefixTransform = require("./create-prefix-transform-stream")
const spawn = require("./spawn")
const path = require('path')
const parseArgs = require('shell-quote').parse
const createHeader = require('./create-header')
const createPrefixTransform = require('./create-prefix-transform-stream')
const spawn = require('./spawn')
const ansiStylesPromise = import('ansi-styles')
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
const colors = ["cyan", "green", "magenta", "yellow", "red"]
const colors = ['cyan', 'green', 'magenta', 'yellow', 'red']

@@ -36,10 +36,10 @@ let colorIndex = 0

*/
function selectColor(taskName) {
let color = taskNamesToColors.get(taskName)
if (!color) {
color = colors[colorIndex]
colorIndex = (colorIndex + 1) % colors.length
taskNamesToColors.set(taskName, color)
}
return color
function selectColor (taskName) {
let color = taskNamesToColors.get(taskName)
if (!color) {
color = colors[colorIndex]
colorIndex = (colorIndex + 1) % colors.length
taskNamesToColors.set(taskName, color)
}
return color
}

@@ -55,15 +55,15 @@

*/
function wrapLabeling(taskName, source, labelState) {
if (source == null || !labelState.enabled) {
return source
}
function wrapLabeling (taskName, source, labelState, ansiStyles) {
if (source == null || !labelState.enabled) {
return source
}
const label = taskName.padEnd(labelState.width)
const color = source.isTTY ? ansiStyles[selectColor(taskName)] : { open: "", close: "" }
const prefix = `${color.open}[${label}]${color.close} `
const stream = createPrefixTransform(prefix, labelState)
const label = taskName.padEnd(labelState.width)
const color = source.isTTY ? ansiStyles[selectColor(taskName)] : { open: '', close: '' }
const prefix = `${color.open}[${label}]${color.close} `
const stream = createPrefixTransform(prefix, labelState)
stream.pipe(source)
stream.pipe(source)
return stream
return stream
}

@@ -78,9 +78,10 @@

*/
function detectStreamKind(stream, std) {
return (
stream == null ? "ignore" :
// `|| !std.isTTY` is needed for the workaround of https://github.com/nodejs/node/issues/5620
stream !== std || !std.isTTY ? "pipe" :
/* else */ stream
)
function detectStreamKind (stream, std) {
return (
stream == null
? 'ignore' // `|| !std.isTTY` is needed for the workaround of https://github.com/nodejs/node/issues/5620
: stream !== std || !std.isTTY
? 'pipe'
: stream
)
}

@@ -100,9 +101,9 @@

*/
function cleanTaskArg(arg) {
return arg.pattern || arg.op || arg
function cleanTaskArg (arg) {
return arg.pattern || arg.op || arg
}
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Interface
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -140,74 +141,76 @@ /**

*/
module.exports = function runTask(task, options) {
let cp = null
const promise = new Promise((resolve, reject) => {
const stdin = options.stdin
const stdout = wrapLabeling(task, options.stdout, options.labelState)
const stderr = wrapLabeling(task, options.stderr, options.labelState)
const stdinKind = detectStreamKind(stdin, process.stdin)
const stdoutKind = detectStreamKind(stdout, process.stdout)
const stderrKind = detectStreamKind(stderr, process.stderr)
const spawnOptions = { stdio: [stdinKind, stdoutKind, stderrKind] }
module.exports = function runTask (task, options) {
let cp = null
const promise = new Promise((resolve, reject) => {
ansiStylesPromise.then(({ default: ansiStyles }) => {
const stdin = options.stdin
const stdout = wrapLabeling(task, options.stdout, options.labelState, ansiStyles)
const stderr = wrapLabeling(task, options.stderr, options.labelState, ansiStyles)
const stdinKind = detectStreamKind(stdin, process.stdin)
const stdoutKind = detectStreamKind(stdout, process.stdout)
const stderrKind = detectStreamKind(stderr, process.stderr)
const spawnOptions = { stdio: [stdinKind, stdoutKind, stderrKind] }
// Print task name.
if (options.printName && stdout != null) {
stdout.write(createHeader(
task,
options.packageInfo,
options.stdout.isTTY
))
}
// Print task name.
if (options.printName && stdout != null) {
stdout.write(createHeader(
task,
options.packageInfo,
options.stdout.isTTY,
ansiStyles
))
}
// Execute.
const npmPath = options.npmPath || path.basename(process.env.npm_execpath).startsWith("npx") //eslint-disable-line no-process-env
? path.join(path.dirname(process.env.npm_execpath), path.basename(process.env.npm_execpath).replace("npx", "npm")) //eslint-disable-line no-process-env
: process.env.npm_execpath //eslint-disable-line no-process-env
const npmPathIsJs = typeof npmPath === "string" && /\.m?js/.test(path.extname(npmPath))
const execPath = (npmPathIsJs ? process.execPath : npmPath || "npm")
const isYarn = process.env.npm_config_user_agent && process.env.npm_config_user_agent.startsWith("yarn") //eslint-disable-line no-process-env
const spawnArgs = ["run"]
// Execute.
const npmPath = options.npmPath || path.basename(process.env.npm_execpath).startsWith('npx') // eslint-disable-line no-process-env
? path.join(path.dirname(process.env.npm_execpath), path.basename(process.env.npm_execpath).replace('npx', 'npm')) // eslint-disable-line no-process-env
: process.env.npm_execpath // eslint-disable-line no-process-env
const npmPathIsJs = typeof npmPath === 'string' && /\.m?js/.test(path.extname(npmPath))
const execPath = (npmPathIsJs ? process.execPath : npmPath || 'npm')
const isYarn = process.env.npm_config_user_agent && process.env.npm_config_user_agent.startsWith('yarn') // eslint-disable-line no-process-env
const spawnArgs = ['run']
if (npmPathIsJs) {
spawnArgs.unshift(npmPath)
}
if (!isYarn) {
Array.prototype.push.apply(spawnArgs, options.prefixOptions)
}
else if (options.prefixOptions.indexOf("--silent") !== -1) {
spawnArgs.push("--silent")
}
Array.prototype.push.apply(spawnArgs, parseArgs(task).map(cleanTaskArg))
if (npmPathIsJs) {
spawnArgs.unshift(npmPath)
}
if (!isYarn) {
Array.prototype.push.apply(spawnArgs, options.prefixOptions)
} else if (options.prefixOptions.indexOf('--silent') !== -1) {
spawnArgs.push('--silent')
}
Array.prototype.push.apply(spawnArgs, parseArgs(task).map(cleanTaskArg))
cp = spawn(execPath, spawnArgs, spawnOptions)
cp = spawn(execPath, spawnArgs, spawnOptions)
// Piping stdio.
if (stdinKind === "pipe") {
stdin.pipe(cp.stdin)
}
if (stdoutKind === "pipe") {
cp.stdout.pipe(stdout, { end: false })
}
if (stderrKind === "pipe") {
cp.stderr.pipe(stderr, { end: false })
}
// Piping stdio.
if (stdinKind === 'pipe') {
stdin.pipe(cp.stdin)
}
if (stdoutKind === 'pipe') {
cp.stdout.pipe(stdout, { end: false })
}
if (stderrKind === 'pipe') {
cp.stderr.pipe(stderr, { end: false })
}
// Register
cp.on("error", (err) => {
cp = null
reject(err)
})
cp.on("close", (code, signal) => {
cp = null
resolve({ task, code, signal })
})
// Register
cp.on('error', (err) => {
cp = null
reject(err)
})
cp.on('close', (code, signal) => {
cp = null
resolve({ task, code, signal })
})
})
})
promise.abort = function abort() {
if (cp != null) {
cp.kill()
cp = null
}
promise.abort = function abort () {
if (cp != null) {
cp.kill()
cp = null
}
}
return promise
return promise
}

@@ -7,15 +7,15 @@ /**

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
const MemoryStream = require("memorystream")
const NpmRunAllError = require("./npm-run-all-error")
const runTask = require("./run-task")
const MemoryStream = require('memorystream')
const NpmRunAllError = require('./npm-run-all-error')
const runTask = require('./run-task')
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -29,31 +29,31 @@ /**

*/
function remove(array, x) {
const index = array.indexOf(x)
if (index !== -1) {
array.splice(index, 1)
}
function remove (array, x) {
const index = array.indexOf(x)
if (index !== -1) {
array.splice(index, 1)
}
}
const signals = {
SIGABRT: 6,
SIGALRM: 14,
SIGBUS: 10,
SIGCHLD: 20,
SIGCONT: 19,
SIGFPE: 8,
SIGHUP: 1,
SIGILL: 4,
SIGINT: 2,
SIGKILL: 9,
SIGPIPE: 13,
SIGQUIT: 3,
SIGSEGV: 11,
SIGSTOP: 17,
SIGTERM: 15,
SIGTRAP: 5,
SIGTSTP: 18,
SIGTTIN: 21,
SIGTTOU: 22,
SIGUSR1: 30,
SIGUSR2: 31,
SIGABRT: 6,
SIGALRM: 14,
SIGBUS: 10,
SIGCHLD: 20,
SIGCONT: 19,
SIGFPE: 8,
SIGHUP: 1,
SIGILL: 4,
SIGINT: 2,
SIGKILL: 9,
SIGPIPE: 13,
SIGQUIT: 3,
SIGSEGV: 11,
SIGSTOP: 17,
SIGTERM: 15,
SIGTRAP: 5,
SIGTSTP: 18,
SIGTTIN: 21,
SIGTTOU: 22,
SIGUSR1: 30,
SIGUSR2: 31
}

@@ -66,9 +66,9 @@

*/
function convert(signal) {
return signals[signal] || 0
function convert (signal) {
return signals[signal] || 0
}
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -85,139 +85,137 @@ /**

*/
module.exports = function runTasks(tasks, options) {
return new Promise((resolve, reject) => {
if (tasks.length === 0) {
resolve([])
return
}
module.exports = function runTasks (tasks, options) {
return new Promise((resolve, reject) => {
if (tasks.length === 0) {
resolve([])
return
}
const results = tasks.map(task => ({ name: task, code: undefined }))
const queue = tasks.map((task, index) => ({ name: task, index }))
const promises = []
let error = null
let aborted = false
const results = tasks.map(task => ({ name: task, code: undefined }))
const queue = tasks.map((task, index) => ({ name: task, index }))
const promises = []
let error = null
let aborted = false
/**
/**
* Done.
* @returns {void}
*/
function done() {
if (error == null) {
resolve(results)
}
else {
reject(error)
}
}
function done () {
if (error == null) {
resolve(results)
} else {
reject(error)
}
}
/**
/**
* Aborts all tasks.
* @returns {void}
*/
function abort() {
if (aborted) {
return
}
aborted = true
function abort () {
if (aborted) {
return
}
aborted = true
if (promises.length === 0) {
done()
}
else {
for (const p of promises) {
p.abort()
}
Promise.all(promises).then(done, reject)
}
if (promises.length === 0) {
done()
} else {
for (const p of promises) {
p.abort()
}
Promise.all(promises).then(done, reject)
}
}
/**
/**
* Runs a next task.
* @returns {void}
*/
function next() {
if (aborted) {
return
}
if (queue.length === 0) {
if (promises.length === 0) {
done()
}
return
}
function next () {
if (aborted) {
return
}
if (queue.length === 0) {
if (promises.length === 0) {
done()
}
return
}
const originalOutputStream = options.stdout
const optionsClone = Object.assign({}, options)
const writer = new MemoryStream(null, {
readable: false,
})
const originalOutputStream = options.stdout
const optionsClone = Object.assign({}, options)
const writer = new MemoryStream(null, {
readable: false
})
if (options.aggregateOutput) {
optionsClone.stdout = writer
}
if (options.aggregateOutput) {
optionsClone.stdout = writer
}
const task = queue.shift()
const promise = runTask(task.name, optionsClone)
const task = queue.shift()
const promise = runTask(task.name, optionsClone)
promises.push(promise)
promise.then(
(result) => {
remove(promises, promise)
if (aborted) {
return
}
promises.push(promise)
promise.then(
(result) => {
remove(promises, promise)
if (aborted) {
return
}
if (options.aggregateOutput) {
originalOutputStream.write(writer.toString())
}
if (options.aggregateOutput) {
originalOutputStream.write(writer.toString())
}
// Check if the task failed as a result of a signal, and
// amend the exit code as a result.
if (result.code === null && result.signal !== null) {
// An exit caused by a signal must return a status code
// of 128 plus the value of the signal code.
// Ref: https://nodejs.org/api/process.html#process_exit_codes
result.code = 128 + convert(result.signal)
}
// Check if the task failed as a result of a signal, and
// amend the exit code as a result.
if (result.code === null && result.signal !== null) {
// An exit caused by a signal must return a status code
// of 128 plus the value of the signal code.
// Ref: https://nodejs.org/api/process.html#process_exit_codes
result.code = 128 + convert(result.signal)
}
// Save the result.
results[task.index].code = result.code
// Save the result.
results[task.index].code = result.code
// Aborts all tasks if it's an error.
if (result.code) {
error = new NpmRunAllError(result, results)
if (!options.continueOnError) {
abort()
return
}
}
// Aborts all tasks if it's an error.
if (result.code) {
error = new NpmRunAllError(result, results)
if (!options.continueOnError) {
abort()
return
}
}
// Aborts all tasks if options.race is true.
if (options.race && !result.code) {
abort()
return
}
// Aborts all tasks if options.race is true.
if (options.race && !result.code) {
abort()
return
}
// Call the next task.
next()
},
(thisError) => {
remove(promises, promise)
if (!options.continueOnError || options.race) {
error = thisError
abort()
return
}
next()
}
)
// Call the next task.
next()
},
(thisError) => {
remove(promises, promise)
if (!options.continueOnError || options.race) {
error = thisError
abort()
return
}
next()
}
)
}
const max = options.maxParallel
const end = (typeof max === "number" && max > 0)
? Math.min(tasks.length, max)
: tasks.length
for (let i = 0; i < end; ++i) {
next()
}
})
const max = options.maxParallel
const end = (typeof max === 'number' && max > 0)
? Math.min(tasks.length, max)
: tasks.length
for (let i = 0; i < end; ++i) {
next()
}
})
}

@@ -7,14 +7,14 @@ /**

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
const crossSpawn = require("cross-spawn")
const getDescendentProcessInfo = require("pidtree")
const crossSpawn = require('cross-spawn')
const getDescendentProcessInfo = require('pidtree')
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -26,22 +26,21 @@ /**

*/
function kill() {
getDescendentProcessInfo(this.pid, { root: true }, (err, pids) => {
if (err) {
return
}
function kill () {
getDescendentProcessInfo(this.pid, { root: true }, (err, pids) => {
if (err) {
return
}
for (const pid of pids) {
try {
process.kill(pid)
}
catch (_err) {
// ignore.
}
}
})
for (const pid of pids) {
try {
process.kill(pid)
} catch (_err) {
// ignore.
}
}
})
}
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -61,7 +60,7 @@ /**

*/
module.exports = function spawn(command, args, options) {
const child = crossSpawn(command, args, options)
child.kill = kill
module.exports = function spawn (command, args, options) {
const child = crossSpawn(command, args, options)
child.kill = kill
return child
return child
}

@@ -7,13 +7,13 @@ /**

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
const crossSpawn = require("cross-spawn")
const crossSpawn = require('cross-spawn')
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -25,9 +25,9 @@ /**

*/
function kill() {
crossSpawn("taskkill", ["/F", "/T", "/PID", this.pid])
function kill () {
crossSpawn('taskkill', ['/F', '/T', '/PID', this.pid])
}
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -47,7 +47,7 @@ /**

*/
module.exports = function spawn(command, args, options) {
const child = crossSpawn(command, args, options)
child.kill = kill
module.exports = function spawn (command, args, options) {
const child = crossSpawn(command, args, options)
child.kill = kill
return child
return child
}

@@ -7,7 +7,7 @@ /**

*/
"use strict"
'use strict'
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
// ------------------------------------------------------------------------------

@@ -20,3 +20,3 @@ /**

module.exports = require(
process.platform === "win32" ? "./spawn-win32" : "./spawn-posix"
process.platform === 'win32' ? './spawn-win32' : './spawn-posix'
)
{
"name": "npm-run-all2",
"version": "6.0.5",
"version": "6.0.6",
"description": "A CLI tool to run multiple npm-scripts in parallel or sequential. (Maintainence fork)",

@@ -22,5 +22,5 @@ "bin": {

"_mocha": "mocha --timeout 120000",
"clean": "rimraf coverage jsdoc \"test-workspace/{build,test.txt}\"",
"clean": "rm -rf coverage jsdoc \"test-workspace/{build,test.txt}\"",
"docs": "jsdoc -c jsdoc.json",
"lint": "eslint --ignore-path .gitignore --report-unused-disable-directives .",
"lint": "standard",
"pretest": "node scripts/make-slink.js && npm run lint",

@@ -34,8 +34,8 @@ "test": "c8 npm run _mocha",

"dependencies": {
"ansi-styles": "^5.0.0",
"ansi-styles": "^6.2.1",
"cross-spawn": "^7.0.3",
"memorystream": "^0.3.1",
"minimatch": "^8.0.2",
"minimatch": "^9.0.0",
"pidtree": "^0.6.0",
"read-pkg": "^5.2.0",
"read-pkg": "^8.0.0",
"shell-quote": "^1.7.3"

@@ -45,5 +45,3 @@ },

"auto-changelog": "^2.2.0",
"c8": "^7.9.0",
"eslint": "^4.19.1",
"eslint-config-mysticatea": "^13.0.2",
"c8": "^8.0.0",
"fs-extra": "^11.1.0",

@@ -53,5 +51,5 @@ "gh-release": "^7.0.0",

"mocha": "^10.0.0",
"p-queue": "^6.6.1",
"rimraf": "^4.0.4",
"yarn": "^1.12.3"
"p-queue": "^7.3.4",
"yarn": "^1.12.3",
"standard": "^17.1.0"
},

@@ -58,0 +56,0 @@ "repository": {

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc