This commit is contained in:
2024-11-03 17:16:20 +01:00
commit fd6412d6f2
8090 changed files with 778406 additions and 0 deletions

48
node_modules/npm-run-all/lib/create-header.js generated vendored Normal file
View File

@@ -0,0 +1,48 @@
/**
* @module create-header
* @author Toru Nagashima
* @copyright 2016 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const ansiStyles = require("ansi-styles")
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Creates the header text for a given task.
*
* @param {string} nameAndArgs - A task name and arguments.
* @param {object} packageInfo - A package.json's information.
* @param {object} packageInfo.body - A package.json's JSON object.
* @param {string} packageInfo.path - A package.json's file path.
* @param {boolean} isTTY - The flag to color the header.
* @returns {string} The header of a given task.
*/
module.exports = function createHeader(nameAndArgs, packageInfo, isTTY) {
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: "" }
return `
${color.open}> ${packageName}@${packageVersion} ${name} ${packagePath}${color.close}
${color.open}> ${scriptBody} ${args}${color.close}
`
}

View File

@@ -0,0 +1,89 @@
/**
* @module create-prefix-transform-stream
* @author Toru Nagashima
* @copyright 2016 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const stream = require("stream")
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const ALL_BR = /\n/g
/**
* The transform stream to insert a specific prefix.
*
* Several streams can exist for the same output stream.
* This stream will insert the prefix if the last output came from other instance.
* To do that, this stream is using a shared state object.
*
* @private
*/
class PrefixTransform extends stream.Transform {
/**
* @param {string} prefix - A prefix text to be inserted.
* @param {object} state - A state object.
* @param {string} state.lastPrefix - The last prefix which is printed.
* @param {boolean} state.lastIsLinebreak -The flag to check whether the last output is a line break or not.
*/
constructor(prefix, state) {
super()
this.prefix = prefix
this.state = state
}
/**
* Transforms the output chunk.
*
* @param {string|Buffer} chunk - A chunk to be transformed.
* @param {string} _encoding - The encoding of the chunk.
* @param {function} callback - A callback function that is called when done.
* @returns {void}
*/
_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))
state.lastPrefix = prefix
state.lastIsLinebreak = (index !== -1)
callback(null, (index !== -1) ? prefixed.slice(0, index) : prefixed)
}
}
//------------------------------------------------------------------------------
// Public API
//------------------------------------------------------------------------------
/**
* Create a transform stream to insert the specific prefix.
*
* Several streams can exist for the same output stream.
* This stream will insert the prefix if the last output came from other instance.
* To do that, this stream is using a shared state object.
*
* @param {string} prefix - A prefix text to be inserted.
* @param {object} state - A state object.
* @param {string} state.lastPrefix - The last prefix which is printed.
* @param {boolean} state.lastIsLinebreak -The flag to check whether the last output is a line break or not.
* @returns {stream.Transform} The created transform stream.
*/
module.exports = function createPrefixTransform(prefix, state) {
return new PrefixTransform(prefix, state)
}

287
node_modules/npm-run-all/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,287 @@
/**
* @module index
* @author Toru Nagashima
* @copyright 2015 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const shellQuote = require("shell-quote")
const matchTasks = require("./match-tasks")
const readPackageJson = require("./read-package-json")
const runTasks = require("./run-tasks")
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const ARGS_PATTERN = /\{(!)?([*@]|\d+)([^}]+)?}/g
/**
* Converts a given value to an array.
*
* @param {string|string[]|null|undefined} x - A value to convert.
* @returns {string[]} An array.
*/
function toArray(x) {
if (x == null) {
return []
}
return Array.isArray(x) ? x : [x]
}
/**
* Replaces argument placeholders (such as `{1}`) by arguments.
*
* @param {string[]} patterns - Patterns to replace.
* @param {string[]} args - Arguments to replace.
* @returns {string[]} replaced
*/
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(" ")])
}
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)
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]
}
return ""
}))
}
/**
* Parse patterns.
* In parsing process, it replaces argument placeholders (such as `{1}`) by arguments.
*
* @param {string|string[]} patternOrPatterns - Patterns to run.
* A pattern is a npm-script name or a Glob-like pattern.
* @param {string[]} args - Arguments to replace placeholders.
* @returns {string[]} Parsed patterns.
*/
function parsePatterns(patternOrPatterns, args) {
const patterns = toArray(patternOrPatterns)
const hasPlaceholder = patterns.some(pattern => ARGS_PATTERN.test(pattern))
return hasPlaceholder ? applyArguments(patterns, args) : patterns
}
/**
* Converts a given config object to an `--:=` style option array.
*
* @param {object|null} config -
* A map-like object to overwrite package configs.
* Keys are package names.
* Every value is a map-like object (Pairs of variable name and value).
* @returns {string[]} `--:=` style options.
*/
function toOverwriteOptions(config) {
const options = []
for (const packageName of Object.keys(config)) {
const packageConfig = config[packageName]
for (const variableName of Object.keys(packageConfig)) {
const value = packageConfig[variableName]
options.push(`--${packageName}:${variableName}=${value}`)
}
}
return options
}
/**
* Converts a given config object to an `--a=b` style option array.
*
* @param {object|null} config -
* A map-like object to set configs.
* @returns {string[]} `--a=b` style options.
*/
function toConfigOptions(config) {
return Object.keys(config).map(key => `--${key}=${config[key]}`)
}
/**
* Gets the maximum length.
*
* @param {number} length - The current maximum length.
* @param {string} name - A name.
* @returns {number} The maximum length.
*/
function maxLength(length, name) {
return Math.max(name.length, length)
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Runs npm-scripts which are matched with given patterns.
*
* @param {string|string[]} patternOrPatterns - Patterns to run.
* A pattern is a npm-script name or a Glob-like pattern.
* @param {object|undefined} [options] Optional.
* @param {boolean} options.parallel -
* If this is `true`, run scripts in parallel.
* Otherwise, run scripts in sequencial.
* Default is `false`.
* @param {stream.Readable|null} options.stdin -
* A readable stream to send messages to stdin of child process.
* If this is `null`, ignores it.
* If this is `process.stdin`, inherits it.
* Otherwise, makes a pipe.
* Default is `null`.
* @param {stream.Writable|null} options.stdout -
* A writable stream to receive messages from stdout of child process.
* If this is `null`, cannot send.
* If this is `process.stdout`, inherits it.
* Otherwise, makes a pipe.
* Default is `null`.
* @param {stream.Writable|null} options.stderr -
* A writable stream to receive messages from stderr of child process.
* If this is `null`, cannot send.
* If this is `process.stderr`, inherits it.
* Otherwise, makes a pipe.
* Default is `null`.
* @param {string[]} options.taskList -
* Actual name list of npm-scripts.
* This function search npm-script names in this list.
* If this is `null`, this function reads `package.json` of current directly.
* @param {object|null} options.packageConfig -
* A map-like object to overwrite package configs.
* Keys are package names.
* Every value is a map-like object (Pairs of variable name and value).
* e.g. `{"npm-run-all": {"test": 777}}`
* Default is `null`.
* @param {boolean} options.silent -
* The flag to set `silent` to the log level of npm.
* Default is `false`.
* @param {boolean} options.continueOnError -
* The flag to ignore errors.
* Default is `false`.
* @param {boolean} options.printLabel -
* The flag to print task names at the head of each line.
* Default is `false`.
* @param {boolean} options.printName -
* The flag to print task names before running each task.
* Default is `false`.
* @param {number} options.maxParallel -
* The maximum number of parallelism.
* Default is unlimited.
* @param {string} options.npmPath -
* The path to npm.
* Default is `process.env.npm_execpath`.
* @returns {Promise}
* A promise object which becomes fullfilled when all npm-scripts are completed.
*/
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) : []
)
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))
}
}

128
node_modules/npm-run-all/lib/match-tasks.js generated vendored Normal file
View File

@@ -0,0 +1,128 @@
/**
* @module match-tasks
* @author Toru Nagashima
* @copyright 2015 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const Minimatch = require("minimatch").Minimatch
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const COLON_OR_SLASH = /[:/]/g
const CONVERT_MAP = { ":": "/", "/": ":" }
/**
* Swaps ":" and "/", in order to use ":" as the separator in minimatch.
*
* @param {string} s - A text to swap.
* @returns {string} The text which was swapped.
*/
function swapColonAndSlash(s) {
return s.replace(COLON_OR_SLASH, (matched) => CONVERT_MAP[matched])
}
/**
* Creates a filter from user-specified pattern text.
*
* The task name is the part until the first space.
* The rest part is the arguments for this task.
*
* @param {string} pattern - A pattern to create filter.
* @returns {{match: function, task: string, args: string}} The filter object of the pattern.
*/
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 }
}
/**
* The set to remove overlapped task.
*/
class TaskSet {
/**
* Creates a instance.
*/
constructor() {
this.result = []
this.sourceMap = Object.create(null)
}
/**
* Adds a command (a pattern) into this set if it's not overlapped.
* "Overlapped" is meaning that the command was added from a different source.
*
* @param {string} command - A pattern text to add.
* @param {string} source - A task name to check.
* @returns {void}
*/
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
//------------------------------------------------------------------------------
/**
* Enumerates tasks which matches with given patterns.
*
* @param {string[]} taskList - A list of actual task names.
* @param {string[]} patterns - Pattern texts to match.
* @returns {string[]} Tasks which matches with the patterns.
* @private
*/
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
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
}
}
const unknownTasks = Object.keys(unknownSet)
if (unknownTasks.length > 0) {
throw new Error(`Task not found: "${unknownTasks.join("\", ")}"`)
}
return taskSet.result
}

47
node_modules/npm-run-all/lib/npm-run-all-error.js generated vendored Normal file
View File

@@ -0,0 +1,47 @@
/**
* @module npm-run-all-error
* @author Toru Nagashima
* @copyright 2016 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Error object with some additional info.
*/
module.exports = class NpmRunAllError extends Error {
/**
* Constructor.
*
* @param {{name: string, code: number}} causeResult -
* The result item of the npm-script which causes an error.
* @param {Array.<{name: string, code: (number|undefined)}>} allResults -
* All result items of npm-scripts.
*/
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
/**
* The code of a npm-script which exited with a non-zero code.
* This can be `undefined`.
* @type {number}
*/
this.code = causeResult.code
/**
* All result items of npm-scripts.
* @type {Array.<{name: string, code: (number|undefined)}>}
*/
this.results = allResults
}
}

31
node_modules/npm-run-all/lib/read-package-json.js generated vendored Normal file
View File

@@ -0,0 +1,31 @@
/**
* @module read-package-json
* @author Toru Nagashima
* @copyright 2016 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const joinPath = require("path").join
const readPkg = require("read-pkg")
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Reads the package.json in the current directory.
*
* @returns {object} package.json's information.
*/
module.exports = function readPackageJson() {
const path = joinPath(process.cwd(), "package.json")
return readPkg(path).then(body => ({
taskList: Object.keys(body.scripts || {}),
packageInfo: { path, body },
}))
}

206
node_modules/npm-run-all/lib/run-task.js generated vendored Normal file
View File

@@ -0,0 +1,206 @@
/**
* @module run-task
* @author Toru Nagashima
* @copyright 2015 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const path = require("path")
const chalk = require("chalk")
const parseArgs = require("shell-quote").parse
const padEnd = require("string.prototype.padend")
const createHeader = require("./create-header")
const createPrefixTransform = require("./create-prefix-transform-stream")
const spawn = require("./spawn")
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const colors = [chalk.cyan, chalk.green, chalk.magenta, chalk.yellow, chalk.red]
let colorIndex = 0
const taskNamesToColors = new Map()
/**
* Select a color from given task name.
*
* @param {string} taskName - The task name.
* @returns {function} A colorize function that provided by `chalk`
*/
function selectColor(taskName) {
let color = taskNamesToColors.get(taskName)
if (!color) {
color = colors[colorIndex]
colorIndex = (colorIndex + 1) % colors.length
taskNamesToColors.set(taskName, color)
}
return color
}
/**
* Wraps stdout/stderr with a transform stream to add the task name as prefix.
*
* @param {string} taskName - The task name.
* @param {stream.Writable} source - An output stream to be wrapped.
* @param {object} labelState - An label state for the transform stream.
* @returns {stream.Writable} `source` or the created wrapped stream.
*/
function wrapLabeling(taskName, source, labelState) {
if (source == null || !labelState.enabled) {
return source
}
const label = padEnd(taskName, labelState.width)
const color = source.isTTY ? selectColor(taskName) : (x) => x
const prefix = color(`[${label}] `)
const stream = createPrefixTransform(prefix, labelState)
stream.pipe(source)
return stream
}
/**
* Converts a given stream to an option for `child_process.spawn`.
*
* @param {stream.Readable|stream.Writable|null} stream - An original stream to convert.
* @param {process.stdin|process.stdout|process.stderr} std - A standard stream for this option.
* @returns {string|stream.Readable|stream.Writable} An option for `child_process.spawn`.
*/
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
)
}
/**
* Ensure the output of shell-quote's `parse()` is acceptable input to npm-cli.
*
* The `parse()` method of shell-quote sometimes returns special objects in its
* output array, e.g. if it thinks some elements should be globbed. But npm-cli
* only accepts strings and will throw an error otherwise.
*
* See https://github.com/substack/node-shell-quote#parsecmd-env
*
* @param {object|string} arg - Item in the output of shell-quote's `parse()`.
* @returns {string} A valid argument for npm-cli.
*/
function cleanTaskArg(arg) {
return arg.pattern || arg.op || arg
}
//------------------------------------------------------------------------------
// Interface
//------------------------------------------------------------------------------
/**
* Run a npm-script of a given name.
* The return value is a promise which has an extra method: `abort()`.
* The `abort()` kills the child process to run the npm-script.
*
* @param {string} task - A npm-script name to run.
* @param {object} options - An option object.
* @param {stream.Readable|null} options.stdin -
* A readable stream to send messages to stdin of child process.
* If this is `null`, ignores it.
* If this is `process.stdin`, inherits it.
* Otherwise, makes a pipe.
* @param {stream.Writable|null} options.stdout -
* A writable stream to receive messages from stdout of child process.
* If this is `null`, cannot send.
* If this is `process.stdout`, inherits it.
* Otherwise, makes a pipe.
* @param {stream.Writable|null} options.stderr -
* A writable stream to receive messages from stderr of child process.
* If this is `null`, cannot send.
* If this is `process.stderr`, inherits it.
* Otherwise, makes a pipe.
* @param {string[]} options.prefixOptions -
* An array of options which are inserted before the task name.
* @param {object} options.labelState - A state object for printing labels.
* @param {boolean} options.printName - The flag to print task names before running each task.
* @returns {Promise}
* A promise object which becomes fullfilled when the npm-script is completed.
* This promise object has an extra method: `abort()`.
* @private
*/
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] }
// Print task name.
if (options.printName && stdout != null) {
stdout.write(createHeader(
task,
options.packageInfo,
options.stdout.isTTY
))
}
// Execute.
const npmPath = options.npmPath || 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 = path.basename(npmPath || "npm").startsWith("yarn")
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))
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 })
}
// Register
cp.on("error", (err) => {
cp = null
reject(err)
})
cp.on("close", (code) => {
cp = null
resolve({ task, code })
})
})
promise.abort = function abort() {
if (cp != null) {
cp.kill()
cp = null
}
}
return promise
}

177
node_modules/npm-run-all/lib/run-tasks.js generated vendored Normal file
View File

@@ -0,0 +1,177 @@
/**
* @module run-tasks-in-parallel
* @author Toru Nagashima
* @copyright 2015 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const MemoryStream = require("memorystream")
const NpmRunAllError = require("./npm-run-all-error")
const runTask = require("./run-task")
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Remove the given value from the array.
* @template T
* @param {T[]} array - The array to remove.
* @param {T} x - The item to be removed.
* @returns {void}
*/
function remove(array, x) {
const index = array.indexOf(x)
if (index !== -1) {
array.splice(index, 1)
}
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Run npm-scripts of given names in parallel.
*
* If a npm-script exited with a non-zero code, this aborts other all npm-scripts.
*
* @param {string} tasks - A list of npm-script name to run in parallel.
* @param {object} options - An option object.
* @returns {Promise} A promise object which becomes fullfilled when all npm-scripts are completed.
* @private
*/
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
/**
* Done.
* @returns {void}
*/
function done() {
if (error == null) {
resolve(results)
}
else {
reject(error)
}
}
/**
* Aborts all tasks.
* @returns {void}
*/
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)
}
}
/**
* Runs a next task.
* @returns {void}
*/
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,
})
if (options.aggregateOutput) {
optionsClone.stdout = writer
}
const task = queue.shift()
const promise = runTask(task.name, optionsClone)
promises.push(promise)
promise.then(
(result) => {
remove(promises, promise)
if (aborted) {
return
}
if (options.aggregateOutput) {
originalOutputStream.write(writer.toString())
}
// 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 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()
}
)
}
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()
}
})
}

64
node_modules/npm-run-all/lib/spawn-posix.js generated vendored Normal file
View File

@@ -0,0 +1,64 @@
/**
* @module spawn-posix
* @author Toru Nagashima
* @copyright 2015 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const crossSpawn = require("cross-spawn")
const getDescendentProcessInfo = require("pidtree")
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Kills the new process and its sub processes.
* @this ChildProcess
* @returns {void}
*/
function kill() {
getDescendentProcessInfo(this.pid, { root: true }, (err, pids) => {
if (err) {
return
}
for (const pid of pids) {
try {
process.kill(pid)
}
catch (_err) {
// ignore.
}
}
})
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Launches a new process with the given command.
* This is almost same as `child_process.spawn`.
*
* This returns a `ChildProcess` instance.
* `kill` method of the instance kills the new process and its sub processes.
*
* @param {string} command - The command to run.
* @param {string[]} args - List of string arguments.
* @param {object} options - Options.
* @returns {ChildProcess} A ChildProcess instance of new process.
* @private
*/
module.exports = function spawn(command, args, options) {
const child = crossSpawn(command, args, options)
child.kill = kill
return child
}

50
node_modules/npm-run-all/lib/spawn-win32.js generated vendored Normal file
View File

@@ -0,0 +1,50 @@
/**
* @module spawn-win32
* @author Toru Nagashima
* @copyright 2015 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const crossSpawn = require("cross-spawn")
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Kills the new process and its sub processes forcibly.
* @this ChildProcess
* @returns {void}
*/
function kill() {
crossSpawn("taskkill", ["/F", "/T", "/PID", this.pid])
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Launches a new process with the given command.
* This is almost same as `child_process.spawn`.
*
* This returns a `ChildProcess` instance.
* `kill` method of the instance kills the new process and its sub processes forcibly.
*
* @param {string} command - The command to run.
* @param {string[]} args - List of string arguments.
* @param {object} options - Options.
* @returns {ChildProcess} A ChildProcess instance of new process.
* @private
*/
module.exports = function spawn(command, args, options) {
const child = crossSpawn(command, args, options)
child.kill = kill
return child
}

20
node_modules/npm-run-all/lib/spawn.js generated vendored Normal file
View File

@@ -0,0 +1,20 @@
/**
* @module spawn
* @author Toru Nagashima
* @copyright 2015 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Launches a new process with the given command.
* This is {@link ./spawn-posix.js:spawn} or {@link ./spawn-win32.js:spawn}
* @private
*/
module.exports = require(
process.platform === "win32" ? "./spawn-win32" : "./spawn-posix"
)