Initial import with skill sheet working

This commit is contained in:
2024-12-04 00:11:23 +01:00
commit 9050c80ab4
4488 changed files with 671048 additions and 0 deletions

21
node_modules/gulp-cli/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015, 2017-2020, 2022-2023 Blaine Bublitz <blaine.bublitz@gmail.com> and Eric Schoffstall <yo@contra.io>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

243
node_modules/gulp-cli/README.md generated vendored Normal file
View File

@@ -0,0 +1,243 @@
<p align="center">
<a href="https://gulpjs.com">
<img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png">
</a>
</p>
# gulp-cli
[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][ci-image]][ci-url] [![Coveralls Status][coveralls-image]][coveralls-url]
Command Line Utility for Gulp
## Install
```bash
npm install --global gulp-cli
```
## Usage
```bash
> gulp [flags] <task> <task>...
```
## Custom Metadata
When listing tasks with the `gulp -T` command, gulp-cli displays some custom metadata as defined upon task functions. Currently supported properties:
* `task.description` - String of the description to display.
```js
function clean() { ... }
clean.description = 'Cleans up generated files.';
```
* `task.flags` - Object with key/value pairs being flag/description to display.
```js
function build() { ... }
build.flags = {
'--prod': 'Builds in production mode.'
};
```
Example Usage:
```js
function build() { ... }
build.description = 'Build entire project.';
build.flags = {
'--prod': 'Builds in production mode (minification, etc).'
};
// gulp 3.x
gulp.task('build', build);
// gulp 4.x
gulp.task(build);
```
## Tasks
The task(s) listed on the command line will be executed.
If more than one task is listed, Gulp will execute all of them
concurrently, that is, as if they had all been listed as dependencies of
a single task.
By default, Gulp does not serialize tasks listed on the command line. If you would like to execute tasks serially, you must specify the `--series` flag. e.g. `gulp clean build --series`
Just running `gulp` will execute the task `default`. If there is no
`default` task, gulp will error.
## Completion
> Thanks to the grunt team, specifically Tyler Kellen
To enable tasks auto-completion in shell you should add `eval "$(gulp --completion=shell)"` in your `.shellrc` file.
###### Bash:
Add `eval "$(gulp --completion=bash)"` to `~/.bashrc`.
###### Zsh:
Add `eval "$(gulp --completion=zsh)"` to `~/.zshrc`.
###### Powershell:
Add `Invoke-Expression ((gulp --completion=powershell) -join [System.Environment]::NewLine)` to `$PROFILE`.
###### Fish:
Add `gulp --completion=fish | source` to `~/.config/fish/config.fish`.
## Compilers
You can find a list of supported JavaScript variant languages in [Interpret][interpret-js-variants]. If you would like to add support for a new language, send pull requests/open issues on that project.
## Environment
The CLI adds `process.env.INIT_CWD` which is the original cwd it was launched from.
## Configuration
Configuration is supported through the use of a `.gulp.*` file (e.g. `.gulp.js`, `.gulp.ts`). You can find a list of supported JavaScript variant languages in [Interpret][interpret-js-variants].
A configuration file from the current working directory (`cwd`) or above are selected before a configuration file from the home directory (`~`).
Supported configurations properties:
| Property | Description |
|--------------------|-------------|
| description | Top-level description of the project/gulpfile (Replaces "Tasks for ~/path/of/gulpfile.js") |
| gulpfile | Set a default gulpfile |
| preload | An array of modules to preload before running the gulpfile. Any relative paths will be resolved against the `--cwd` directory (if you don't want that behavior, use absolute paths) |
| nodeFlags | An array of flags used to forcibly respawn the process upon startup. For example, if you always want your gulpfiles to run in node's harmony mode, you can set `--harmony` here |
| flags.continue | Continue execution of tasks upon failure by default. |
| flags.compactTasks | Reduce the output of task dependency tree by default. |
| flags.tasksDepth | Set default depth of task dependency tree. |
| flags.silent | Silence logging by default |
| flags.series | Run tasks given on the CLI in series (the default is parallel) |
| message(data) | A function used to translate messages that pass through gulp-cli. Can receive an object like `{ tag: Symbol(), ...props }` where the `tag` is a symbol from `@gulpjs/messages`. The string returned from this function will be logged. If `false` is explicitly returned, no message will be logged. |
| timestamp(data) | A function used to provide timestamps for gulp-cli. Can receive an object like `{ tag: Symbol(), ...props }` where the `tag` is a symbol from `@gulpjs/messages`. The string returned from this function will be output before any messages. If `false` is explicitly returned, no timestamp will be output. |
## Flags
gulp has very few flags to know about. All other flags are for tasks to use if needed.
__Some flags only work with gulp 4 and will be ignored when invoked against gulp 3.__
<table>
<thead>
<tr>
<th width="25%">Flag</th>
<th width="15%">Short Flag</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>--help</td>
<td>-h</td>
<td>Show this help.</td>
</tr>
<tr>
<td>--version</td>
<td>-v</td>
<td>Print the global and local gulp versions.</td>
</tr>
<tr>
<td>--preload [path]</td>
<td></td>
<td>Will preload a module before running the gulpfile. This is useful for transpilers but also has other applications.</td>
</tr>
<tr>
<td>--gulpfile [path]</td>
<td>-f</td>
<td>Manually set path of gulpfile. Useful if you have multiple gulpfiles. This will set the CWD to the gulpfile directory as well.</td>
</tr>
<tr>
<td>--cwd [path]</td>
<td></td>
<td>Manually set the CWD. The search for the gulpfile, as well as the relativity of all preloads (with the `--preload` flag) will be from here.</td>
</tr>
<tr>
<td>--tasks</td>
<td>-T</td>
<td>Print the task dependency tree for the loaded gulpfile.</td>
</tr>
<tr>
<td>--tasks-simple</td>
<td></td>
<td>Print a plaintext list of tasks for the loaded gulpfile.</td>
</tr>
<tr>
<td>--tasks-json [path]</td>
<td></td>
<td>Print the task dependency tree, in JSON format, for the loaded gulpfile. The [path] argument is optional, and if given writes the JSON to the path.</td>
</tr>
<tr>
<td>--tasks-depth [number]</td>
<td></td>
<td>Specify the depth of the task dependency tree to print. This flag can be used with --tasks or --tasks-json. (This flag was named --depth before but is deprecated.)</td>
</tr>
<tr>
<td>--compact-tasks</td>
<td></td>
<td>Reduce the output of task dependency tree by printing only top tasks and their child tasks. This flag can be used with --tasks or --tasks-json.</td>
</tr>
<tr>
<td>--sort-tasks</td>
<td></td>
<td>Will sort top tasks of task dependency tree. This flag can be used with --tasks.</td>
</tr>
<tr>
<td>--color</td>
<td></td>
<td>Will force gulp and gulp plugins to display colors, even when no color support is detected.</td>
</tr>
<tr>
<td>--no-color</td>
<td></td>
<td>Will force gulp and gulp plugins to not display colors, even when color support is detected.</td>
</tr>
<tr>
<td>--silent</td>
<td>-S</td>
<td>Suppress all gulp logging.</td>
</tr>
<tr>
<td>--continue</td>
<td></td>
<td>Continue execution of tasks upon failure.</td>
</tr>
<tr>
<td>--series</td>
<td></td>
<td>Run tasks given on the CLI in series (the default is parallel).</td>
</tr>
<tr>
<td>--log-level</td>
<td>-L</td>
<td>Set the loglevel. -L for least verbose and -LLLL for most verbose. -LLL is default.</td>
</tr>
</tbody>
</table>
## License
MIT
<!-- prettier-ignore-start -->
[interpret-js-variants]: https://github.com/gulpjs/interpret#jsvariants
<!-- prettier-ignore-end -->
<!-- prettier-ignore-start -->
[downloads-image]: https://img.shields.io/npm/dm/gulp-cli.svg?style=flat-square
[npm-url]: https://www.npmjs.com/package/gulp-cli
[npm-image]: https://img.shields.io/npm/v/gulp-cli.svg?style=flat-square
[ci-url]: https://github.com/gulpjs/gulp-cli/actions?query=workflow:dev
[ci-image]: https://img.shields.io/github/actions/workflow/status/gulpjs/gulp-cli/dev.yml?branch=master&style=flat-square
[coveralls-url]: https://coveralls.io/r/gulpjs/gulp-cli
[coveralls-image]: https://img.shields.io/coveralls/gulpjs/gulp-cli.svg?style=flat-square
<!-- prettier-ignore-end -->

5
node_modules/gulp-cli/bin/gulp.js generated vendored Executable file
View File

@@ -0,0 +1,5 @@
#!/usr/bin/env node
'use strict';
require('../')();

20
node_modules/gulp-cli/completion/README.md generated vendored Normal file
View File

@@ -0,0 +1,20 @@
# Completion for gulp
> Thanks to the grunt team, specifically Tyler Kellen
To enable tasks auto-completion in shell you should add `eval "$(gulp --completion=shell)"` in your `.shellrc` file.
## Bash
Add `eval "$(gulp --completion=bash)"` to `~/.bashrc`.
## Zsh
Add `eval "$(gulp --completion=zsh)"` to `~/.zshrc`.
## Powershell
Add `Invoke-Expression ((gulp --completion=powershell) -join [System.Environment]::NewLine)` to `$PROFILE`.
## Fish
Add `gulp --completion=fish | source` to `~/.config/fish/config.fish`.

27
node_modules/gulp-cli/completion/bash generated vendored Normal file
View File

@@ -0,0 +1,27 @@
#!/bin/bash
# Borrowed from grunt-cli
# http://gruntjs.com/
#
# Copyright (c) 2012 Tyler Kellen, contributors
# Licensed under the MIT license.
# https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
# Usage:
#
# To enable bash <tab> completion for gulp, add the following line (minus the
# leading #, which is the bash comment character) to your ~/.bashrc file:
#
# eval "$(gulp --completion=bash)"
# Enable bash autocompletion.
function _gulp_completions() {
# The currently-being-completed word.
local cur="${COMP_WORDS[COMP_CWORD]}"
#Grab tasks
local compls=$(gulp --tasks-simple)
# Tell complete what stuff to show.
COMPREPLY=($(compgen -W "$compls" -- "$cur"))
}
complete -o default -F _gulp_completions gulp

10
node_modules/gulp-cli/completion/fish generated vendored Normal file
View File

@@ -0,0 +1,10 @@
#!/usr/bin/env fish
# Usage:
#
# To enable fish <tab> completion for gulp, add the following line to
# your ~/.config/fish/config.fish file:
#
# gulp --completion=fish | source
complete -c gulp -a "(gulp --tasks-simple)" -f

61
node_modules/gulp-cli/completion/powershell generated vendored Normal file
View File

@@ -0,0 +1,61 @@
# Copyright (c) 2014 Jason Jarrett
#
# Tab completion for the `gulp`
#
# Usage:
#
# To enable powershell <tab> completion for gulp you need to be running
# at least PowerShell v3 or greater and add the below to your $PROFILE
#
# Invoke-Expression ((gulp --completion=powershell) -join [System.Environment]::NewLine)
#
#
$gulp_completion_Process = {
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
# Load up an assembly to read the gulpfile's sha1
if(-not $global:GulpSHA1Managed) {
[Reflection.Assembly]::LoadWithPartialName("System.Security") | out-null
$global:GulpSHA1Managed = new-Object System.Security.Cryptography.SHA1Managed
}
# setup a global (in-memory) cache
if(-not $global:GulpfileShaCache) {
$global:GulpfileShaCache = @{};
}
$cache = $global:GulpfileShaCache;
# Get the gulpfile's sha1
$sha1gulpFile = (resolve-path gulpfile.js -ErrorAction Ignore | %{
$file = [System.IO.File]::Open($_.Path, "open", "read")
[string]::join('', ($global:GulpSHA1Managed.ComputeHash($file) | %{ $_.ToString("x2") }))
$file.Dispose()
})
# lookup the sha1 for previously cached task lists.
if($cache.ContainsKey($sha1gulpFile)){
$tasks = $cache[$sha1gulpFile];
} else {
$tasks = (gulp --tasks-simple).split("`n");
$cache[$sha1gulpFile] = $tasks;
}
$tasks |
where { $_.startswith($commandName) }
Sort-Object |
foreach { New-Object System.Management.Automation.CompletionResult $_, $_, 'ParameterValue', ('{0}' -f $_) }
}
if (-not $global:options) {
$global:options = @{
CustomArgumentCompleters = @{};
NativeArgumentCompleters = @{}
}
}
$global:options['NativeArgumentCompleters']['gulp'] = $gulp_completion_Process
$function:tabexpansion2 = $function:tabexpansion2 -replace 'End\r\n{','End { if ($null -ne $options) { $options += $global:options} else {$options = $global:options}'

25
node_modules/gulp-cli/completion/zsh generated vendored Normal file
View File

@@ -0,0 +1,25 @@
#!/bin/zsh
# Borrowed from grunt-cli
# http://gruntjs.com/
#
# Copyright (c) 2012 Tyler Kellen, contributors
# Licensed under the MIT license.
# https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
# Usage:
#
# To enable zsh <tab> completion for gulp, add the following line (minus the
# leading #, which is the zsh comment character) to your ~/.zshrc file:
#
# eval "$(gulp --completion=zsh)"
# Enable zsh autocompletion.
function _gulp_completion() {
# Grab tasks
compls=$(gulp --tasks-simple)
completions=(${=compls})
compadd -- $completions
}
compdef _gulp_completion gulp

80
node_modules/gulp-cli/gulp.1 generated vendored Normal file
View File

@@ -0,0 +1,80 @@
.TH "GULP" "" "March 2024" "" ""
.SH "NAME"
\fBgulp\fR
.SS Usage
.P
\fBgulp [flags] <task> <task>\.\.\.\fP
.SS Tasks
.P
The task(s) listed will be executed\.
If more than one task is listed, Gulp will execute all of them
concurrently, that is, as if they had all been listed as dependencies of
a single task\.
.P
By default, Gulp does not serialize tasks listed on the command line\. If you would like to execute tasks serially, you must specify the \fB\-\-series\fP flag\. e\.g\. \fBgulp clean build \-\-series\fP
.P
Just running \fBgulp\fP will execute the task \fBdefault\fP\|\. If there is no
\fBdefault\fP task, gulp will error\.
.SS Compilers
.P
You can find a list of supported languages at https://github\.com/gulpjs/interpret \fIhttps://github\.com/gulpjs/interpret\fR\|\. If you would like to add support for a new language, send pull requests/open issues on that project\.
.SS Environment
.P
The CLI adds process\.env\.INIT_CWD which is the original cwd it was launched from\.
.SS Flags
.P
gulp has very few flags to know about\. All other flags are for tasks to use if needed\.
.P
\fBSome flags only work with gulp 4 and will be ignored when invoked against gulp 3\.\fR
.P
\fB\-\-help\fR, \fB\-h\fR
Show the help\.
.P
\fB\-\-version\fR, \fB\-v\fR
Print the global and local gulp versions\.
.P
\fB\-\-require\fR [path]
Will require a module before running the gulpfile\. This is useful for transpilers but also has other applications\.
.P
\fB\-\-gulpfile\fR [path], \fB\-f\fR [path]
Manually set path of gulpfile\. Useful if you have multiple gulpfiles\. This will set the CWD to the gulpfile directory as well\.
.P
\fB\-\-cwd\fR [path]
Manually set the CWD\. The search for the gulpfile, as well as the relativity of all requires will be from here\.
.P
\fB\-\-tasks\fR, \fB\-T\fR
Print the task dependency tree for the loaded gulpfile\.
.P
\fB\-\-tasks\-simple\fR
Print a plaintext list of tasks for the loaded gulpfile\.
.P
\fB\-\-tasks\-json\fR [path]
Print the task dependency tree, in JSON format, for the loaded gulpfile\. The [path] argument is optional, and if given writes the JSON to the path\.
.P
\fB\-\-tasks\-depth\fR [number]
Specify the depth of the task dependency tree to print\. This flag can be used with \-\-tasks or \-\-tasks\-json\. (This flag was named \-\-depth before but is deprecated\.)
.P
\fB\-\-compact\-tasks\fR
Reduce the output of task dependency tree by printing only top tasks and their child tasks\. This flag can be used with \-\-tasks or \-\-tasks\-json\.
.P
\fB\-\-sort\-tasks\fR
Will sort top tasks of task dependency tree\. This flag can be used with \-\-tasks\.
.P
\fB\-\-color\fR
Will force gulp and gulp plugins to display colors, even when no color support is detected\.
.P
\fB\-\-no\-color\fR
Will force gulp and gulp plugins to not display colors, even when color support is detected\.
.P
\fB\-\-silent\fR, \fB\-S\fR
Suppress all gulp logging\.
.P
\fB\-\-continue\fR
Continue execution of tasks upon failure\.
.P
\fB\-\-series\fR
Run tasks given on the CLI in series (the default is parallel)\.
.P
\fB\-\-log\-level\fR, \fB\-L\fR
Set the loglevel\. \-L for least verbose and \-LLLL for most verbose\. \-LLL is default\.

231
node_modules/gulp-cli/index.js generated vendored Normal file
View File

@@ -0,0 +1,231 @@
'use strict';
var fs = require('fs');
var path = require('path');
var log = require('gulplog');
var yargs = require('yargs');
var Liftoff = require('liftoff');
var interpret = require('interpret');
var v8flags = require('v8flags');
var messages = require('@gulpjs/messages');
var findRange = require('semver-greatest-satisfied-range');
var exit = require('./lib/shared/exit');
var arrayFind = require('./lib/shared/array-find');
var makeTitle = require('./lib/shared/make-title');
var makeHelp = require('./lib/shared/options/make-help');
var cliOptions = require('./lib/shared/options/cli-options');
var completion = require('./lib/shared/completion');
var cliVersion = require('./package.json').version;
var toConsole = require('./lib/shared/log/to-console');
var mergeCliOpts = require('./lib/shared/config/cli-flags');
var buildTranslations = require('./lib/shared/translate');
// Get supported ranges
var ranges = fs.readdirSync(path.join(__dirname, '/lib/versioned/'));
// Set env var for ORIGINAL cwd
// before anything touches it
process.env.INIT_CWD = process.cwd();
var cli = new Liftoff({
name: 'gulp',
processTitle: makeTitle('gulp', process.argv.slice(2)),
extensions: interpret.jsVariants,
v8flags: v8flags,
configFiles: [
{
name: '.gulp',
path: '.',
extensions: interpret.jsVariants,
findUp: true,
},
{
name: '.gulp',
path: '~',
extensions: interpret.jsVariants,
},
],
});
var parser = yargs
.help(false)
.version(false)
.detectLocale(false)
.showHelpOnFail(false)
.exitProcess(false)
.fail(onFail)
.options(cliOptions);
var opts = parser.parse();
// Set up event listeners for logging temporarily.
// TODO: Rework console logging before we can set up proper config
// Possibly by batching messages in gulplog until listeners are attached
var cleanupListeners = toConsole(log, opts, buildTranslations());
cli.on('preload:before', function(name) {
log.info({ tag: messages.PRELOAD_BEFORE, name: name });
});
cli.on('preload:success', function(name) {
log.info({ tag: messages.PRELOAD_SUCCESS, name: name });
});
cli.on('preload:failure', function(name, error) {
log.warn({ tag: messages.PRELOAD_FAILURE, name: name });
if (error) {
log.warn({ tag: messages.PRELOAD_ERROR, error: error });
}
});
cli.on('loader:success', function(name) {
// This is needed because interpret needs to stub the .mjs extension
// Without the .mjs require hook, rechoir blows up
// However, we don't want to show the mjs-stub loader in the logs
/* istanbul ignore else */
if (path.basename(name, '.js') !== 'mjs-stub') {
log.info({ tag: messages.LOADER_SUCCESS, name: name });
}
});
cli.on('loader:failure', function(name, error) {
log.warn({ tag: messages.LOADER_FAILURE, name: name });
if (error) {
log.warn({ tag: messages.LOADER_ERROR, error: error });
}
});
cli.on('respawn', function(flags, child) {
log.info({ tag: messages.NODE_FLAGS, flags: flags });
log.info({ tag: messages.RESPAWNED, pid: child.pid });
});
function run() {
cli.prepare({
cwd: opts.cwd,
configPath: opts.gulpfile,
preload: opts.preload,
}, onPrepare);
}
module.exports = run;
function isDefined(cfg) {
return cfg != null;
}
function onFail(message, error) {
// Run Liftoff#prepare to get the env. Primarily to load themes.
cli.prepare({}, function (env) {
// We only use the first config found, which is a departure from
// the previous implementation that merged with the home
var cfg = arrayFind(env.config, isDefined);
var translate = buildTranslations(cfg);
var errorMsg = translate.message({ tag: messages.ARGV_ERROR, message: message, error: error });
if (errorMsg) {
console.error(errorMsg);
}
makeHelp(parser, translate).showHelp(console.error);
exit(1);
});
}
function onPrepare(env) {
// We only use the first config found, which is a departure from
// the previous implementation that merged with the home
var cfg = arrayFind(env.config, isDefined);
var flags = mergeCliOpts(opts, cfg);
// Remove the previous listeners since we have appropriate config now
cleanupListeners();
var translate = buildTranslations(cfg);
// Set up event listeners for logging again after configuring.
toConsole(log, flags, translate);
cli.execute(env, cfg.nodeFlags, function (env) {
onExecute(env, flags, translate);
});
}
// The actual logic
function onExecute(env, flags, translate) {
// Moved the completion logic outside of Liftoff since we need to include translations
if (flags.completion) {
return completion(flags.completion, translate);
}
// This translates the --continue flag in gulp
// To the settle env variable for undertaker
// We use the process.env so the user's gulpfile
// Can know about the flag
if (flags.continue) {
process.env.UNDERTAKER_SETTLE = 'true';
}
if (flags.help) {
makeHelp(parser, translate).showHelp(console.log);
exit(0);
}
// Anything that needs to print outside of the logging mechanism should use console.log
if (flags.version) {
console.log('CLI version:', cliVersion);
console.log('Local version:', env.modulePackage.version || 'Unknown');
exit(0);
}
if (!env.modulePath) {
var missingNodeModules =
fs.existsSync(path.join(env.cwd, 'package.json'))
&& !fs.existsSync(path.join(env.cwd, 'node_modules'));
var hasYarn = fs.existsSync(path.join(env.cwd, 'yarn.lock'));
if (missingNodeModules) {
log.error({ tag: messages.MISSING_NODE_MODULES, cwd: env.cwd });
if (hasYarn) {
log.error({ tag: messages.YARN_INSTALL })
} else {
log.error({ tag: messages.NPM_INSTALL })
}
} else {
log.error({ tag: messages.MISSING_GULP, cwd: env.cwd });
if (hasYarn) {
log.error({ tag: messages.YARN_INSTALL_GULP });
} else {
log.error({ tag: messages.NPM_INSTALL_GULP });
}
}
exit(1);
}
if (!env.configPath) {
log.error({ tag: messages.MISSING_GULPFILE });
exit(1);
}
// Chdir before requiring gulpfile to make sure
// we let them chdir as needed
if (process.cwd() !== env.cwd) {
process.chdir(env.cwd);
log.info({ tag: messages.CWD_CHANGED, cwd: env.cwd });
}
// Find the correct CLI version to run
var range = findRange(env.modulePackage.version, ranges);
if (!range) {
log.error({ tag: messages.UNSUPPORTED_GULP_VERSION, version: env.modulePackage.version });
exit(1);
}
// Load and execute the CLI version
var versionedDir = path.join(__dirname, '/lib/versioned/', range, '/');
require(versionedDir)(env, flags, translate);
}

19
node_modules/gulp-cli/lib/shared/array-find.js generated vendored Normal file
View File

@@ -0,0 +1,19 @@
'use strict';
function arrayFind(arr, fn) {
if (!Array.isArray(arr)) {
return;
}
var idx = 0;
while (idx < arr.length) {
var result = fn(arr[idx]);
if (result) {
// TODO: This is wrong in Liftoff
return arr[idx];
}
idx++;
}
}
module.exports = arrayFind;

20
node_modules/gulp-cli/lib/shared/completion.js generated vendored Normal file
View File

@@ -0,0 +1,20 @@
'use strict';
var fs = require('fs');
var path = require('path');
var messages = require('@gulpjs/messages');
module.exports = function(name, translate) {
if (typeof name !== 'string') {
throw new Error(translate.message({ tag: messages.COMPLETION_TYPE_MISSING }));
}
var file = path.join(__dirname, '../../completion', name);
try {
console.log(fs.readFileSync(file, 'utf8'));
process.exit(0);
} catch (err) {
console.log(translate.message({ tag: messages.COMPLETION_TYPE_UNKNOWN, name: name }));
process.exit(5);
}
};

26
node_modules/gulp-cli/lib/shared/config/cli-flags.js generated vendored Normal file
View File

@@ -0,0 +1,26 @@
'use strict';
var copyProps = require('copy-props');
var fromConfigToCliOpts = {
'flags.silent': 'silent',
'flags.continue': 'continue',
'flags.series': 'series',
'flags.logLevel': 'logLevel',
'flags.compactTasks': 'compactTasks',
'flags.tasksDepth': 'tasksDepth',
'flags.sortTasks': 'sortTasks',
};
function mergeCliOpts(opts, config) {
opts = copyProps(opts, {});
return copyProps(config, opts, fromConfigToCliOpts, defaults);
}
function defaults(cfgInfo, optInfo) {
if (optInfo.value === undefined) {
return cfgInfo.value;
}
}
module.exports = mergeCliOpts;

15
node_modules/gulp-cli/lib/shared/exit.js generated vendored Normal file
View File

@@ -0,0 +1,15 @@
'use strict';
// Fix stdout truncation on windows
function exit(code) {
/* istanbul ignore next */
if (process.platform === 'win32' && process.stdout.bufferSize) {
process.stdout.once('drain', function() {
process.exit(code);
});
return;
}
process.exit(code);
}
module.exports = exit;

7
node_modules/gulp-cli/lib/shared/is-object.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
'use strict';
function isObject(v) {
return (v != null && typeof v === 'object' && !Array.isArray(v));
}
module.exports = isObject;

81
node_modules/gulp-cli/lib/shared/log/copy-tree.js generated vendored Normal file
View File

@@ -0,0 +1,81 @@
'use strict';
function copyNode(node) {
var newNode = {};
Object.keys(node).forEach(function(key) {
newNode[key] = node[key];
});
return newNode;
}
var defaultNodeFactory = {
topNode: copyNode,
taskNode: copyNode,
childNode: copyNode,
};
function copyTree(tree, opts, nodeFactory) {
opts = opts || {};
var depth = opts.tasksDepth;
depth = typeof depth === 'number' ? ((depth < 1) ? 1 : depth) : null;
nodeFactory = nodeFactory || defaultNodeFactory;
var newTree = nodeFactory.topNode(tree);
newTree.nodes = [];
if (Array.isArray(tree.nodes)) {
tree.nodes.forEach(visit);
}
function visit(node) {
var newNode = nodeFactory.taskNode(node);
newNode.nodes = [];
newTree.nodes.push(newNode);
if (opts.compactTasks) {
forEach(node.nodes, copyNotRecursively, newNode);
} else if (!depth || depth > 1) {
forEach(node.nodes, copyRecursively, depth, 2, newNode);
}
}
function copyNotRecursively(child, newParent) {
var newChild = nodeFactory.childNode(child);
newChild.nodes = [];
newParent.nodes.push(newChild);
if (child.branch) {
forEach(child.nodes, copyNotRecursively, newChild);
}
}
function copyRecursively(child, maxDepth, nowDepth, newParent) {
var newChild = nodeFactory.childNode(child);
newChild.nodes = [];
newParent.nodes.push(newChild);
if (!maxDepth || maxDepth > nowDepth) {
forEach(child.nodes, copyRecursively, maxDepth, nowDepth + 1, newChild);
}
}
return newTree;
}
function forEach(nodes, fn) {
if (!Array.isArray(nodes)) {
return;
}
var args = Array.prototype.slice.call(arguments, 2);
for (var i = 0, n = nodes.length; i < n; i++) {
fn.apply(nodes[i], [nodes[i]].concat(args));
}
}
module.exports = copyTree;

48
node_modules/gulp-cli/lib/shared/log/format-hrtime.js generated vendored Normal file
View File

@@ -0,0 +1,48 @@
'use strict';
var units = [
[ 'h', 3600e9 ],
[ 'min', 60e9 ],
[ 's', 1e9 ],
[ 'ms', 1e6 ],
[ 'μs', 1e3 ],
];
function formatHrTime(hrtime) {
if (!Array.isArray(hrtime) || hrtime.length !== 2) {
return '';
}
if (typeof hrtime[0] !== 'number' || typeof hrtime[1] !== 'number') {
return '';
}
var nano = hrtime[0] * 1e9 + hrtime[1];
for (var i = 0; i < units.length; i++) {
if (nano < units[i][1]) {
continue;
}
if (nano >= units[i][1] * 10) {
return Math.round(nano / units[i][1]) + ' ' + units[i][0];
}
var s = String(Math.round(nano * 1e2 / units[i][1]));
if (s.slice(-2) === '00') {
s = s.slice(0, -2);
} else if (s.slice(-1) === '0') {
s = s.slice(0, -2) + '.' + s.slice(-2, -1);
} else {
s = s.slice(0, -2) + '.' + s.slice(-2);
}
return s + ' ' + units[i][0];
}
if (nano > 0) {
return nano + ' ns';
}
return '';
}
module.exports = formatHrTime;

171
node_modules/gulp-cli/lib/shared/log/tasks.js generated vendored Normal file
View File

@@ -0,0 +1,171 @@
'use strict';
var stringWidth = require('string-width');
var messages = require('@gulpjs/messages');
var isObject = require('../is-object');
function logTasks(tree, opts, getTask, translate) {
if (opts.sortTasks) {
tree.nodes = tree.nodes.sort(compareByLabel);
}
var maxDepth = opts.tasksDepth;
if (typeof maxDepth !== 'number') {
maxDepth = 50;
} else if (maxDepth < 1) {
maxDepth = 1;
}
var compactedTasks = opts.compactTasks ? tree.nodes : [];
var treeOpts = {
maxDepth: maxDepth,
compactedTasks: compactedTasks,
getTask: getTask,
};
printTaskTree(tree, treeOpts);
function printTaskTree(tree, opts) {
var lines = [];
lines.push({ label: tree.label });
var maxLabelWidth = 0;
tree.nodes.forEach(function(node, idx, arr) {
var isLast = idx === arr.length - 1;
var w = createTreeLines(node, lines, opts, 1, '', isLast);
maxLabelWidth = Math.max(maxLabelWidth, w);
});
lines.forEach(function(line) {
var s = line.label;
if (line.desc) {
var spaces = ' '.repeat(maxLabelWidth - line.width) + ' ';
s += spaces + line.desc;
}
if (s) {
// We don't need timestamps here
console.log(s);
}
});
}
function createTreeLines(node, lines, opts, depth, bars, isLast) {
var task = { label: node.label, bars: bars, depth: depth };
if (depth === 1) {
var t = opts.getTask(node.label);
task.desc = t.description;
task.flags = t.flags;
}
var isLeaf = isLeafNode(node, depth, opts);
var maxLabelWidth = addTaskToLines(task, lines, isLast, isLeaf);
if (!isLeaf) {
bars += (isLast ? ' ' : translate.message({ tag: messages.BOX_DRAWINGS_LIGHT_VERTICAL }));
bars += ' '
node.nodes.forEach(function(node, idx, arr) {
var isLast = idx === arr.length - 1;
createTreeLines(node, lines, opts, depth + 1, bars, isLast);
});
}
return maxLabelWidth;
}
function addTaskToLines(task, lines, isLast, isLeaf) {
var taskBars = task.bars + (isLast
? translate.message({ tag: messages.BOX_DRAWINGS_LIGHT_UP_AND_RIGHT })
: translate.message({ tag: messages.BOX_DRAWINGS_LIGHT_VERTICAL_AND_RIGHT })) +
translate.message({ tag: messages.BOX_DRAWINGS_LIGHT_HORIZONTAL });
if (isLeaf) {
taskBars += translate.message({ tag: messages.BOX_DRAWINGS_LIGHT_HORIZONTAL });
} else {
taskBars += translate.message({ tag: messages.BOX_DRAWINGS_LIGHT_DOWN_AND_HORIZONTAL });
}
taskBars += ' ';
var line = {};
if (task.depth === 1) {
line.label = taskBars + translate.message({ tag: messages.TASK_NAME, name: task.label });
} else {
line.label = taskBars + translate.message({ tag: messages.TASK_NAME, name: task.label });
}
line.width = stringWidth(line.label);
if (typeof task.desc === 'string' && task.desc) {
line.desc = translate.message({ tag: messages.TASK_DESCRIPTION, description: task.desc });
}
lines.push(line);
var maxLabelWidth = line.width;
if (!isObject(task.flags)) {
return maxLabelWidth;
}
var flagBars = task.bars;
if (isLast) {
flagBars += ' ';
} else {
flagBars += translate.message({ tag: messages.BOX_DRAWINGS_LIGHT_VERTICAL });
}
flagBars += ' ';
if (isLeaf) {
flagBars += ' ';
} else {
flagBars += translate.message({ tag: messages.BOX_DRAWINGS_LIGHT_VERTICAL });
}
flagBars += ' ';
Object.entries(task.flags).sort(flagSorter).forEach(addFlagsToLines);
function addFlagsToLines(ent) {
if (typeof ent[0] !== 'string' || !ent[0]) return;
var line = {};
line.label = flagBars + translate.message({ tag: messages.TASK_FLAG, flag: ent[0] });
line.width = stringWidth(line.label);
maxLabelWidth = Math.max(maxLabelWidth, line.width);
if (typeof ent[1] === 'string' && ent[1] !== '') {
line.desc = translate.message({ tag: messages.TASK_FLAG_DESCRIPTION, description: ent[1] });
}
lines.push(line);
}
return maxLabelWidth;
}
}
function isLeafNode(node, depth, opts) {
if (depth >= opts.maxDepth) {
return true;
} else if (depth > 1 && opts.compactedTasks.includes(node)) {
return true;
} else if (!Array.isArray(node.nodes) || node.nodes.length === 0) {
return true;
}
return false;
}
function compareByLabel(a, b) {
/* istanbul ignore if */
if (!b.label) {
return -1;
} else /* istanbul ignore if */ if (!a.label) {
return 1;
} else {
return (a.label <= b.label) ? -1 : 1;
}
}
function flagSorter(a, b) {
return (a[0] <= b[0]) ? -1 : 1;
}
module.exports = logTasks;

135
node_modules/gulp-cli/lib/shared/log/to-console.js generated vendored Normal file
View File

@@ -0,0 +1,135 @@
'use strict';
var messages = require('@gulpjs/messages');
/* istanbul ignore next */
function noop() {}
function toConsole(log, opts, translate) {
// Return immediately if logging is
// not desired.
if (opts.tasksSimple || opts.tasksJson || opts.help || opts.version || opts.silent) {
// Keep from crashing process when silent.
log.on('error', noop);
return function () {
log.removeListener('error', noop);
};
}
// Default loglevel to info level (3).
var loglevel = opts.logLevel || 3;
var deprecatedPrinted = false;
log.on('deprecated', onDeprecated);
// -L: Logs error events.
if (loglevel > 0) {
log.on('error', onError);
}
// -LL: Logs warn and error events.
if (loglevel > 1) {
log.on('warn', onWarn);
}
// -LLL: Logs info, warn and error events.
if (loglevel > 2) {
log.on('info', onInfo);
}
if (loglevel > 3) {
log.on('debug', onDebug);
}
return function () {
log.removeListener('deprecated', onDeprecated);
log.removeListener('error', onError);
log.removeListener('warn', onWarn);
log.removeListener('info', onInfo);
log.removeListener('debug', onDebug);
};
function onDeprecated() {
if (!deprecatedPrinted) {
var msg = { tag: messages.GULPLOG_DEPRECATED };
// Get message and timestamp before printing anything to avoid
// logging a half message if there's an error in one of them
var message = translate.message(msg);
var timestamp = translate.timestamp(msg);
if (message) {
// Ensure timestamp is not written without a message
if (timestamp) {
process.stderr.write(timestamp + ' ');
}
console.error(message);
}
deprecatedPrinted = true;
}
}
function onError(msg) {
// Get message and timestamp before printing anything to avoid
// logging a half message if there's an error in one of them
var message = translate.message(msg);
var timestamp = translate.timestamp(msg);
if (message) {
// Ensure timestamp is not written without a message
if (timestamp) {
process.stderr.write(timestamp + ' ');
}
console.error(message);
}
}
// onWarn, onInfo, and onDebug are currently all the same
// implementation but separated to change independently
function onWarn(msg) {
// Get message and timestamp before printing anything to avoid
// logging a half message if there's an error in one of them
var message = translate.message(msg);
var timestamp = translate.timestamp(msg);
if (message) {
// Ensure timestamp is not written without a message
if (timestamp) {
process.stdout.write(timestamp + ' ');
}
console.log(message);
}
}
function onInfo(msg) {
// Get message and timestamp before printing anything to avoid
// logging a half message if there's an error in one of them
var message = translate.message(msg);
var timestamp = translate.timestamp(msg);
if (message) {
// Ensure timestamp is not written without a message
if (timestamp) {
process.stdout.write(timestamp + ' ');
}
console.log(message);
}
}
function onDebug(msg) {
// Get message and timestamp before printing anything to avoid
// logging a half message if there's an error in one of them
var message = translate.message(msg);
var timestamp = translate.timestamp(msg);
if (message) {
// Ensure timestamp is not written without a message
if (timestamp) {
process.stdout.write(timestamp + ' ');
}
console.log(message);
}
}
}
module.exports = toConsole;

11
node_modules/gulp-cli/lib/shared/make-title.js generated vendored Normal file
View File

@@ -0,0 +1,11 @@
'use strict';
function makeTitle(cmd, argv) {
if (!argv || argv.length === 0) {
return cmd;
}
return [cmd].concat(argv).join(' ');
}
module.exports = makeTitle;

View File

@@ -0,0 +1,94 @@
'use strict';
var messages = require('@gulpjs/messages');
var options = {
help: {
alias: 'h',
type: 'boolean',
tag: messages.FLAG_HELP,
},
version: {
alias: 'v',
type: 'boolean',
tag: messages.FLAG_VERSION,
},
preload: {
type: 'string',
requiresArg: true,
tag: messages.FLAG_PRELOAD,
},
gulpfile: {
alias: 'f',
type: 'string',
requiresArg: true,
tag: messages.FLAG_GULPFILE,
},
cwd: {
type: 'string',
requiresArg: true,
tag: messages.FLAG_CWD,
},
tasks: {
alias: 'T',
type: 'boolean',
tag: messages.FLAG_TASKS,
},
'tasks-simple': {
type: 'boolean',
tag: messages.FLAG_TASKS_SIMPLE,
},
'tasks-json': {
tag: messages.FLAG_TASKS_JSON,
},
'tasks-depth': {
alias: 'depth',
type: 'number',
requiresArg: true,
default: undefined, // To detect if this cli option is specified.
tag: messages.FLAG_TASKS_DEPTH,
},
'compact-tasks': {
type: 'boolean',
default: undefined, // To detect if this cli option is specified.
tag: messages.FLAG_COMPACT_TASKS,
},
'sort-tasks': {
type: 'boolean',
default: undefined, // To detect if this cli option is specified.
tag: messages.FLAG_SORT_TASKS,
},
color: {
type: 'boolean',
tag: messages.FLAG_COLOR,
},
'no-color': {
type: 'boolean',
tag: messages.FLAG_NO_COLOR,
},
silent: {
alias: 'S',
type: 'boolean',
default: undefined, // To detect if this cli option is specified.
tag: messages.FLAG_SILENT,
},
continue: {
type: 'boolean',
default: undefined, // To detect if this cli option is specified.
tag: messages.FLAG_CONTINUE,
},
series: {
type: 'boolean',
default: undefined, // To detect if this cli option is specified.
tag: messages.FLAG_SERIES,
},
'log-level': {
alias: 'L',
// Type isn't needed because count acts as a boolean
count: true,
default: undefined, // To detect if this cli option is specified.
tag: messages.FLAG_LOG_LEVEL,
}
};
module.exports = options;

24
node_modules/gulp-cli/lib/shared/options/make-help.js generated vendored Normal file
View File

@@ -0,0 +1,24 @@
'use strict';
var cliOptions = require('./cli-options');
var messages = require('@gulpjs/messages');
function makeHelp(parser, translate) {
var usage = translate.message({ tag: messages.USAGE });
if (usage) {
parser.usage(usage);
}
Object.keys(cliOptions).forEach(function (flag) {
var opt = cliOptions[flag];
var description = translate.message({ tag: opt.tag });
if (description) {
parser.describe(flag, description);
}
});
return parser;
}
module.exports = makeHelp;

21
node_modules/gulp-cli/lib/shared/register-exports.js generated vendored Normal file
View File

@@ -0,0 +1,21 @@
'use strict';
function registerExports(gulpInst, tasks) {
var taskNames = Object.keys(tasks);
if (taskNames.length) {
taskNames.forEach(register);
}
function register(taskName) {
var task = tasks[taskName];
if (typeof task !== 'function') {
return;
}
gulpInst.task(task.displayName || taskName, task);
}
}
module.exports = registerExports;

39
node_modules/gulp-cli/lib/shared/require-or-import.js generated vendored Normal file
View File

@@ -0,0 +1,39 @@
'use strict';
var pathToFileURL = require('url').pathToFileURL;
var importESM;
try {
// Node.js <10 errors out with a SyntaxError when loading a script that uses import().
// So a function is dynamically created to catch the SyntaxError at runtime instead of parsetime.
// That way we can keep supporting all Node.js versions all the way back to 0.10.
importESM = new Function('id', 'return import(id);');
} catch (e) {
/* istanbul ignore next */
importESM = null;
}
function requireOrImport(path, callback) {
var err = null;
var cjs;
try {
cjs = require(path);
} catch (e) {
/* istanbul ignore else */
if (pathToFileURL && importESM) {
// Because e.code is undefined on nyc process.
/* istanbul ignore else */
if (e.code === 'ERR_REQUIRE_ESM' || process.env.NYC_CONFIG) {
// This is needed on Windows, because import() fails if providing a Windows file path.
var url = pathToFileURL(path);
importESM(url).then(function(esm) { callback(null, esm); }, callback);
return;
}
}
/* istanbul ignore next */
err = e;
}
process.nextTick(function() { callback(err, cjs); });
}
module.exports = requireOrImport;

9
node_modules/gulp-cli/lib/shared/tildify.js generated vendored Normal file
View File

@@ -0,0 +1,9 @@
'use strict';
var replaceHomedir = require('replace-homedir');
function tildify(filepath) {
return replaceHomedir(filepath, '~');
}
module.exports = tildify;

305
node_modules/gulp-cli/lib/shared/translate.js generated vendored Normal file
View File

@@ -0,0 +1,305 @@
'use strict';
var util = require('util');
var chalk = require('chalk');
var messages = require('@gulpjs/messages');
var tildify = require('./tildify');
var formatTime = require('./log/format-hrtime');
function Timestamp() {
this.now = new Date();
}
Timestamp.prototype[util.inspect.custom] = function (depth, opts) {
var timestamp = this.now.toLocaleTimeString('en', { hour12: false });
return '[' + opts.stylize(timestamp, 'date') + ']';
};
function getDefaultMessage(data) {
switch (data.tag) {
case messages.PRELOAD_BEFORE: {
return 'Preloading external module: ' + chalk.magenta(data.name);
}
case messages.PRELOAD_SUCCESS: {
return 'Preloaded external module: ' + chalk.magenta(data.name)
}
case messages.PRELOAD_FAILURE: {
return chalk.yellow('Failed to preload external module: ') + chalk.magenta(data.name);
}
case messages.PRELOAD_ERROR: {
return chalk.yellow(data.error.toString());
}
case messages.LOADER_SUCCESS: {
return 'Loaded external module: ' + chalk.magenta(data.name);
}
case messages.LOADER_FAILURE: {
return chalk.yellow('Failed to load external module: ') + chalk.magenta(data.name);
}
case messages.LOADER_ERROR: {
return chalk.yellow(data.error.toString());
}
case messages.NODE_FLAGS: {
var nodeFlags = chalk.magenta(data.flags.join(', '));
return 'Node flags detected: ' + nodeFlags;
}
case messages.RESPAWNED: {
var pid = chalk.magenta(data.pid);
return 'Respawned to PID: ' + pid;
}
case messages.MISSING_GULPFILE: {
return chalk.red('No gulpfile found');
}
case messages.CWD_CHANGED: {
return 'Working directory changed to ' + chalk.magenta(tildify(data.cwd));
}
case messages.UNSUPPORTED_GULP_VERSION: {
return chalk.red('Unsupported gulp version', data.version)
}
case messages.DESCRIPTION: {
return 'Tasks for ' + chalk.magenta(tildify(data.path));
}
case messages.GULPFILE: {
return 'Using gulpfile ' + chalk.magenta(tildify(data.path));
}
case messages.TASK_START: {
return "Starting '" + chalk.cyan(data.task) + "'..."
}
case messages.TASK_STOP: {
return "Finished '" + chalk.cyan(data.task) + "' after " + chalk.magenta(formatTime(data.duration));
}
case messages.TASK_FAILURE: {
return "'" + chalk.cyan(data.task) + "' " + chalk.red('errored after') + ' ' + chalk.magenta(formatTime(data.duration));
}
case messages.TASK_MISSING: {
if (data.similar) {
return chalk.red('Task never defined: ' + data.task + ' - did you mean? ' + data.similar.join(', '))
+ '\nTo list available tasks, try running: gulp --tasks';
} else {
return chalk.red('Task never defined: ' + data.task) +
'\nTo list available tasks, try running: gulp --tasks';
}
}
case messages.TASK_SYNC: {
return chalk.red('The following tasks did not complete: ') + chalk.cyan(data.tasks) + "\n"
+ chalk.red('Did you forget to signal async completion?');
}
case messages.MISSING_NODE_MODULES: {
return chalk.red('Local modules not found in') + ' ' + chalk.magenta(tildify(data.cwd));
}
case messages.MISSING_GULP: {
return chalk.red('Local gulp not found in') + ' ' + chalk.magenta(tildify(data.cwd));
}
case messages.YARN_INSTALL: {
return chalk.red('Try running: yarn install');
}
case messages.NPM_INSTALL: {
return chalk.red('Try running: npm install');
}
case messages.YARN_INSTALL_GULP: {
return chalk.red('Try running: yarn add gulp');
}
case messages.NPM_INSTALL_GULP: {
return chalk.red('Try running: npm install gulp');
}
case messages.GULPLOG_DEPRECATED: {
return chalk.yellow("gulplog v1 is deprecated. Please help your plugins update!");
}
case messages.COMPLETION_TYPE_MISSING: {
return 'Missing completion type';
}
case messages.COMPLETION_TYPE_UNKNOWN: {
return 'echo "gulp autocompletion rules for' + " '" + data.name + "' " + 'not found"'
}
case messages.ARGV_ERROR: {
return data.message;
}
case messages.EXEC_ERROR: {
return data.message;
}
case messages.TASK_ERROR: {
return data.message;
}
case messages.USAGE: {
return '\n' + chalk.bold('Usage:') + ' gulp ' + chalk.blue('[options]') + ' tasks';
}
case messages.FLAG_HELP: {
return chalk.gray('Show this help.');
}
case messages.FLAG_VERSION: {
return chalk.gray('Print the global and local gulp versions.');
}
case messages.FLAG_PRELOAD: {
return chalk.gray(
'Will preload a module before running the gulpfile. ' +
'This is useful for transpilers but also has other applications.'
);
}
case messages.FLAG_GULPFILE: {
return chalk.gray(
'Manually set path of gulpfile. Useful if you have multiple gulpfiles. ' +
'This will set the CWD to the gulpfile directory as well.'
)
}
case messages.FLAG_CWD: {
return chalk.gray(
'Manually set the CWD. The search for the gulpfile, ' +
'as well as the relativity of all requires will be from here.'
);
}
case messages.FLAG_TASKS: {
return chalk.gray('Print the task dependency tree for the loaded gulpfile.');
}
case messages.FLAG_TASKS_SIMPLE: {
return chalk.gray('Print a plaintext list of tasks for the loaded gulpfile.');
}
case messages.FLAG_TASKS_JSON: {
return chalk.gray(
'Print the task dependency tree, ' +
'in JSON format, for the loaded gulpfile.'
);
}
case messages.FLAG_TASKS_DEPTH: {
return chalk.gray('Specify the depth of the task dependency tree.');
}
case messages.FLAG_COMPACT_TASKS: {
return chalk.gray(
'Reduce the output of task dependency tree by printing ' +
'only top tasks and their child tasks.'
);
}
case messages.FLAG_SORT_TASKS: {
return chalk.gray('Will sort top tasks of task dependency tree.');
}
case messages.FLAG_COLOR: {
return chalk.gray(
'Will force gulp and gulp plugins to display colors, ' +
'even when no color support is detected.'
);
}
case messages.FLAG_NO_COLOR: {
return chalk.gray(
'Will force gulp and gulp plugins to not display colors, ' +
'even when color support is detected.'
);
}
case messages.FLAG_SILENT: {
return chalk.gray('Suppress all gulp logging.');
}
case messages.FLAG_CONTINUE: {
return chalk.gray('Continue execution of tasks upon failure.');
}
case messages.FLAG_SERIES: {
return chalk.gray('Run tasks given on the CLI in series (the default is parallel).');
}
case messages.FLAG_LOG_LEVEL: {
return chalk.gray(
'Set the loglevel. -L for least verbose and -LLLL for most verbose. ' +
'-LLL is default.'
);
}
case messages.TASK_NAME: {
return chalk.cyan(data.name);
}
case messages.TASK_DESCRIPTION: {
return chalk.white(data.description);
}
case messages.TASK_FLAG: {
return chalk.magenta(data.flag);
}
case messages.TASK_FLAG_DESCRIPTION: {
return chalk.white('…' + data.description);
}
case messages.BOX_DRAWINGS_LIGHT_UP_AND_RIGHT: {
return chalk.white('└');
}
case messages.BOX_DRAWINGS_LIGHT_VERTICAL_AND_RIGHT: {
return chalk.white('├');
}
case messages.BOX_DRAWINGS_LIGHT_HORIZONTAL: {
return chalk.white('─');
}
case messages.BOX_DRAWINGS_LIGHT_DOWN_AND_HORIZONTAL: {
return chalk.white('┬');
}
case messages.BOX_DRAWINGS_LIGHT_VERTICAL: {
return chalk.white('│');
}
default: {
return data;
}
}
}
function getDefaultTimestamp() {
return util.inspect(new Timestamp(), { colors: !!chalk.supportsColor });
}
function buildTranslations(cfg) {
cfg = cfg || {};
return {
message: function (data) {
// Don't allow an `undefined` message through
if (typeof data === 'undefined') {
data = Object.create(null);
}
var message;
if (typeof cfg.message === 'function') {
try {
message = cfg.message(data);
} catch (err) {
console.error('A problem occurred with the user-defined `message()` function.');
console.error('Please correct your `.gulp.*` config file.');
}
}
// If the user has provided a message, return it
if (message) {
return message;
}
// Users can filter messages by explicitly returning `false`
if (message === false) {
return '';
}
// If the user hasn't returned a message or silenced it with `false`
// get the default message. Will return the first argument if the message
// is not defined in the `@gulpjs/messages` package
return getDefaultMessage(data);
},
timestamp: function (data) {
// Don't allow an `undefined` message through
if (typeof data === 'undefined') {
data = Object.create(null);
}
var time;
if (typeof cfg.timestamp === 'function') {
try {
time = cfg.timestamp(data);
} catch (err) {
console.error('A problem occurred with the user-defined `timestamp()` function.');
console.error('Please correct your `.gulp.*` config file.');
}
}
// If the user has provided a timestamp, return it
if (time) {
return time;
}
// Users can filter timestamps by explicitly returning `false`
if (time === false) {
return '';
}
return getDefaultTimestamp();
}
}
}
module.exports = buildTranslations;

View File

@@ -0,0 +1,23 @@
'use strict';
// Format orchestrator errors
function formatError(e) {
if (!e.err) {
return e.message;
}
// PluginError
if (typeof e.err.showStack === 'boolean') {
return e.err.toString();
}
// Normal error
if (e.err.stack) {
return e.err.stack;
}
// Unknown (string, number, etc.)
return new Error(String(e.err)).stack;
}
module.exports = formatError;

74
node_modules/gulp-cli/lib/versioned/^3.7.0/index.js generated vendored Normal file
View File

@@ -0,0 +1,74 @@
'use strict';
var fs = require('fs');
var log = require('gulplog');
var stdout = require('mute-stdout');
var messages = require('@gulpjs/messages');
var taskTree = require('./task-tree');
var copyTree = require('../../shared/log/copy-tree');
var logTasks = require('../../shared/log/tasks');
var exit = require('../../shared/exit');
var logEvents = require('./log/events');
var logTasksSimple = require('./log/tasks-simple');
var registerExports = require('../../shared/register-exports');
var requireOrImport = require('../../shared/require-or-import');
function execute(env, opts, translate) {
var tasks = opts._;
var toRun = tasks.length ? tasks : ['default'];
if (opts.tasksSimple || opts.tasks || opts.tasksJson) {
// Mute stdout if we are listing tasks
stdout.mute();
}
// This is what actually loads up the gulpfile
requireOrImport(env.configPath, function(err, exported) {
// Before import(), if require() failed we got an unhandled exception on the module level.
// So console.error() & exit() were added here to mimic the old behavior as close as possible.
if (err) {
console.error(err);
exit(1);
}
log.info({ tag: messages.GULPFILE, path: env.configPath });
var gulpInst = require(env.modulePath);
logEvents(gulpInst);
registerExports(gulpInst, exported);
// Always unmute stdout after gulpfile is required
stdout.unmute();
var tree;
if (opts.tasksSimple) {
return logTasksSimple(env, gulpInst);
}
if (opts.tasks) {
tree = taskTree(gulpInst.tasks);
tree.label = translate.message({ tag: messages.DESCRIPTION, path: env.configPath });
return logTasks(tree, opts, function(task) {
return gulpInst.tasks[task].fn;
}, translate);
}
if (opts.tasksJson) {
tree = taskTree(gulpInst.tasks);
tree.label = translate.message({ tag: messages.DESCRIPTION, path: env.configPath });
var output = JSON.stringify(copyTree(tree, opts));
if (typeof opts.tasksJson === 'boolean') {
return console.log(output);
}
return fs.writeFileSync(opts.tasksJson, output, 'utf-8');
}
gulpInst.start.apply(gulpInst, toRun);
});
}
module.exports = execute;

View File

@@ -0,0 +1,46 @@
'use strict';
var log = require('gulplog');
var messages = require('@gulpjs/messages');
var exit = require('../../../shared/exit');
var formatError = require('../format-error');
// Wire up logging events
function logEvents(gulpInst) {
// Exit with 0 or 1
var failed = false;
process.once('exit', function(code) {
if (code === 0 && failed) {
exit(1);
}
});
// Total hack due to poor error management in orchestrator
gulpInst.on('err', function() {
failed = true;
});
gulpInst.on('task_start', function(e) {
// TODO: batch these
// so when 5 tasks start at once it only logs one time with all 5
log.info({ tag: messages.TASK_START, task: e.task });
});
gulpInst.on('task_stop', function(e) {
log.info({ tag: messages.TASK_STOP, task: e.task, duration: e.hrDuration });
});
gulpInst.on('task_err', function(e) {
log.error({ tag: messages.TASK_FAILURE, task: e.task, duration: e.hrDuration });
log.error({ tag: messages.TASK_ERROR, message: formatError(e) });
});
gulpInst.on('task_not_found', function(err) {
log.error({ tag: messages.TASK_MISSING, task: err.task });
exit(1);
});
}
module.exports = logEvents;

View File

@@ -0,0 +1,9 @@
'use strict';
function logTasksSimple(env, localGulp) {
console.log(Object.keys(localGulp.tasks)
.join('\n')
.trim());
}
module.exports = logTasksSimple;

View File

@@ -0,0 +1,27 @@
'use strict';
module.exports = function(tasks) {
var map = {};
var arr = [];
Object.keys(tasks).forEach(function(taskname) {
var task = {
label: taskname,
type: 'task',
nodes: [],
};
map[taskname] = task;
arr.push(task);
});
Object.keys(tasks).forEach(function(taskname) {
var task = map[taskname];
tasks[taskname].dep.forEach(function(childname) {
var child = map[childname] || {
label: childname,
type: 'task',
nodes: [],
};
task.nodes.push(child);
});
});
return { label: 'Tasks', nodes: arr };
};

View File

@@ -0,0 +1,24 @@
'use strict';
// Format orchestrator errors
/* istanbul ignore next */
function formatError(e) {
if (!e.error) {
return e.message;
}
// PluginError
if (typeof e.error.showStack === 'boolean') {
return e.error.toString();
}
// Normal error
if (e.error.stack) {
return e.error.stack;
}
// Unknown (string, number, etc.)
return new Error(String(e.error)).stack;
}
module.exports = formatError;

91
node_modules/gulp-cli/lib/versioned/^4.0.0/index.js generated vendored Normal file
View File

@@ -0,0 +1,91 @@
'use strict';
var fs = require('fs');
var log = require('gulplog');
var stdout = require('mute-stdout');
var messages = require('@gulpjs/messages');
var exit = require('../../shared/exit');
var logTasks = require('../../shared/log/tasks');
var logEvents = require('./log/events');
var logSyncTask = require('./log/sync-task');
var normalizeError = require('./normalize-error');
var logTasksSimple = require('./log/tasks-simple');
var registerExports = require('../../shared/register-exports');
var copyTree = require('../../shared/log/copy-tree');
var getTask = require('./log/get-task');
var requireOrImport = require('../../shared/require-or-import');
function execute(env, opts, translate) {
var tasks = opts._;
var toRun = tasks.length ? tasks : ['default'];
if (opts.tasksSimple || opts.tasks || opts.tasksJson) {
// Mute stdout if we are listing tasks
stdout.mute();
}
var gulpInst = require(env.modulePath);
logEvents(gulpInst);
logSyncTask(gulpInst, opts);
// This is what actually loads up the gulpfile
requireOrImport(env.configPath, function(err, exported) {
// Before import(), if require() failed we got an unhandled exception on the module level.
// So console.error() & exit() were added here to mimic the old behavior as close as possible.
if (err) {
console.error(err);
exit(1);
}
registerExports(gulpInst, exported);
// Always unmute stdout after gulpfile is required
stdout.unmute();
var tree;
if (opts.tasksSimple) {
tree = gulpInst.tree();
return logTasksSimple(tree.nodes);
}
if (opts.tasks) {
tree = gulpInst.tree({ deep: true });
tree.label = translate.message({ tag: messages.DESCRIPTION, path: env.configPath });
return logTasks(tree, opts, getTask(gulpInst), translate);
}
if (opts.tasksJson) {
tree = gulpInst.tree({ deep: true });
tree.label = translate.message({ tag: messages.DESCRIPTION, path: env.configPath });
var output = JSON.stringify(copyTree(tree, opts));
if (typeof opts.tasksJson === 'boolean' && opts.tasksJson) {
return console.log(output);
}
return fs.writeFileSync(opts.tasksJson, output, 'utf-8');
}
try {
log.info({ tag: messages.GULPFILE, path: env.configPath });
var runMethod = opts.series ? 'series' : 'parallel';
gulpInst[runMethod](toRun)(function(err) {
if (err) {
exit(1);
}
});
} catch (err) {
normalizeError(err);
if (err.task) {
log.error({ tag: messages.TASK_MISSING, task: err.task, similar: err.similar });
} else {
log.error({ tag: messages.EXEC_ERROR, message: err.message, error: err });
}
exit(1);
}
});
}
module.exports = execute;

View File

@@ -0,0 +1,39 @@
'use strict';
var log = require('gulplog');
var messages = require('@gulpjs/messages');
var formatError = require('../format-error');
// Wire up logging events
function logEvents(gulpInst) {
var loggedErrors = [];
gulpInst.on('start', function(evt) {
/* istanbul ignore next */
// TODO: batch these
// so when 5 tasks start at once it only logs one time with all 5
var level = evt.branch ? 'debug' : 'info';
log[level]({ tag: messages.TASK_START, task: evt.name });
});
gulpInst.on('stop', function(evt) {
/* istanbul ignore next */
var level = evt.branch ? 'debug' : 'info';
log[level]({ tag: messages.TASK_STOP, task: evt.name, duration: evt.duration });
});
gulpInst.on('error', function(evt) {
var level = evt.branch ? 'debug' : 'error';
log[level]({ tag: messages.TASK_FAILURE, task: evt.name, duration: evt.duration });
// If we haven't logged this before, log it and add to list
if (loggedErrors.indexOf(evt.error) === -1) {
log.error({ tag: messages.TASK_ERROR, message: formatError(evt) });
loggedErrors.push(evt.error);
}
});
}
module.exports = logEvents;

View File

@@ -0,0 +1,43 @@
'use strict';
var isObject = require('../../../shared/is-object');
function getTask(gulpInst) {
return function(name) {
var task = gulpInst.task(name);
return {
description: getDescription(task),
flags: getFlags(task),
};
};
}
function getDescription(task) {
if (typeof task.description === 'string') {
return task.description;
}
/* istanbul ignore else */
if (typeof task.unwrap === 'function') {
var origFn = task.unwrap();
if (typeof origFn.description === 'string') {
return origFn.description;
}
}
return undefined;
}
function getFlags(task) {
if (isObject(task.flags)) {
return task.flags;
}
/* istanbul ignore else */
if (typeof task.unwrap === 'function') {
var origFn = task.unwrap();
if (isObject(origFn.flags)) {
return origFn.flags;
}
}
return undefined;
}
module.exports = getTask;

View File

@@ -0,0 +1,46 @@
'use strict';
var log = require('gulplog');
var messages = require('@gulpjs/messages');
var tasks = {};
function warn() {
var taskKeys = Object.keys(tasks);
if (!taskKeys.length) {
return;
}
var taskNames = taskKeys.map(function(key) {
return tasks[key];
}).join(', ');
process.exitCode = 1;
log.warn({ tag: messages.TASK_SYNC, tasks: taskNames });
}
function start(e) {
tasks[e.uid] = e.name;
}
function clear(e) {
delete tasks[e.uid];
}
function clearAll() {
tasks = {};
}
function logSyncTask(gulpInst, opts) {
process.once('exit', warn);
gulpInst.on('start', start);
gulpInst.on('stop', clear);
// When not running in --continue mode, we need to clear everything on error to avoid
// false positives.
gulpInst.on('error', opts.continue ? clear : clearAll);
}
module.exports = logSyncTask;

View File

@@ -0,0 +1,7 @@
'use strict';
function logTasksSimple(nodes) {
console.log(nodes.join('\n').trim());
}
module.exports = logTasksSimple;

View File

@@ -0,0 +1,26 @@
'use strict';
// Normalize an undertaker v1 error like an undertaker v2 error
function normalizeError(err) {
/* istanbul ignore if */
if (!err || !err.message) {
return;
}
var fixed0 = 'Task never defined: ';
var fixed1 = ' - did you mean? ';
if (err.message.startsWith(fixed0)) {
var task = err.message.slice(fixed0.length);
var index = task.indexOf(fixed1);
if (index >= 0) {
err.similar = task.slice(index + fixed1.length).split(', ');
err.task = task.slice(0, index);
} else {
err.task = task
}
}
}
module.exports = normalizeError;

View File

@@ -0,0 +1,24 @@
'use strict';
// Format orchestrator errors
/* istanbul ignore next */
function formatError(e) {
if (!e.error) {
return e.message;
}
// PluginError
if (typeof e.error.showStack === 'boolean') {
return e.error.toString();
}
// Normal error
if (e.error.stack) {
return e.error.stack;
}
// Unknown (string, number, etc.)
return new Error(String(e.error)).stack;
}
module.exports = formatError;

89
node_modules/gulp-cli/lib/versioned/^5.0.0/index.js generated vendored Normal file
View File

@@ -0,0 +1,89 @@
'use strict';
var fs = require('fs');
var log = require('gulplog');
var stdout = require('mute-stdout');
var messages = require('@gulpjs/messages');
var exit = require('../../shared/exit');
var logTasks = require('../../shared/log/tasks');
var logEvents = require('./log/events');
var logSyncTask = require('./log/sync-task');
var logTasksSimple = require('./log/tasks-simple');
var registerExports = require('../../shared/register-exports');
var copyTree = require('../../shared/log/copy-tree');
var getTask = require('./log/get-task');
var requireOrImport = require('../../shared/require-or-import');
function execute(env, opts, translate) {
var tasks = opts._;
var toRun = tasks.length ? tasks : ['default'];
if (opts.tasksSimple || opts.tasks || opts.tasksJson) {
// Mute stdout if we are listing tasks
stdout.mute();
}
var gulpInst = require(env.modulePath);
logEvents(gulpInst);
logSyncTask(gulpInst, opts);
// This is what actually loads up the gulpfile
requireOrImport(env.configPath, function(err, exported) {
// Before import(), if require() failed we got an unhandled exception on the module level.
// So console.error() & exit() were added here to mimic the old behavior as close as possible.
if (err) {
console.error(err);
exit(1);
}
registerExports(gulpInst, exported);
// Always unmute stdout after gulpfile is required
stdout.unmute();
var tree;
if (opts.tasksSimple) {
tree = gulpInst.tree();
return logTasksSimple(tree.nodes);
}
if (opts.tasks) {
tree = gulpInst.tree({ deep: true });
tree.label = translate.message({ tag: messages.DESCRIPTION, path: env.configPath });
return logTasks(tree, opts, getTask(gulpInst), translate);
}
if (opts.tasksJson) {
tree = gulpInst.tree({ deep: true });
tree.label = translate.message({ tag: messages.DESCRIPTION, path: env.configPath });
var output = JSON.stringify(copyTree(tree, opts));
if (typeof opts.tasksJson === 'boolean' && opts.tasksJson) {
return console.log(output);
}
return fs.writeFileSync(opts.tasksJson, output, 'utf-8');
}
try {
log.info({ tag: messages.GULPFILE, path: env.configPath });
var runMethod = opts.series ? 'series' : 'parallel';
gulpInst[runMethod](toRun)(function(err) {
if (err) {
exit(1);
}
});
} catch (err) {
if (err.task) {
log.error({ tag: messages.TASK_MISSING, task: err.task, similar: err.similar });
} else {
log.error({ tag: messages.EXEC_ERROR, message: err.message, error: err });
}
exit(1);
}
});
}
module.exports = execute;

View File

@@ -0,0 +1,39 @@
'use strict';
var log = require('gulplog');
var messages = require('@gulpjs/messages');
var formatError = require('../format-error');
// Wire up logging events
function logEvents(gulpInst) {
var loggedErrors = [];
gulpInst.on('start', function(evt) {
/* istanbul ignore next */
// TODO: batch these
// so when 5 tasks start at once it only logs one time with all 5
var level = evt.branch ? 'debug' : 'info';
log[level]({ tag: messages.TASK_START, task: evt.name });
});
gulpInst.on('stop', function(evt) {
/* istanbul ignore next */
var level = evt.branch ? 'debug' : 'info';
log[level]({ tag: messages.TASK_STOP, task: evt.name, duration: evt.duration });
});
gulpInst.on('error', function(evt) {
var level = evt.branch ? 'debug' : 'error';
log[level]({ tag: messages.TASK_FAILURE, task: evt.name, duration: evt.duration });
// If we haven't logged this before, log it and add to list
if (loggedErrors.indexOf(evt.error) === -1) {
log.error({ tag: messages.TASK_ERROR, message: formatError(evt) });
loggedErrors.push(evt.error);
}
});
}
module.exports = logEvents;

View File

@@ -0,0 +1,43 @@
'use strict';
var isObject = require('../../../shared/is-object');
function getTask(gulpInst) {
return function(name) {
var task = gulpInst.task(name);
return {
description: getDescription(task),
flags: getFlags(task),
};
};
}
function getDescription(task) {
if (typeof task.description === 'string') {
return task.description;
}
/* istanbul ignore else */
if (typeof task.unwrap === 'function') {
var origFn = task.unwrap();
if (typeof origFn.description === 'string') {
return origFn.description;
}
}
return undefined;
}
function getFlags(task) {
if (isObject(task.flags)) {
return task.flags;
}
/* istanbul ignore else */
if (typeof task.unwrap === 'function') {
var origFn = task.unwrap();
if (isObject(origFn.flags)) {
return origFn.flags;
}
}
return undefined;
}
module.exports = getTask;

View File

@@ -0,0 +1,46 @@
'use strict';
var log = require('gulplog');
var messages = require('@gulpjs/messages');
var tasks = {};
function warn() {
var taskKeys = Object.keys(tasks);
if (!taskKeys.length) {
return;
}
var taskNames = taskKeys.map(function(key) {
return tasks[key];
}).join(', ');
process.exitCode = 1;
log.warn({ tag: messages.TASK_SYNC, tasks: taskNames });
}
function start(e) {
tasks[e.uid] = e.name;
}
function clear(e) {
delete tasks[e.uid];
}
function clearAll() {
tasks = {};
}
function logSyncTask(gulpInst, opts) {
process.once('exit', warn);
gulpInst.on('start', start);
gulpInst.on('stop', clear);
// When not running in --continue mode, we need to clear everything on error to avoid
// false positives.
gulpInst.on('error', opts.continue ? clear : clearAll);
}
module.exports = logSyncTask;

View File

@@ -0,0 +1,7 @@
'use strict';
function logTasksSimple(nodes) {
console.log(nodes.join('\n').trim());
}
module.exports = logTasksSimple;

415
node_modules/gulp-cli/node_modules/chalk/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,415 @@
/**
Basic foreground colors.
[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
*/
declare type ForegroundColor =
| 'black'
| 'red'
| 'green'
| 'yellow'
| 'blue'
| 'magenta'
| 'cyan'
| 'white'
| 'gray'
| 'grey'
| 'blackBright'
| 'redBright'
| 'greenBright'
| 'yellowBright'
| 'blueBright'
| 'magentaBright'
| 'cyanBright'
| 'whiteBright';
/**
Basic background colors.
[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
*/
declare type BackgroundColor =
| 'bgBlack'
| 'bgRed'
| 'bgGreen'
| 'bgYellow'
| 'bgBlue'
| 'bgMagenta'
| 'bgCyan'
| 'bgWhite'
| 'bgGray'
| 'bgGrey'
| 'bgBlackBright'
| 'bgRedBright'
| 'bgGreenBright'
| 'bgYellowBright'
| 'bgBlueBright'
| 'bgMagentaBright'
| 'bgCyanBright'
| 'bgWhiteBright';
/**
Basic colors.
[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
*/
declare type Color = ForegroundColor | BackgroundColor;
declare type Modifiers =
| 'reset'
| 'bold'
| 'dim'
| 'italic'
| 'underline'
| 'inverse'
| 'hidden'
| 'strikethrough'
| 'visible';
declare namespace chalk {
/**
Levels:
- `0` - All colors disabled.
- `1` - Basic 16 colors support.
- `2` - ANSI 256 colors support.
- `3` - Truecolor 16 million colors support.
*/
type Level = 0 | 1 | 2 | 3;
interface Options {
/**
Specify the color support for Chalk.
By default, color support is automatically detected based on the environment.
Levels:
- `0` - All colors disabled.
- `1` - Basic 16 colors support.
- `2` - ANSI 256 colors support.
- `3` - Truecolor 16 million colors support.
*/
level?: Level;
}
/**
Return a new Chalk instance.
*/
type Instance = new (options?: Options) => Chalk;
/**
Detect whether the terminal supports color.
*/
interface ColorSupport {
/**
The color level used by Chalk.
*/
level: Level;
/**
Return whether Chalk supports basic 16 colors.
*/
hasBasic: boolean;
/**
Return whether Chalk supports ANSI 256 colors.
*/
has256: boolean;
/**
Return whether Chalk supports Truecolor 16 million colors.
*/
has16m: boolean;
}
interface ChalkFunction {
/**
Use a template string.
@remarks Template literals are unsupported for nested calls (see [issue #341](https://github.com/chalk/chalk/issues/341))
@example
```
import chalk = require('chalk');
log(chalk`
CPU: {red ${cpu.totalPercent}%}
RAM: {green ${ram.used / ram.total * 100}%}
DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
`);
```
@example
```
import chalk = require('chalk');
log(chalk.red.bgBlack`2 + 3 = {bold ${2 + 3}}`)
```
*/
(text: TemplateStringsArray, ...placeholders: unknown[]): string;
(...text: unknown[]): string;
}
interface Chalk extends ChalkFunction {
/**
Return a new Chalk instance.
*/
Instance: Instance;
/**
The color support for Chalk.
By default, color support is automatically detected based on the environment.
Levels:
- `0` - All colors disabled.
- `1` - Basic 16 colors support.
- `2` - ANSI 256 colors support.
- `3` - Truecolor 16 million colors support.
*/
level: Level;
/**
Use HEX value to set text color.
@param color - Hexadecimal value representing the desired color.
@example
```
import chalk = require('chalk');
chalk.hex('#DEADED');
```
*/
hex(color: string): Chalk;
/**
Use keyword color value to set text color.
@param color - Keyword value representing the desired color.
@example
```
import chalk = require('chalk');
chalk.keyword('orange');
```
*/
keyword(color: string): Chalk;
/**
Use RGB values to set text color.
*/
rgb(red: number, green: number, blue: number): Chalk;
/**
Use HSL values to set text color.
*/
hsl(hue: number, saturation: number, lightness: number): Chalk;
/**
Use HSV values to set text color.
*/
hsv(hue: number, saturation: number, value: number): Chalk;
/**
Use HWB values to set text color.
*/
hwb(hue: number, whiteness: number, blackness: number): Chalk;
/**
Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set text color.
30 <= code && code < 38 || 90 <= code && code < 98
For example, 31 for red, 91 for redBright.
*/
ansi(code: number): Chalk;
/**
Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color.
*/
ansi256(index: number): Chalk;
/**
Use HEX value to set background color.
@param color - Hexadecimal value representing the desired color.
@example
```
import chalk = require('chalk');
chalk.bgHex('#DEADED');
```
*/
bgHex(color: string): Chalk;
/**
Use keyword color value to set background color.
@param color - Keyword value representing the desired color.
@example
```
import chalk = require('chalk');
chalk.bgKeyword('orange');
```
*/
bgKeyword(color: string): Chalk;
/**
Use RGB values to set background color.
*/
bgRgb(red: number, green: number, blue: number): Chalk;
/**
Use HSL values to set background color.
*/
bgHsl(hue: number, saturation: number, lightness: number): Chalk;
/**
Use HSV values to set background color.
*/
bgHsv(hue: number, saturation: number, value: number): Chalk;
/**
Use HWB values to set background color.
*/
bgHwb(hue: number, whiteness: number, blackness: number): Chalk;
/**
Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set background color.
30 <= code && code < 38 || 90 <= code && code < 98
For example, 31 for red, 91 for redBright.
Use the foreground code, not the background code (for example, not 41, nor 101).
*/
bgAnsi(code: number): Chalk;
/**
Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color.
*/
bgAnsi256(index: number): Chalk;
/**
Modifier: Resets the current color chain.
*/
readonly reset: Chalk;
/**
Modifier: Make text bold.
*/
readonly bold: Chalk;
/**
Modifier: Emitting only a small amount of light.
*/
readonly dim: Chalk;
/**
Modifier: Make text italic. (Not widely supported)
*/
readonly italic: Chalk;
/**
Modifier: Make text underline. (Not widely supported)
*/
readonly underline: Chalk;
/**
Modifier: Inverse background and foreground colors.
*/
readonly inverse: Chalk;
/**
Modifier: Prints the text, but makes it invisible.
*/
readonly hidden: Chalk;
/**
Modifier: Puts a horizontal line through the center of the text. (Not widely supported)
*/
readonly strikethrough: Chalk;
/**
Modifier: Prints the text only when Chalk has a color support level > 0.
Can be useful for things that are purely cosmetic.
*/
readonly visible: Chalk;
readonly black: Chalk;
readonly red: Chalk;
readonly green: Chalk;
readonly yellow: Chalk;
readonly blue: Chalk;
readonly magenta: Chalk;
readonly cyan: Chalk;
readonly white: Chalk;
/*
Alias for `blackBright`.
*/
readonly gray: Chalk;
/*
Alias for `blackBright`.
*/
readonly grey: Chalk;
readonly blackBright: Chalk;
readonly redBright: Chalk;
readonly greenBright: Chalk;
readonly yellowBright: Chalk;
readonly blueBright: Chalk;
readonly magentaBright: Chalk;
readonly cyanBright: Chalk;
readonly whiteBright: Chalk;
readonly bgBlack: Chalk;
readonly bgRed: Chalk;
readonly bgGreen: Chalk;
readonly bgYellow: Chalk;
readonly bgBlue: Chalk;
readonly bgMagenta: Chalk;
readonly bgCyan: Chalk;
readonly bgWhite: Chalk;
/*
Alias for `bgBlackBright`.
*/
readonly bgGray: Chalk;
/*
Alias for `bgBlackBright`.
*/
readonly bgGrey: Chalk;
readonly bgBlackBright: Chalk;
readonly bgRedBright: Chalk;
readonly bgGreenBright: Chalk;
readonly bgYellowBright: Chalk;
readonly bgBlueBright: Chalk;
readonly bgMagentaBright: Chalk;
readonly bgCyanBright: Chalk;
readonly bgWhiteBright: Chalk;
}
}
/**
Main Chalk object that allows to chain styles together.
Call the last one as a method with a string argument.
Order doesn't matter, and later styles take precedent in case of a conflict.
This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
*/
declare const chalk: chalk.Chalk & chalk.ChalkFunction & {
supportsColor: chalk.ColorSupport | false;
Level: chalk.Level;
Color: Color;
ForegroundColor: ForegroundColor;
BackgroundColor: BackgroundColor;
Modifiers: Modifiers;
stderr: chalk.Chalk & {supportsColor: chalk.ColorSupport | false};
};
export = chalk;

9
node_modules/gulp-cli/node_modules/chalk/license generated vendored Normal file
View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

68
node_modules/gulp-cli/node_modules/chalk/package.json generated vendored Normal file
View File

@@ -0,0 +1,68 @@
{
"name": "chalk",
"version": "4.1.2",
"description": "Terminal string styling done right",
"license": "MIT",
"repository": "chalk/chalk",
"funding": "https://github.com/chalk/chalk?sponsor=1",
"main": "source",
"engines": {
"node": ">=10"
},
"scripts": {
"test": "xo && nyc ava && tsd",
"bench": "matcha benchmark.js"
},
"files": [
"source",
"index.d.ts"
],
"keywords": [
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"str",
"ansi",
"style",
"styles",
"tty",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"dependencies": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
},
"devDependencies": {
"ava": "^2.4.0",
"coveralls": "^3.0.7",
"execa": "^4.0.0",
"import-fresh": "^3.1.0",
"matcha": "^0.7.0",
"nyc": "^15.0.0",
"resolve-from": "^5.0.0",
"tsd": "^0.7.4",
"xo": "^0.28.2"
},
"xo": {
"rules": {
"unicorn/prefer-string-slice": "off",
"unicorn/prefer-includes": "off",
"@typescript-eslint/member-ordering": "off",
"no-redeclare": "off",
"unicorn/string-content": "off",
"unicorn/better-regex": "off"
}
}
}

341
node_modules/gulp-cli/node_modules/chalk/readme.md generated vendored Normal file
View File

@@ -0,0 +1,341 @@
<h1 align="center">
<br>
<br>
<img width="320" src="media/logo.svg" alt="Chalk">
<br>
<br>
<br>
</h1>
> Terminal string styling done right
[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![npm dependents](https://badgen.net/npm/dependents/chalk)](https://www.npmjs.com/package/chalk?activeTab=dependents) [![Downloads](https://badgen.net/npm/dt/chalk)](https://www.npmjs.com/package/chalk) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) ![TypeScript-ready](https://img.shields.io/npm/types/chalk.svg) [![run on repl.it](https://repl.it/badge/github/chalk/chalk)](https://repl.it/github/chalk/chalk)
<img src="https://cdn.jsdelivr.net/gh/chalk/ansi-styles@8261697c95bf34b6c7767e2cbe9941a851d59385/screenshot.svg" width="900">
<br>
---
<div align="center">
<p>
<p>
<sup>
Sindre Sorhus' open source work is supported by the community on <a href="https://github.com/sponsors/sindresorhus">GitHub Sponsors</a> and <a href="https://stakes.social/0x44d871aebF0126Bf646753E2C976Aa7e68A66c15">Dev</a>
</sup>
</p>
<sup>Special thanks to:</sup>
<br>
<br>
<a href="https://standardresume.co/tech">
<img src="https://sindresorhus.com/assets/thanks/standard-resume-logo.svg" width="160"/>
</a>
<br>
<br>
<a href="https://retool.com/?utm_campaign=sindresorhus">
<img src="https://sindresorhus.com/assets/thanks/retool-logo.svg" width="230"/>
</a>
<br>
<br>
<a href="https://doppler.com/?utm_campaign=github_repo&utm_medium=referral&utm_content=chalk&utm_source=github">
<div>
<img src="https://dashboard.doppler.com/imgs/logo-long.svg" width="240" alt="Doppler">
</div>
<b>All your environment variables, in one place</b>
<div>
<span>Stop struggling with scattered API keys, hacking together home-brewed tools,</span>
<br>
<span>and avoiding access controls. Keep your team and servers in sync with Doppler.</span>
</div>
</a>
<br>
<a href="https://uibakery.io/?utm_source=chalk&utm_medium=sponsor&utm_campaign=github">
<div>
<img src="https://sindresorhus.com/assets/thanks/uibakery-logo.jpg" width="270" alt="UI Bakery">
</div>
</a>
</p>
</div>
---
<br>
## Highlights
- Expressive API
- Highly performant
- Ability to nest styles
- [256/Truecolor color support](#256-and-truecolor-color-support)
- Auto-detects color support
- Doesn't extend `String.prototype`
- Clean and focused
- Actively maintained
- [Used by ~50,000 packages](https://www.npmjs.com/browse/depended/chalk) as of January 1, 2020
## Install
```console
$ npm install chalk
```
## Usage
```js
const chalk = require('chalk');
console.log(chalk.blue('Hello world!'));
```
Chalk comes with an easy to use composable API where you just chain and nest the styles you want.
```js
const chalk = require('chalk');
const log = console.log;
// Combine styled and normal strings
log(chalk.blue('Hello') + ' World' + chalk.red('!'));
// Compose multiple styles using the chainable API
log(chalk.blue.bgRed.bold('Hello world!'));
// Pass in multiple arguments
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
// Nest styles
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
// Nest styles of the same type even (color, underline, background)
log(chalk.green(
'I am a green line ' +
chalk.blue.underline.bold('with a blue substring') +
' that becomes green again!'
));
// ES2015 template literal
log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);
// ES2015 tagged template literal
log(chalk`
CPU: {red ${cpu.totalPercent}%}
RAM: {green ${ram.used / ram.total * 100}%}
DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
`);
// Use RGB colors in terminal emulators that support it.
log(chalk.keyword('orange')('Yay for orange colored text!'));
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
log(chalk.hex('#DEADED').bold('Bold gray!'));
```
Easily define your own themes:
```js
const chalk = require('chalk');
const error = chalk.bold.red;
const warning = chalk.keyword('orange');
console.log(error('Error!'));
console.log(warning('Warning!'));
```
Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args):
```js
const name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
//=> 'Hello Sindre'
```
## API
### chalk.`<style>[.<style>...](string, [string...])`
Example: `chalk.red.bold.underline('Hello', 'world');`
Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
Multiple arguments will be separated by space.
### chalk.level
Specifies the level of color support.
Color support is automatically detected, but you can override it by setting the `level` property. You should however only do this in your own code as it applies globally to all Chalk consumers.
If you need to change this in a reusable module, create a new instance:
```js
const ctx = new chalk.Instance({level: 0});
```
| Level | Description |
| :---: | :--- |
| `0` | All colors disabled |
| `1` | Basic color support (16 colors) |
| `2` | 256 color support |
| `3` | Truecolor support (16 million colors) |
### chalk.supportsColor
Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks.
Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.
### chalk.stderr and chalk.stderr.supportsColor
`chalk.stderr` contains a separate instance configured with color support detected for `stderr` stream instead of `stdout`. Override rules from `chalk.supportsColor` apply to this too. `chalk.stderr.supportsColor` is exposed for convenience.
## Styles
### Modifiers
- `reset` - Resets the current color chain.
- `bold` - Make text bold.
- `dim` - Emitting only a small amount of light.
- `italic` - Make text italic. *(Not widely supported)*
- `underline` - Make text underline. *(Not widely supported)*
- `inverse`- Inverse background and foreground colors.
- `hidden` - Prints the text, but makes it invisible.
- `strikethrough` - Puts a horizontal line through the center of the text. *(Not widely supported)*
- `visible`- Prints the text only when Chalk has a color level > 0. Can be useful for things that are purely cosmetic.
### Colors
- `black`
- `red`
- `green`
- `yellow`
- `blue`
- `magenta`
- `cyan`
- `white`
- `blackBright` (alias: `gray`, `grey`)
- `redBright`
- `greenBright`
- `yellowBright`
- `blueBright`
- `magentaBright`
- `cyanBright`
- `whiteBright`
### Background colors
- `bgBlack`
- `bgRed`
- `bgGreen`
- `bgYellow`
- `bgBlue`
- `bgMagenta`
- `bgCyan`
- `bgWhite`
- `bgBlackBright` (alias: `bgGray`, `bgGrey`)
- `bgRedBright`
- `bgGreenBright`
- `bgYellowBright`
- `bgBlueBright`
- `bgMagentaBright`
- `bgCyanBright`
- `bgWhiteBright`
## Tagged template literal
Chalk can be used as a [tagged template literal](https://exploringjs.com/es6/ch_template-literals.html#_tagged-template-literals).
```js
const chalk = require('chalk');
const miles = 18;
const calculateFeet = miles => miles * 5280;
console.log(chalk`
There are {bold 5280 feet} in a mile.
In {bold ${miles} miles}, there are {green.bold ${calculateFeet(miles)} feet}.
`);
```
Blocks are delimited by an opening curly brace (`{`), a style, some content, and a closing curly brace (`}`).
Template styles are chained exactly like normal Chalk styles. The following three statements are equivalent:
```js
console.log(chalk.bold.rgb(10, 100, 200)('Hello!'));
console.log(chalk.bold.rgb(10, 100, 200)`Hello!`);
console.log(chalk`{bold.rgb(10,100,200) Hello!}`);
```
Note that function styles (`rgb()`, `hsl()`, `keyword()`, etc.) may not contain spaces between parameters.
All interpolated values (`` chalk`${foo}` ``) are converted to strings via the `.toString()` method. All curly braces (`{` and `}`) in interpolated value strings are escaped.
## 256 and Truecolor color support
Chalk supports 256 colors and [Truecolor](https://gist.github.com/XVilka/8346728) (16 million colors) on supported terminal apps.
Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying `{level: n}` as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red).
Examples:
- `chalk.hex('#DEADED').underline('Hello, world!')`
- `chalk.keyword('orange')('Some orange text')`
- `chalk.rgb(15, 100, 204).inverse('Hello!')`
Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `keyword` for foreground colors and `bgKeyword` for background colors).
- `chalk.bgHex('#DEADED').underline('Hello, world!')`
- `chalk.bgKeyword('orange')('Some orange text')`
- `chalk.bgRgb(15, 100, 204).inverse('Hello!')`
The following color models can be used:
- [`rgb`](https://en.wikipedia.org/wiki/RGB_color_model) - Example: `chalk.rgb(255, 136, 0).bold('Orange!')`
- [`hex`](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) - Example: `chalk.hex('#FF8800').bold('Orange!')`
- [`keyword`](https://www.w3.org/wiki/CSS/Properties/color/keywords) (CSS keywords) - Example: `chalk.keyword('orange').bold('Orange!')`
- [`hsl`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 100, 50).bold('Orange!')`
- [`hsv`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsv(32, 100, 100).bold('Orange!')`
- [`hwb`](https://en.wikipedia.org/wiki/HWB_color_model) - Example: `chalk.hwb(32, 0, 50).bold('Orange!')`
- [`ansi`](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) - Example: `chalk.ansi(31).bgAnsi(93)('red on yellowBright')`
- [`ansi256`](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) - Example: `chalk.bgAnsi256(194)('Honeydew, more or less')`
## Windows
If you're on Windows, do yourself a favor and use [Windows Terminal](https://github.com/microsoft/terminal) instead of `cmd.exe`.
## Origin story
[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68) and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative.
## chalk for enterprise
Available as part of the Tidelift Subscription.
The maintainers of chalk and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-chalk?utm_source=npm-chalk&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
## Related
- [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
- [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal
- [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color
- [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes
- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Strip ANSI escape codes from a stream
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
- [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes
- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes
- [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models
- [chalk-animation](https://github.com/bokub/chalk-animation) - Animate strings in the terminal
- [gradient-string](https://github.com/bokub/gradient-string) - Apply color gradients to strings
- [chalk-pipe](https://github.com/LitoMore/chalk-pipe) - Create chalk style schemes with simpler style strings
- [terminal-link](https://github.com/sindresorhus/terminal-link) - Create clickable links in the terminal
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)

View File

@@ -0,0 +1,229 @@
'use strict';
const ansiStyles = require('ansi-styles');
const {stdout: stdoutColor, stderr: stderrColor} = require('supports-color');
const {
stringReplaceAll,
stringEncaseCRLFWithFirstIndex
} = require('./util');
const {isArray} = Array;
// `supportsColor.level` → `ansiStyles.color[name]` mapping
const levelMapping = [
'ansi',
'ansi',
'ansi256',
'ansi16m'
];
const styles = Object.create(null);
const applyOptions = (object, options = {}) => {
if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
throw new Error('The `level` option should be an integer from 0 to 3');
}
// Detect level if not set manually
const colorLevel = stdoutColor ? stdoutColor.level : 0;
object.level = options.level === undefined ? colorLevel : options.level;
};
class ChalkClass {
constructor(options) {
// eslint-disable-next-line no-constructor-return
return chalkFactory(options);
}
}
const chalkFactory = options => {
const chalk = {};
applyOptions(chalk, options);
chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
Object.setPrototypeOf(chalk, Chalk.prototype);
Object.setPrototypeOf(chalk.template, chalk);
chalk.template.constructor = () => {
throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
};
chalk.template.Instance = ChalkClass;
return chalk.template;
};
function Chalk(options) {
return chalkFactory(options);
}
for (const [styleName, style] of Object.entries(ansiStyles)) {
styles[styleName] = {
get() {
const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
Object.defineProperty(this, styleName, {value: builder});
return builder;
}
};
}
styles.visible = {
get() {
const builder = createBuilder(this, this._styler, true);
Object.defineProperty(this, 'visible', {value: builder});
return builder;
}
};
const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
for (const model of usedModels) {
styles[model] = {
get() {
const {level} = this;
return function (...arguments_) {
const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
return createBuilder(this, styler, this._isEmpty);
};
}
};
}
for (const model of usedModels) {
const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
styles[bgModel] = {
get() {
const {level} = this;
return function (...arguments_) {
const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
return createBuilder(this, styler, this._isEmpty);
};
}
};
}
const proto = Object.defineProperties(() => {}, {
...styles,
level: {
enumerable: true,
get() {
return this._generator.level;
},
set(level) {
this._generator.level = level;
}
}
});
const createStyler = (open, close, parent) => {
let openAll;
let closeAll;
if (parent === undefined) {
openAll = open;
closeAll = close;
} else {
openAll = parent.openAll + open;
closeAll = close + parent.closeAll;
}
return {
open,
close,
openAll,
closeAll,
parent
};
};
const createBuilder = (self, _styler, _isEmpty) => {
const builder = (...arguments_) => {
if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) {
// Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
return applyStyle(builder, chalkTag(builder, ...arguments_));
}
// Single argument is hot path, implicit coercion is faster than anything
// eslint-disable-next-line no-implicit-coercion
return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
};
// We alter the prototype because we must return a function, but there is
// no way to create a function with a different prototype
Object.setPrototypeOf(builder, proto);
builder._generator = self;
builder._styler = _styler;
builder._isEmpty = _isEmpty;
return builder;
};
const applyStyle = (self, string) => {
if (self.level <= 0 || !string) {
return self._isEmpty ? '' : string;
}
let styler = self._styler;
if (styler === undefined) {
return string;
}
const {openAll, closeAll} = styler;
if (string.indexOf('\u001B') !== -1) {
while (styler !== undefined) {
// Replace any instances already present with a re-opening code
// otherwise only the part of the string until said closing code
// will be colored, and the rest will simply be 'plain'.
string = stringReplaceAll(string, styler.close, styler.open);
styler = styler.parent;
}
}
// We can move both next actions out of loop, because remaining actions in loop won't have
// any/visible effect on parts we add here. Close the styling before a linebreak and reopen
// after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
const lfIndex = string.indexOf('\n');
if (lfIndex !== -1) {
string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
}
return openAll + string + closeAll;
};
let template;
const chalkTag = (chalk, ...strings) => {
const [firstString] = strings;
if (!isArray(firstString) || !isArray(firstString.raw)) {
// If chalk() was called by itself or with a string,
// return the string itself as a string.
return strings.join(' ');
}
const arguments_ = strings.slice(1);
const parts = [firstString.raw[0]];
for (let i = 1; i < firstString.length; i++) {
parts.push(
String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'),
String(firstString.raw[i])
);
}
if (template === undefined) {
template = require('./templates');
}
return template(chalk, parts.join(''));
};
Object.defineProperties(Chalk.prototype, styles);
const chalk = Chalk(); // eslint-disable-line new-cap
chalk.supportsColor = stdoutColor;
chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap
chalk.stderr.supportsColor = stderrColor;
module.exports = chalk;

View File

@@ -0,0 +1,134 @@
'use strict';
const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
const ESCAPES = new Map([
['n', '\n'],
['r', '\r'],
['t', '\t'],
['b', '\b'],
['f', '\f'],
['v', '\v'],
['0', '\0'],
['\\', '\\'],
['e', '\u001B'],
['a', '\u0007']
]);
function unescape(c) {
const u = c[0] === 'u';
const bracket = c[1] === '{';
if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
return String.fromCharCode(parseInt(c.slice(1), 16));
}
if (u && bracket) {
return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
}
return ESCAPES.get(c) || c;
}
function parseArguments(name, arguments_) {
const results = [];
const chunks = arguments_.trim().split(/\s*,\s*/g);
let matches;
for (const chunk of chunks) {
const number = Number(chunk);
if (!Number.isNaN(number)) {
results.push(number);
} else if ((matches = chunk.match(STRING_REGEX))) {
results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character));
} else {
throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
}
}
return results;
}
function parseStyle(style) {
STYLE_REGEX.lastIndex = 0;
const results = [];
let matches;
while ((matches = STYLE_REGEX.exec(style)) !== null) {
const name = matches[1];
if (matches[2]) {
const args = parseArguments(name, matches[2]);
results.push([name].concat(args));
} else {
results.push([name]);
}
}
return results;
}
function buildStyle(chalk, styles) {
const enabled = {};
for (const layer of styles) {
for (const style of layer.styles) {
enabled[style[0]] = layer.inverse ? null : style.slice(1);
}
}
let current = chalk;
for (const [styleName, styles] of Object.entries(enabled)) {
if (!Array.isArray(styles)) {
continue;
}
if (!(styleName in current)) {
throw new Error(`Unknown Chalk style: ${styleName}`);
}
current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
}
return current;
}
module.exports = (chalk, temporary) => {
const styles = [];
const chunks = [];
let chunk = [];
// eslint-disable-next-line max-params
temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
if (escapeCharacter) {
chunk.push(unescape(escapeCharacter));
} else if (style) {
const string = chunk.join('');
chunk = [];
chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
styles.push({inverse, styles: parseStyle(style)});
} else if (close) {
if (styles.length === 0) {
throw new Error('Found extraneous } in Chalk template literal');
}
chunks.push(buildStyle(chalk, styles)(chunk.join('')));
chunk = [];
styles.pop();
} else {
chunk.push(character);
}
});
chunks.push(chunk.join(''));
if (styles.length > 0) {
const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
throw new Error(errMessage);
}
return chunks.join('');
};

View File

@@ -0,0 +1,39 @@
'use strict';
const stringReplaceAll = (string, substring, replacer) => {
let index = string.indexOf(substring);
if (index === -1) {
return string;
}
const substringLength = substring.length;
let endIndex = 0;
let returnValue = '';
do {
returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
endIndex = index + substringLength;
index = string.indexOf(substring, endIndex);
} while (index !== -1);
returnValue += string.substr(endIndex);
return returnValue;
};
const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
let endIndex = 0;
let returnValue = '';
do {
const gotCR = string[index - 1] === '\r';
returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
endIndex = index + 1;
index = string.indexOf('\n', endIndex);
} while (index !== -1);
returnValue += string.substr(endIndex);
return returnValue;
};
module.exports = {
stringReplaceAll,
stringEncaseCRLFWithFirstIndex
};

121
node_modules/gulp-cli/node_modules/cliui/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,121 @@
# Change Log
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
### [7.0.4](https://www.github.com/yargs/cliui/compare/v7.0.3...v7.0.4) (2020-11-08)
### Bug Fixes
* **deno:** import UIOptions from definitions ([#97](https://www.github.com/yargs/cliui/issues/97)) ([f04f343](https://www.github.com/yargs/cliui/commit/f04f3439bc78114c7e90f82ff56f5acf16268ea8))
### [7.0.3](https://www.github.com/yargs/cliui/compare/v7.0.2...v7.0.3) (2020-10-16)
### Bug Fixes
* **exports:** node 13.0 and 13.1 require the dotted object form _with_ a string fallback ([#93](https://www.github.com/yargs/cliui/issues/93)) ([eca16fc](https://www.github.com/yargs/cliui/commit/eca16fc05d26255df3280906c36d7f0e5b05c6e9))
### [7.0.2](https://www.github.com/yargs/cliui/compare/v7.0.1...v7.0.2) (2020-10-14)
### Bug Fixes
* **exports:** node 13.0-13.6 require a string fallback ([#91](https://www.github.com/yargs/cliui/issues/91)) ([b529d7e](https://www.github.com/yargs/cliui/commit/b529d7e432901af1af7848b23ed6cf634497d961))
### [7.0.1](https://www.github.com/yargs/cliui/compare/v7.0.0...v7.0.1) (2020-08-16)
### Bug Fixes
* **build:** main should be build/index.cjs ([dc29a3c](https://www.github.com/yargs/cliui/commit/dc29a3cc617a410aa850e06337b5954b04f2cb4d))
## [7.0.0](https://www.github.com/yargs/cliui/compare/v6.0.0...v7.0.0) (2020-08-16)
### ⚠ BREAKING CHANGES
* tsc/ESM/Deno support (#82)
* modernize deps and build (#80)
### Build System
* modernize deps and build ([#80](https://www.github.com/yargs/cliui/issues/80)) ([339d08d](https://www.github.com/yargs/cliui/commit/339d08dc71b15a3928aeab09042af94db2f43743))
### Code Refactoring
* tsc/ESM/Deno support ([#82](https://www.github.com/yargs/cliui/issues/82)) ([4b777a5](https://www.github.com/yargs/cliui/commit/4b777a5fe01c5d8958c6708695d6aab7dbe5706c))
## [6.0.0](https://www.github.com/yargs/cliui/compare/v5.0.0...v6.0.0) (2019-11-10)
### ⚠ BREAKING CHANGES
* update deps, drop Node 6
### Code Refactoring
* update deps, drop Node 6 ([62056df](https://www.github.com/yargs/cliui/commit/62056df))
## [5.0.0](https://github.com/yargs/cliui/compare/v4.1.0...v5.0.0) (2019-04-10)
### Bug Fixes
* Update wrap-ansi to fix compatibility with latest versions of chalk. ([#60](https://github.com/yargs/cliui/issues/60)) ([7bf79ae](https://github.com/yargs/cliui/commit/7bf79ae))
### BREAKING CHANGES
* Drop support for node < 6.
<a name="4.1.0"></a>
## [4.1.0](https://github.com/yargs/cliui/compare/v4.0.0...v4.1.0) (2018-04-23)
### Features
* add resetOutput method ([#57](https://github.com/yargs/cliui/issues/57)) ([7246902](https://github.com/yargs/cliui/commit/7246902))
<a name="4.0.0"></a>
## [4.0.0](https://github.com/yargs/cliui/compare/v3.2.0...v4.0.0) (2017-12-18)
### Bug Fixes
* downgrades strip-ansi to version 3.0.1 ([#54](https://github.com/yargs/cliui/issues/54)) ([5764c46](https://github.com/yargs/cliui/commit/5764c46))
* set env variable FORCE_COLOR. ([#56](https://github.com/yargs/cliui/issues/56)) ([7350e36](https://github.com/yargs/cliui/commit/7350e36))
### Chores
* drop support for node < 4 ([#53](https://github.com/yargs/cliui/issues/53)) ([b105376](https://github.com/yargs/cliui/commit/b105376))
### Features
* add fallback for window width ([#45](https://github.com/yargs/cliui/issues/45)) ([d064922](https://github.com/yargs/cliui/commit/d064922))
### BREAKING CHANGES
* officially drop support for Node < 4
<a name="3.2.0"></a>
## [3.2.0](https://github.com/yargs/cliui/compare/v3.1.2...v3.2.0) (2016-04-11)
### Bug Fixes
* reduces tarball size ([acc6c33](https://github.com/yargs/cliui/commit/acc6c33))
### Features
* adds standard-version for release management ([ff84e32](https://github.com/yargs/cliui/commit/ff84e32))

14
node_modules/gulp-cli/node_modules/cliui/LICENSE.txt generated vendored Normal file
View File

@@ -0,0 +1,14 @@
Copyright (c) 2015, Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice
appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE
LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

141
node_modules/gulp-cli/node_modules/cliui/README.md generated vendored Normal file
View File

@@ -0,0 +1,141 @@
# cliui
![ci](https://github.com/yargs/cliui/workflows/ci/badge.svg)
[![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui)
[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org)
![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/cliui)
easily create complex multi-column command-line-interfaces.
## Example
```js
const ui = require('cliui')()
ui.div('Usage: $0 [command] [options]')
ui.div({
text: 'Options:',
padding: [2, 0, 1, 0]
})
ui.div(
{
text: "-f, --file",
width: 20,
padding: [0, 4, 0, 4]
},
{
text: "the file to load." +
chalk.green("(if this description is long it wraps).")
,
width: 20
},
{
text: chalk.red("[required]"),
align: 'right'
}
)
console.log(ui.toString())
```
## Deno/ESM Support
As of `v7` `cliui` supports [Deno](https://github.com/denoland/deno) and
[ESM](https://nodejs.org/api/esm.html#esm_ecmascript_modules):
```typescript
import cliui from "https://deno.land/x/cliui/deno.ts";
const ui = cliui({})
ui.div('Usage: $0 [command] [options]')
ui.div({
text: 'Options:',
padding: [2, 0, 1, 0]
})
ui.div({
text: "-f, --file",
width: 20,
padding: [0, 4, 0, 4]
})
console.log(ui.toString())
```
<img width="500" src="screenshot.png">
## Layout DSL
cliui exposes a simple layout DSL:
If you create a single `ui.div`, passing a string rather than an
object:
* `\n`: characters will be interpreted as new rows.
* `\t`: characters will be interpreted as new columns.
* `\s`: characters will be interpreted as padding.
**as an example...**
```js
var ui = require('./')({
width: 60
})
ui.div(
'Usage: node ./bin/foo.js\n' +
' <regex>\t provide a regex\n' +
' <glob>\t provide a glob\t [required]'
)
console.log(ui.toString())
```
**will output:**
```shell
Usage: node ./bin/foo.js
<regex> provide a regex
<glob> provide a glob [required]
```
## Methods
```js
cliui = require('cliui')
```
### cliui({width: integer})
Specify the maximum width of the UI being generated.
If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`.
### cliui({wrap: boolean})
Enable or disable the wrapping of text in a column.
### cliui.div(column, column, column)
Create a row with any number of columns, a column
can either be a string, or an object with the following
options:
* **text:** some text to place in the column.
* **width:** the width of a column.
* **align:** alignment, `right` or `center`.
* **padding:** `[top, right, bottom, left]`.
* **border:** should a border be placed around the div?
### cliui.span(column, column, column)
Similar to `div`, except the next row will be appended without
a new line being created.
### cliui.resetOutput()
Resets the UI elements of the current cliui instance, maintaining the values
set for `width` and `wrap`.

View File

@@ -0,0 +1,302 @@
'use strict';
const align = {
right: alignRight,
center: alignCenter
};
const top = 0;
const right = 1;
const bottom = 2;
const left = 3;
class UI {
constructor(opts) {
var _a;
this.width = opts.width;
this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true;
this.rows = [];
}
span(...args) {
const cols = this.div(...args);
cols.span = true;
}
resetOutput() {
this.rows = [];
}
div(...args) {
if (args.length === 0) {
this.div('');
}
if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') {
return this.applyLayoutDSL(args[0]);
}
const cols = args.map(arg => {
if (typeof arg === 'string') {
return this.colFromString(arg);
}
return arg;
});
this.rows.push(cols);
return cols;
}
shouldApplyLayoutDSL(...args) {
return args.length === 1 && typeof args[0] === 'string' &&
/[\t\n]/.test(args[0]);
}
applyLayoutDSL(str) {
const rows = str.split('\n').map(row => row.split('\t'));
let leftColumnWidth = 0;
// simple heuristic for layout, make sure the
// second column lines up along the left-hand.
// don't allow the first column to take up more
// than 50% of the screen.
rows.forEach(columns => {
if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) {
leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0]));
}
});
// generate a table:
// replacing ' ' with padding calculations.
// using the algorithmically generated width.
rows.forEach(columns => {
this.div(...columns.map((r, i) => {
return {
text: r.trim(),
padding: this.measurePadding(r),
width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined
};
}));
});
return this.rows[this.rows.length - 1];
}
colFromString(text) {
return {
text,
padding: this.measurePadding(text)
};
}
measurePadding(str) {
// measure padding without ansi escape codes
const noAnsi = mixin.stripAnsi(str);
return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
}
toString() {
const lines = [];
this.rows.forEach(row => {
this.rowToString(row, lines);
});
// don't display any lines with the
// hidden flag set.
return lines
.filter(line => !line.hidden)
.map(line => line.text)
.join('\n');
}
rowToString(row, lines) {
this.rasterize(row).forEach((rrow, r) => {
let str = '';
rrow.forEach((col, c) => {
const { width } = row[c]; // the width with padding.
const wrapWidth = this.negatePadding(row[c]); // the width without padding.
let ts = col; // temporary string used during alignment/padding.
if (wrapWidth > mixin.stringWidth(col)) {
ts += ' '.repeat(wrapWidth - mixin.stringWidth(col));
}
// align the string within its column.
if (row[c].align && row[c].align !== 'left' && this.wrap) {
const fn = align[row[c].align];
ts = fn(ts, wrapWidth);
if (mixin.stringWidth(ts) < wrapWidth) {
ts += ' '.repeat((width || 0) - mixin.stringWidth(ts) - 1);
}
}
// apply border and padding to string.
const padding = row[c].padding || [0, 0, 0, 0];
if (padding[left]) {
str += ' '.repeat(padding[left]);
}
str += addBorder(row[c], ts, '| ');
str += ts;
str += addBorder(row[c], ts, ' |');
if (padding[right]) {
str += ' '.repeat(padding[right]);
}
// if prior row is span, try to render the
// current row on the prior line.
if (r === 0 && lines.length > 0) {
str = this.renderInline(str, lines[lines.length - 1]);
}
});
// remove trailing whitespace.
lines.push({
text: str.replace(/ +$/, ''),
span: row.span
});
});
return lines;
}
// if the full 'source' can render in
// the target line, do so.
renderInline(source, previousLine) {
const match = source.match(/^ */);
const leadingWhitespace = match ? match[0].length : 0;
const target = previousLine.text;
const targetTextWidth = mixin.stringWidth(target.trimRight());
if (!previousLine.span) {
return source;
}
// if we're not applying wrapping logic,
// just always append to the span.
if (!this.wrap) {
previousLine.hidden = true;
return target + source;
}
if (leadingWhitespace < targetTextWidth) {
return source;
}
previousLine.hidden = true;
return target.trimRight() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimLeft();
}
rasterize(row) {
const rrows = [];
const widths = this.columnWidths(row);
let wrapped;
// word wrap all columns, and create
// a data-structure that is easy to rasterize.
row.forEach((col, c) => {
// leave room for left and right padding.
col.width = widths[c];
if (this.wrap) {
wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n');
}
else {
wrapped = col.text.split('\n');
}
if (col.border) {
wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.');
wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'");
}
// add top and bottom padding.
if (col.padding) {
wrapped.unshift(...new Array(col.padding[top] || 0).fill(''));
wrapped.push(...new Array(col.padding[bottom] || 0).fill(''));
}
wrapped.forEach((str, r) => {
if (!rrows[r]) {
rrows.push([]);
}
const rrow = rrows[r];
for (let i = 0; i < c; i++) {
if (rrow[i] === undefined) {
rrow.push('');
}
}
rrow.push(str);
});
});
return rrows;
}
negatePadding(col) {
let wrapWidth = col.width || 0;
if (col.padding) {
wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
}
if (col.border) {
wrapWidth -= 4;
}
return wrapWidth;
}
columnWidths(row) {
if (!this.wrap) {
return row.map(col => {
return col.width || mixin.stringWidth(col.text);
});
}
let unset = row.length;
let remainingWidth = this.width;
// column widths can be set in config.
const widths = row.map(col => {
if (col.width) {
unset--;
remainingWidth -= col.width;
return col.width;
}
return undefined;
});
// any unset widths should be calculated.
const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
return widths.map((w, i) => {
if (w === undefined) {
return Math.max(unsetWidth, _minWidth(row[i]));
}
return w;
});
}
}
function addBorder(col, ts, style) {
if (col.border) {
if (/[.']-+[.']/.test(ts)) {
return '';
}
if (ts.trim().length !== 0) {
return style;
}
return ' ';
}
return '';
}
// calculates the minimum width of
// a column, based on padding preferences.
function _minWidth(col) {
const padding = col.padding || [];
const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0);
if (col.border) {
return minWidth + 4;
}
return minWidth;
}
function getWindowWidth() {
/* istanbul ignore next: depends on terminal */
if (typeof process === 'object' && process.stdout && process.stdout.columns) {
return process.stdout.columns;
}
return 80;
}
function alignRight(str, width) {
str = str.trim();
const strWidth = mixin.stringWidth(str);
if (strWidth < width) {
return ' '.repeat(width - strWidth) + str;
}
return str;
}
function alignCenter(str, width) {
str = str.trim();
const strWidth = mixin.stringWidth(str);
/* istanbul ignore next */
if (strWidth >= width) {
return str;
}
return ' '.repeat((width - strWidth) >> 1) + str;
}
let mixin;
function cliui(opts, _mixin) {
mixin = _mixin;
return new UI({
width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
});
}
// Bootstrap cliui with CommonJS dependencies:
const stringWidth = require('string-width');
const stripAnsi = require('strip-ansi');
const wrap = require('wrap-ansi');
function ui(opts) {
return cliui(opts, {
stringWidth,
stripAnsi,
wrap
});
}
module.exports = ui;

View File

@@ -0,0 +1,287 @@
'use strict';
const align = {
right: alignRight,
center: alignCenter
};
const top = 0;
const right = 1;
const bottom = 2;
const left = 3;
export class UI {
constructor(opts) {
var _a;
this.width = opts.width;
this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true;
this.rows = [];
}
span(...args) {
const cols = this.div(...args);
cols.span = true;
}
resetOutput() {
this.rows = [];
}
div(...args) {
if (args.length === 0) {
this.div('');
}
if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') {
return this.applyLayoutDSL(args[0]);
}
const cols = args.map(arg => {
if (typeof arg === 'string') {
return this.colFromString(arg);
}
return arg;
});
this.rows.push(cols);
return cols;
}
shouldApplyLayoutDSL(...args) {
return args.length === 1 && typeof args[0] === 'string' &&
/[\t\n]/.test(args[0]);
}
applyLayoutDSL(str) {
const rows = str.split('\n').map(row => row.split('\t'));
let leftColumnWidth = 0;
// simple heuristic for layout, make sure the
// second column lines up along the left-hand.
// don't allow the first column to take up more
// than 50% of the screen.
rows.forEach(columns => {
if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) {
leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0]));
}
});
// generate a table:
// replacing ' ' with padding calculations.
// using the algorithmically generated width.
rows.forEach(columns => {
this.div(...columns.map((r, i) => {
return {
text: r.trim(),
padding: this.measurePadding(r),
width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined
};
}));
});
return this.rows[this.rows.length - 1];
}
colFromString(text) {
return {
text,
padding: this.measurePadding(text)
};
}
measurePadding(str) {
// measure padding without ansi escape codes
const noAnsi = mixin.stripAnsi(str);
return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
}
toString() {
const lines = [];
this.rows.forEach(row => {
this.rowToString(row, lines);
});
// don't display any lines with the
// hidden flag set.
return lines
.filter(line => !line.hidden)
.map(line => line.text)
.join('\n');
}
rowToString(row, lines) {
this.rasterize(row).forEach((rrow, r) => {
let str = '';
rrow.forEach((col, c) => {
const { width } = row[c]; // the width with padding.
const wrapWidth = this.negatePadding(row[c]); // the width without padding.
let ts = col; // temporary string used during alignment/padding.
if (wrapWidth > mixin.stringWidth(col)) {
ts += ' '.repeat(wrapWidth - mixin.stringWidth(col));
}
// align the string within its column.
if (row[c].align && row[c].align !== 'left' && this.wrap) {
const fn = align[row[c].align];
ts = fn(ts, wrapWidth);
if (mixin.stringWidth(ts) < wrapWidth) {
ts += ' '.repeat((width || 0) - mixin.stringWidth(ts) - 1);
}
}
// apply border and padding to string.
const padding = row[c].padding || [0, 0, 0, 0];
if (padding[left]) {
str += ' '.repeat(padding[left]);
}
str += addBorder(row[c], ts, '| ');
str += ts;
str += addBorder(row[c], ts, ' |');
if (padding[right]) {
str += ' '.repeat(padding[right]);
}
// if prior row is span, try to render the
// current row on the prior line.
if (r === 0 && lines.length > 0) {
str = this.renderInline(str, lines[lines.length - 1]);
}
});
// remove trailing whitespace.
lines.push({
text: str.replace(/ +$/, ''),
span: row.span
});
});
return lines;
}
// if the full 'source' can render in
// the target line, do so.
renderInline(source, previousLine) {
const match = source.match(/^ */);
const leadingWhitespace = match ? match[0].length : 0;
const target = previousLine.text;
const targetTextWidth = mixin.stringWidth(target.trimRight());
if (!previousLine.span) {
return source;
}
// if we're not applying wrapping logic,
// just always append to the span.
if (!this.wrap) {
previousLine.hidden = true;
return target + source;
}
if (leadingWhitespace < targetTextWidth) {
return source;
}
previousLine.hidden = true;
return target.trimRight() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimLeft();
}
rasterize(row) {
const rrows = [];
const widths = this.columnWidths(row);
let wrapped;
// word wrap all columns, and create
// a data-structure that is easy to rasterize.
row.forEach((col, c) => {
// leave room for left and right padding.
col.width = widths[c];
if (this.wrap) {
wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n');
}
else {
wrapped = col.text.split('\n');
}
if (col.border) {
wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.');
wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'");
}
// add top and bottom padding.
if (col.padding) {
wrapped.unshift(...new Array(col.padding[top] || 0).fill(''));
wrapped.push(...new Array(col.padding[bottom] || 0).fill(''));
}
wrapped.forEach((str, r) => {
if (!rrows[r]) {
rrows.push([]);
}
const rrow = rrows[r];
for (let i = 0; i < c; i++) {
if (rrow[i] === undefined) {
rrow.push('');
}
}
rrow.push(str);
});
});
return rrows;
}
negatePadding(col) {
let wrapWidth = col.width || 0;
if (col.padding) {
wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
}
if (col.border) {
wrapWidth -= 4;
}
return wrapWidth;
}
columnWidths(row) {
if (!this.wrap) {
return row.map(col => {
return col.width || mixin.stringWidth(col.text);
});
}
let unset = row.length;
let remainingWidth = this.width;
// column widths can be set in config.
const widths = row.map(col => {
if (col.width) {
unset--;
remainingWidth -= col.width;
return col.width;
}
return undefined;
});
// any unset widths should be calculated.
const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
return widths.map((w, i) => {
if (w === undefined) {
return Math.max(unsetWidth, _minWidth(row[i]));
}
return w;
});
}
}
function addBorder(col, ts, style) {
if (col.border) {
if (/[.']-+[.']/.test(ts)) {
return '';
}
if (ts.trim().length !== 0) {
return style;
}
return ' ';
}
return '';
}
// calculates the minimum width of
// a column, based on padding preferences.
function _minWidth(col) {
const padding = col.padding || [];
const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0);
if (col.border) {
return minWidth + 4;
}
return minWidth;
}
function getWindowWidth() {
/* istanbul ignore next: depends on terminal */
if (typeof process === 'object' && process.stdout && process.stdout.columns) {
return process.stdout.columns;
}
return 80;
}
function alignRight(str, width) {
str = str.trim();
const strWidth = mixin.stringWidth(str);
if (strWidth < width) {
return ' '.repeat(width - strWidth) + str;
}
return str;
}
function alignCenter(str, width) {
str = str.trim();
const strWidth = mixin.stringWidth(str);
/* istanbul ignore next */
if (strWidth >= width) {
return str;
}
return ' '.repeat((width - strWidth) >> 1) + str;
}
let mixin;
export function cliui(opts, _mixin) {
mixin = _mixin;
return new UI({
width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
});
}

View File

@@ -0,0 +1,27 @@
// Minimal replacement for ansi string helpers "wrap-ansi" and "strip-ansi".
// to facilitate ESM and Deno modules.
// TODO: look at porting https://www.npmjs.com/package/wrap-ansi to ESM.
// The npm application
// Copyright (c) npm, Inc. and Contributors
// Licensed on the terms of The Artistic License 2.0
// See: https://github.com/npm/cli/blob/4c65cd952bc8627811735bea76b9b110cc4fc80e/lib/utils/ansi-trim.js
const ansi = new RegExp('\x1b(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|' +
'\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)', 'g');
export function stripAnsi(str) {
return str.replace(ansi, '');
}
export function wrap(str, width) {
const [start, end] = str.match(ansi) || ['', ''];
str = stripAnsi(str);
let wrapped = '';
for (let i = 0; i < str.length; i++) {
if (i !== 0 && (i % width) === 0) {
wrapped += '\n';
}
wrapped += str.charAt(i);
}
if (start && end) {
wrapped = `${start}${wrapped}${end}`;
}
return wrapped;
}

13
node_modules/gulp-cli/node_modules/cliui/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,13 @@
// Bootstrap cliui with CommonJS dependencies:
import { cliui } from './build/lib/index.js'
import { wrap, stripAnsi } from './build/lib/string-utils.js'
export default function ui (opts) {
return cliui(opts, {
stringWidth: (str) => {
return [...str].length
},
stripAnsi,
wrap
})
}

83
node_modules/gulp-cli/node_modules/cliui/package.json generated vendored Normal file
View File

@@ -0,0 +1,83 @@
{
"name": "cliui",
"version": "7.0.4",
"description": "easily create complex multi-column command-line-interfaces",
"main": "build/index.cjs",
"exports": {
".": [
{
"import": "./index.mjs",
"require": "./build/index.cjs"
},
"./build/index.cjs"
]
},
"type": "module",
"module": "./index.mjs",
"scripts": {
"check": "standardx '**/*.ts' && standardx '**/*.js' && standardx '**/*.cjs'",
"fix": "standardx --fix '**/*.ts' && standardx --fix '**/*.js' && standardx --fix '**/*.cjs'",
"pretest": "rimraf build && tsc -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs",
"test": "c8 mocha ./test/*.cjs",
"test:esm": "c8 mocha ./test/esm/cliui-test.mjs",
"postest": "check",
"coverage": "c8 report --check-coverage",
"precompile": "rimraf build",
"compile": "tsc",
"postcompile": "npm run build:cjs",
"build:cjs": "rollup -c",
"prepare": "npm run compile"
},
"repository": "yargs/cliui",
"standard": {
"ignore": [
"**/example/**"
],
"globals": [
"it"
]
},
"keywords": [
"cli",
"command-line",
"layout",
"design",
"console",
"wrap",
"table"
],
"author": "Ben Coe <ben@npmjs.com>",
"license": "ISC",
"dependencies": {
"string-width": "^4.2.0",
"strip-ansi": "^6.0.0",
"wrap-ansi": "^7.0.0"
},
"devDependencies": {
"@types/node": "^14.0.27",
"@typescript-eslint/eslint-plugin": "^4.0.0",
"@typescript-eslint/parser": "^4.0.0",
"@wessberg/rollup-plugin-ts": "^1.3.2",
"c8": "^7.3.0",
"chai": "^4.2.0",
"chalk": "^4.1.0",
"cross-env": "^7.0.2",
"eslint": "^7.6.0",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-node": "^11.1.0",
"gts": "^3.0.0",
"mocha": "^8.1.1",
"rimraf": "^3.0.2",
"rollup": "^2.23.1",
"standardx": "^7.0.0",
"typescript": "^4.0.0"
},
"files": [
"build",
"index.mjs",
"!*.d.ts"
],
"engine": {
"node": ">=10"
}
}

View File

@@ -0,0 +1,263 @@
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
### [20.2.9](https://www.github.com/yargs/yargs-parser/compare/yargs-parser-v20.2.8...yargs-parser-v20.2.9) (2021-06-20)
### Bug Fixes
* **build:** fixed automated release pipeline ([1fe9135](https://www.github.com/yargs/yargs-parser/commit/1fe9135884790a083615419b2861683e2597dac3))
### [20.2.8](https://www.github.com/yargs/yargs-parser/compare/yargs-parser-v20.2.7...yargs-parser-v20.2.8) (2021-06-20)
### Bug Fixes
* **locale:** Turkish camelize and decamelize issues with toLocaleLowerCase/toLocaleUpperCase ([2617303](https://www.github.com/yargs/yargs-parser/commit/261730383e02448562f737b94bbd1f164aed5143))
* **perf:** address slow parse when using unknown-options-as-args ([#394](https://www.github.com/yargs/yargs-parser/issues/394)) ([441f059](https://www.github.com/yargs/yargs-parser/commit/441f059d585d446551068ad213db79ac91daf83a))
* **string-utils:** detect [0,1] ranged values as numbers ([#388](https://www.github.com/yargs/yargs-parser/issues/388)) ([efcc32c](https://www.github.com/yargs/yargs-parser/commit/efcc32c2d6b09aba31abfa2db9bd947befe5586b))
### [20.2.7](https://www.github.com/yargs/yargs-parser/compare/v20.2.6...v20.2.7) (2021-03-10)
### Bug Fixes
* **deno:** force release for Deno ([6687c97](https://www.github.com/yargs/yargs-parser/commit/6687c972d0f3ca7865a97908dde3080b05f8b026))
### [20.2.6](https://www.github.com/yargs/yargs-parser/compare/v20.2.5...v20.2.6) (2021-02-22)
### Bug Fixes
* **populate--:** -- should always be array ([#354](https://www.github.com/yargs/yargs-parser/issues/354)) ([585ae8f](https://www.github.com/yargs/yargs-parser/commit/585ae8ffad74cc02974f92d788e750137fd65146))
### [20.2.5](https://www.github.com/yargs/yargs-parser/compare/v20.2.4...v20.2.5) (2021-02-13)
### Bug Fixes
* do not lowercase camel cased string ([#348](https://www.github.com/yargs/yargs-parser/issues/348)) ([5f4da1f](https://www.github.com/yargs/yargs-parser/commit/5f4da1f17d9d50542d2aaa206c9806ce3e320335))
### [20.2.4](https://www.github.com/yargs/yargs-parser/compare/v20.2.3...v20.2.4) (2020-11-09)
### Bug Fixes
* **deno:** address import issues in Deno ([#339](https://www.github.com/yargs/yargs-parser/issues/339)) ([3b54e5e](https://www.github.com/yargs/yargs-parser/commit/3b54e5eef6e9a7b7c6eec7c12bab3ba3b8ba8306))
### [20.2.3](https://www.github.com/yargs/yargs-parser/compare/v20.2.2...v20.2.3) (2020-10-16)
### Bug Fixes
* **exports:** node 13.0 and 13.1 require the dotted object form _with_ a string fallback ([#336](https://www.github.com/yargs/yargs-parser/issues/336)) ([3ae7242](https://www.github.com/yargs/yargs-parser/commit/3ae7242040ff876d28dabded60ac226e00150c88))
### [20.2.2](https://www.github.com/yargs/yargs-parser/compare/v20.2.1...v20.2.2) (2020-10-14)
### Bug Fixes
* **exports:** node 13.0-13.6 require a string fallback ([#333](https://www.github.com/yargs/yargs-parser/issues/333)) ([291aeda](https://www.github.com/yargs/yargs-parser/commit/291aeda06b685b7a015d83bdf2558e180b37388d))
### [20.2.1](https://www.github.com/yargs/yargs-parser/compare/v20.2.0...v20.2.1) (2020-10-01)
### Bug Fixes
* **deno:** update types for deno ^1.4.0 ([#330](https://www.github.com/yargs/yargs-parser/issues/330)) ([0ab92e5](https://www.github.com/yargs/yargs-parser/commit/0ab92e50b090f11196334c048c9c92cecaddaf56))
## [20.2.0](https://www.github.com/yargs/yargs-parser/compare/v20.1.0...v20.2.0) (2020-09-21)
### Features
* **string-utils:** export looksLikeNumber helper ([#324](https://www.github.com/yargs/yargs-parser/issues/324)) ([c8580a2](https://www.github.com/yargs/yargs-parser/commit/c8580a2327b55f6342acecb6e72b62963d506750))
### Bug Fixes
* **unknown-options-as-args:** convert positionals that look like numbers ([#326](https://www.github.com/yargs/yargs-parser/issues/326)) ([f85ebb4](https://www.github.com/yargs/yargs-parser/commit/f85ebb4face9d4b0f56147659404cbe0002f3dad))
## [20.1.0](https://www.github.com/yargs/yargs-parser/compare/v20.0.0...v20.1.0) (2020-09-20)
### Features
* adds parse-positional-numbers configuration ([#321](https://www.github.com/yargs/yargs-parser/issues/321)) ([9cec00a](https://www.github.com/yargs/yargs-parser/commit/9cec00a622251292ffb7dce6f78f5353afaa0d4c))
### Bug Fixes
* **build:** update release-please; make labels kick off builds ([#323](https://www.github.com/yargs/yargs-parser/issues/323)) ([09f448b](https://www.github.com/yargs/yargs-parser/commit/09f448b4cd66e25d2872544718df46dab8af062a))
## [20.0.0](https://www.github.com/yargs/yargs-parser/compare/v19.0.4...v20.0.0) (2020-09-09)
### ⚠ BREAKING CHANGES
* do not ship type definitions (#318)
### Bug Fixes
* only strip camel case if hyphenated ([#316](https://www.github.com/yargs/yargs-parser/issues/316)) ([95a9e78](https://www.github.com/yargs/yargs-parser/commit/95a9e785127b9bbf2d1db1f1f808ca1fb100e82a)), closes [#315](https://www.github.com/yargs/yargs-parser/issues/315)
### Code Refactoring
* do not ship type definitions ([#318](https://www.github.com/yargs/yargs-parser/issues/318)) ([8fbd56f](https://www.github.com/yargs/yargs-parser/commit/8fbd56f1d0b6c44c30fca62708812151ca0ce330))
### [19.0.4](https://www.github.com/yargs/yargs-parser/compare/v19.0.3...v19.0.4) (2020-08-27)
### Bug Fixes
* **build:** fixing publication ([#310](https://www.github.com/yargs/yargs-parser/issues/310)) ([5d3c6c2](https://www.github.com/yargs/yargs-parser/commit/5d3c6c29a9126248ba601920d9cf87c78e161ff5))
### [19.0.3](https://www.github.com/yargs/yargs-parser/compare/v19.0.2...v19.0.3) (2020-08-27)
### Bug Fixes
* **build:** switch to action for publish ([#308](https://www.github.com/yargs/yargs-parser/issues/308)) ([5c2f305](https://www.github.com/yargs/yargs-parser/commit/5c2f30585342bcd8aaf926407c863099d256d174))
### [19.0.2](https://www.github.com/yargs/yargs-parser/compare/v19.0.1...v19.0.2) (2020-08-27)
### Bug Fixes
* **types:** envPrefix should be optional ([#305](https://www.github.com/yargs/yargs-parser/issues/305)) ([ae3f180](https://www.github.com/yargs/yargs-parser/commit/ae3f180e14df2de2fd962145f4518f9aa0e76523))
### [19.0.1](https://www.github.com/yargs/yargs-parser/compare/v19.0.0...v19.0.1) (2020-08-09)
### Bug Fixes
* **build:** push tag created for deno ([2186a14](https://www.github.com/yargs/yargs-parser/commit/2186a14989749887d56189867602e39e6679f8b0))
## [19.0.0](https://www.github.com/yargs/yargs-parser/compare/v18.1.3...v19.0.0) (2020-08-09)
### ⚠ BREAKING CHANGES
* adds support for ESM and Deno (#295)
* **ts:** projects using `@types/yargs-parser` may see variations in type definitions.
* drops Node 6. begin following Node.js LTS schedule (#278)
### Features
* adds support for ESM and Deno ([#295](https://www.github.com/yargs/yargs-parser/issues/295)) ([195bc4a](https://www.github.com/yargs/yargs-parser/commit/195bc4a7f20c2a8f8e33fbb6ba96ef6e9a0120a1))
* expose camelCase and decamelize helpers ([#296](https://www.github.com/yargs/yargs-parser/issues/296)) ([39154ce](https://www.github.com/yargs/yargs-parser/commit/39154ceb5bdcf76b5f59a9219b34cedb79b67f26))
* **deps:** update to latest camelcase/decamelize ([#281](https://www.github.com/yargs/yargs-parser/issues/281)) ([8931ab0](https://www.github.com/yargs/yargs-parser/commit/8931ab08f686cc55286f33a95a83537da2be5516))
### Bug Fixes
* boolean numeric short option ([#294](https://www.github.com/yargs/yargs-parser/issues/294)) ([f600082](https://www.github.com/yargs/yargs-parser/commit/f600082c959e092076caf420bbbc9d7a231e2418))
* raise permission error for Deno if config load fails ([#298](https://www.github.com/yargs/yargs-parser/issues/298)) ([1174e2b](https://www.github.com/yargs/yargs-parser/commit/1174e2b3f0c845a1cd64e14ffc3703e730567a84))
* **deps:** update dependency decamelize to v3 ([#274](https://www.github.com/yargs/yargs-parser/issues/274)) ([4d98698](https://www.github.com/yargs/yargs-parser/commit/4d98698bc6767e84ec54a0842908191739be73b7))
* **types:** switch back to using Partial types ([#293](https://www.github.com/yargs/yargs-parser/issues/293)) ([bdc80ba](https://www.github.com/yargs/yargs-parser/commit/bdc80ba59fa13bc3025ce0a85e8bad9f9da24ea7))
### Build System
* drops Node 6. begin following Node.js LTS schedule ([#278](https://www.github.com/yargs/yargs-parser/issues/278)) ([9014ed7](https://www.github.com/yargs/yargs-parser/commit/9014ed722a32768b96b829e65a31705db5c1458a))
### Code Refactoring
* **ts:** move index.js to TypeScript ([#292](https://www.github.com/yargs/yargs-parser/issues/292)) ([f78d2b9](https://www.github.com/yargs/yargs-parser/commit/f78d2b97567ac4828624406e420b4047c710b789))
### [18.1.3](https://www.github.com/yargs/yargs-parser/compare/v18.1.2...v18.1.3) (2020-04-16)
### Bug Fixes
* **setArg:** options using camel-case and dot-notation populated twice ([#268](https://www.github.com/yargs/yargs-parser/issues/268)) ([f7e15b9](https://www.github.com/yargs/yargs-parser/commit/f7e15b9800900b9856acac1a830a5f35847be73e))
### [18.1.2](https://www.github.com/yargs/yargs-parser/compare/v18.1.1...v18.1.2) (2020-03-26)
### Bug Fixes
* **array, nargs:** support -o=--value and --option=--value format ([#262](https://www.github.com/yargs/yargs-parser/issues/262)) ([41d3f81](https://www.github.com/yargs/yargs-parser/commit/41d3f8139e116706b28de9b0de3433feb08d2f13))
### [18.1.1](https://www.github.com/yargs/yargs-parser/compare/v18.1.0...v18.1.1) (2020-03-16)
### Bug Fixes
* \_\_proto\_\_ will now be replaced with \_\_\_proto\_\_\_ in parse ([#258](https://www.github.com/yargs/yargs-parser/issues/258)), patching a potential
prototype pollution vulnerability. This was reported by the Snyk Security Research Team.([63810ca](https://www.github.com/yargs/yargs-parser/commit/63810ca1ae1a24b08293a4d971e70e058c7a41e2))
## [18.1.0](https://www.github.com/yargs/yargs-parser/compare/v18.0.0...v18.1.0) (2020-03-07)
### Features
* introduce single-digit boolean aliases ([#255](https://www.github.com/yargs/yargs-parser/issues/255)) ([9c60265](https://www.github.com/yargs/yargs-parser/commit/9c60265fd7a03cb98e6df3e32c8c5e7508d9f56f))
## [18.0.0](https://www.github.com/yargs/yargs-parser/compare/v17.1.0...v18.0.0) (2020-03-02)
### ⚠ BREAKING CHANGES
* the narg count is now enforced when parsing arrays.
### Features
* NaN can now be provided as a value for nargs, indicating "at least" one value is expected for array ([#251](https://www.github.com/yargs/yargs-parser/issues/251)) ([9db4be8](https://www.github.com/yargs/yargs-parser/commit/9db4be81417a2c7097128db34d86fe70ef4af70c))
## [17.1.0](https://www.github.com/yargs/yargs-parser/compare/v17.0.1...v17.1.0) (2020-03-01)
### Features
* introduce greedy-arrays config, for specifying whether arrays consume multiple positionals ([#249](https://www.github.com/yargs/yargs-parser/issues/249)) ([60e880a](https://www.github.com/yargs/yargs-parser/commit/60e880a837046314d89fa4725f923837fd33a9eb))
### [17.0.1](https://www.github.com/yargs/yargs-parser/compare/v17.0.0...v17.0.1) (2020-02-29)
### Bug Fixes
* normalized keys were not enumerable ([#247](https://www.github.com/yargs/yargs-parser/issues/247)) ([57119f9](https://www.github.com/yargs/yargs-parser/commit/57119f9f17cf27499bd95e61c2f72d18314f11ba))
## [17.0.0](https://www.github.com/yargs/yargs-parser/compare/v16.1.0...v17.0.0) (2020-02-10)
### ⚠ BREAKING CHANGES
* this reverts parsing behavior of booleans to that of yargs@14
* objects used during parsing are now created with a null
prototype. There may be some scenarios where this change in behavior
leaks externally.
### Features
* boolean arguments will not be collected into an implicit array ([#236](https://www.github.com/yargs/yargs-parser/issues/236)) ([34c4e19](https://www.github.com/yargs/yargs-parser/commit/34c4e19bae4e7af63e3cb6fa654a97ed476e5eb5))
* introduce nargs-eats-options config option ([#246](https://www.github.com/yargs/yargs-parser/issues/246)) ([d50822a](https://www.github.com/yargs/yargs-parser/commit/d50822ac10e1b05f2e9643671ca131ac251b6732))
### Bug Fixes
* address bugs with "uknown-options-as-args" ([bc023e3](https://www.github.com/yargs/yargs-parser/commit/bc023e3b13e20a118353f9507d1c999bf388a346))
* array should take precedence over nargs, but enforce nargs ([#243](https://www.github.com/yargs/yargs-parser/issues/243)) ([4cbc188](https://www.github.com/yargs/yargs-parser/commit/4cbc188b7abb2249529a19c090338debdad2fe6c))
* support keys that collide with object prototypes ([#234](https://www.github.com/yargs/yargs-parser/issues/234)) ([1587b6d](https://www.github.com/yargs/yargs-parser/commit/1587b6d91db853a9109f1be6b209077993fee4de))
* unknown options terminated with digits now handled by unknown-options-as-args ([#238](https://www.github.com/yargs/yargs-parser/issues/238)) ([d36cdfa](https://www.github.com/yargs/yargs-parser/commit/d36cdfa854254d7c7e0fe1d583818332ac46c2a5))
## [16.1.0](https://www.github.com/yargs/yargs-parser/compare/v16.0.0...v16.1.0) (2019-11-01)
### ⚠ BREAKING CHANGES
* populate error if incompatible narg/count or array/count options are used (#191)
### Features
* options that have had their default value used are now tracked ([#211](https://www.github.com/yargs/yargs-parser/issues/211)) ([a525234](https://www.github.com/yargs/yargs-parser/commit/a525234558c847deedd73f8792e0a3b77b26e2c0))
* populate error if incompatible narg/count or array/count options are used ([#191](https://www.github.com/yargs/yargs-parser/issues/191)) ([84a401f](https://www.github.com/yargs/yargs-parser/commit/84a401f0fa3095e0a19661670d1570d0c3b9d3c9))
### Reverts
* revert 16.0.0 CHANGELOG entry ([920320a](https://www.github.com/yargs/yargs-parser/commit/920320ad9861bbfd58eda39221ae211540fc1daf))

View File

@@ -0,0 +1,14 @@
Copyright (c) 2016, Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice
appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE
LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@@ -0,0 +1,518 @@
# yargs-parser
![ci](https://github.com/yargs/yargs-parser/workflows/ci/badge.svg)
[![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser)
[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org)
![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/yargs-parser)
The mighty option parser used by [yargs](https://github.com/yargs/yargs).
visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions.
<img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/main/yargs-logo.png">
## Example
```sh
npm i yargs-parser --save
```
```js
const argv = require('yargs-parser')(process.argv.slice(2))
console.log(argv)
```
```console
$ node example.js --foo=33 --bar hello
{ _: [], foo: 33, bar: 'hello' }
```
_or parse a string!_
```js
const argv = require('yargs-parser')('--foo=99 --bar=33')
console.log(argv)
```
```console
{ _: [], foo: 99, bar: 33 }
```
Convert an array of mixed types before passing to `yargs-parser`:
```js
const parse = require('yargs-parser')
parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string
parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings
```
## Deno Example
As of `v19` `yargs-parser` supports [Deno](https://github.com/denoland/deno):
```typescript
import parser from "https://deno.land/x/yargs_parser/deno.ts";
const argv = parser('--foo=99 --bar=9987930', {
string: ['bar']
})
console.log(argv)
```
## ESM Example
As of `v19` `yargs-parser` supports ESM (_both in Node.js and in the browser_):
**Node.js:**
```js
import parser from 'yargs-parser'
const argv = parser('--foo=99 --bar=9987930', {
string: ['bar']
})
console.log(argv)
```
**Browsers:**
```html
<!doctype html>
<body>
<script type="module">
import parser from "https://unpkg.com/yargs-parser@19.0.0/browser.js";
const argv = parser('--foo=99 --bar=9987930', {
string: ['bar']
})
console.log(argv)
</script>
</body>
```
## API
### parser(args, opts={})
Parses command line arguments returning a simple mapping of keys and values.
**expects:**
* `args`: a string or array of strings representing the options to parse.
* `opts`: provide a set of hints indicating how `args` should be parsed:
* `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`.
* `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br>
Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br>
`{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`.
* `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`.
* `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided
(or throws an error). For arrays the function is called only once for the entire array:<br>
`{coerce: {foo: function (arg) {return modifiedArg}}}`.
* `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed).
* `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br>
`{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`.
* `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)).
* `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`.
* `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`.
* `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed.
* `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`.
* `opts.normalize`: `path.normalize()` will be applied to values set to this key.
* `opts.number`: keys should be treated as numbers.
* `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`).
**returns:**
* `obj`: an object representing the parsed value of `args`
* `key/value`: key value pairs for each argument and their aliases.
* `_`: an array representing the positional arguments.
* [optional] `--`: an array with arguments after the end-of-options flag `--`.
### require('yargs-parser').detailed(args, opts={})
Parses a command line string, returning detailed information required by the
yargs engine.
**expects:**
* `args`: a string or array of strings representing options to parse.
* `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`.
**returns:**
* `argv`: an object representing the parsed value of `args`
* `key/value`: key value pairs for each argument and their aliases.
* `_`: an array representing the positional arguments.
* [optional] `--`: an array with arguments after the end-of-options flag `--`.
* `error`: populated with an error object if an exception occurred during parsing.
* `aliases`: the inferred list of aliases built by combining lists in `opts.alias`.
* `newAliases`: any new aliases added via camel-case expansion:
* `boolean`: `{ fooBar: true }`
* `defaulted`: any new argument created by `opts.default`, no aliases included.
* `boolean`: `{ foo: true }`
* `configuration`: given by default settings and `opts.configuration`.
<a name="configuration"></a>
### Configuration
The yargs-parser applies several automated transformations on the keys provided
in `args`. These features can be turned on and off using the `configuration` field
of `opts`.
```js
var parsed = parser(['--no-dice'], {
configuration: {
'boolean-negation': false
}
})
```
### short option groups
* default: `true`.
* key: `short-option-groups`.
Should a group of short-options be treated as boolean flags?
```console
$ node example.js -abc
{ _: [], a: true, b: true, c: true }
```
_if disabled:_
```console
$ node example.js -abc
{ _: [], abc: true }
```
### camel-case expansion
* default: `true`.
* key: `camel-case-expansion`.
Should hyphenated arguments be expanded into camel-case aliases?
```console
$ node example.js --foo-bar
{ _: [], 'foo-bar': true, fooBar: true }
```
_if disabled:_
```console
$ node example.js --foo-bar
{ _: [], 'foo-bar': true }
```
### dot-notation
* default: `true`
* key: `dot-notation`
Should keys that contain `.` be treated as objects?
```console
$ node example.js --foo.bar
{ _: [], foo: { bar: true } }
```
_if disabled:_
```console
$ node example.js --foo.bar
{ _: [], "foo.bar": true }
```
### parse numbers
* default: `true`
* key: `parse-numbers`
Should keys that look like numbers be treated as such?
```console
$ node example.js --foo=99.3
{ _: [], foo: 99.3 }
```
_if disabled:_
```console
$ node example.js --foo=99.3
{ _: [], foo: "99.3" }
```
### parse positional numbers
* default: `true`
* key: `parse-positional-numbers`
Should positional keys that look like numbers be treated as such.
```console
$ node example.js 99.3
{ _: [99.3] }
```
_if disabled:_
```console
$ node example.js 99.3
{ _: ['99.3'] }
```
### boolean negation
* default: `true`
* key: `boolean-negation`
Should variables prefixed with `--no` be treated as negations?
```console
$ node example.js --no-foo
{ _: [], foo: false }
```
_if disabled:_
```console
$ node example.js --no-foo
{ _: [], "no-foo": true }
```
### combine arrays
* default: `false`
* key: `combine-arrays`
Should arrays be combined when provided by both command line arguments and
a configuration file.
### duplicate arguments array
* default: `true`
* key: `duplicate-arguments-array`
Should arguments be coerced into an array when duplicated:
```console
$ node example.js -x 1 -x 2
{ _: [], x: [1, 2] }
```
_if disabled:_
```console
$ node example.js -x 1 -x 2
{ _: [], x: 2 }
```
### flatten duplicate arrays
* default: `true`
* key: `flatten-duplicate-arrays`
Should array arguments be coerced into a single array when duplicated:
```console
$ node example.js -x 1 2 -x 3 4
{ _: [], x: [1, 2, 3, 4] }
```
_if disabled:_
```console
$ node example.js -x 1 2 -x 3 4
{ _: [], x: [[1, 2], [3, 4]] }
```
### greedy arrays
* default: `true`
* key: `greedy-arrays`
Should arrays consume more than one positional argument following their flag.
```console
$ node example --arr 1 2
{ _: [], arr: [1, 2] }
```
_if disabled:_
```console
$ node example --arr 1 2
{ _: [2], arr: [1] }
```
**Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.**
### nargs eats options
* default: `false`
* key: `nargs-eats-options`
Should nargs consume dash options as well as positional arguments.
### negation prefix
* default: `no-`
* key: `negation-prefix`
The prefix to use for negated boolean variables.
```console
$ node example.js --no-foo
{ _: [], foo: false }
```
_if set to `quux`:_
```console
$ node example.js --quuxfoo
{ _: [], foo: false }
```
### populate --
* default: `false`.
* key: `populate--`
Should unparsed flags be stored in `--` or `_`.
_If disabled:_
```console
$ node example.js a -b -- x y
{ _: [ 'a', 'x', 'y' ], b: true }
```
_If enabled:_
```console
$ node example.js a -b -- x y
{ _: [ 'a' ], '--': [ 'x', 'y' ], b: true }
```
### set placeholder key
* default: `false`.
* key: `set-placeholder-key`.
Should a placeholder be added for keys not set via the corresponding CLI argument?
_If disabled:_
```console
$ node example.js -a 1 -c 2
{ _: [], a: 1, c: 2 }
```
_If enabled:_
```console
$ node example.js -a 1 -c 2
{ _: [], a: 1, b: undefined, c: 2 }
```
### halt at non-option
* default: `false`.
* key: `halt-at-non-option`.
Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line.
_If disabled:_
```console
$ node example.js -a run b -x y
{ _: [ 'b' ], a: 'run', x: 'y' }
```
_If enabled:_
```console
$ node example.js -a run b -x y
{ _: [ 'b', '-x', 'y' ], a: 'run' }
```
### strip aliased
* default: `false`
* key: `strip-aliased`
Should aliases be removed before returning results?
_If disabled:_
```console
$ node example.js --test-field 1
{ _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 }
```
_If enabled:_
```console
$ node example.js --test-field 1
{ _: [], 'test-field': 1, testField: 1 }
```
### strip dashed
* default: `false`
* key: `strip-dashed`
Should dashed keys be removed before returning results? This option has no effect if
`camel-case-expansion` is disabled.
_If disabled:_
```console
$ node example.js --test-field 1
{ _: [], 'test-field': 1, testField: 1 }
```
_If enabled:_
```console
$ node example.js --test-field 1
{ _: [], testField: 1 }
```
### unknown options as args
* default: `false`
* key: `unknown-options-as-args`
Should unknown options be treated like regular arguments? An unknown option is one that is not
configured in `opts`.
_If disabled_
```console
$ node example.js --unknown-option --known-option 2 --string-option --unknown-option2
{ _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true }
```
_If enabled_
```console
$ node example.js --unknown-option --known-option 2 --string-option --unknown-option2
{ _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' }
```
## Supported Node.js Versions
Libraries in this ecosystem make a best effort to track
[Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a
post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a).
## Special Thanks
The yargs project evolves from optimist and minimist. It owes its
existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/
## License
ISC

View File

@@ -0,0 +1,29 @@
// Main entrypoint for ESM web browser environments. Avoids using Node.js
// specific libraries, such as "path".
//
// TODO: figure out reasonable web equivalents for "resolve", "normalize", etc.
import { camelCase, decamelize, looksLikeNumber } from './build/lib/string-utils.js'
import { YargsParser } from './build/lib/yargs-parser.js'
const parser = new YargsParser({
cwd: () => { return '' },
format: (str, arg) => { return str.replace('%s', arg) },
normalize: (str) => { return str },
resolve: (str) => { return str },
require: () => {
throw Error('loading config from files not currently supported in browser')
},
env: () => {}
})
const yargsParser = function Parser (args, opts) {
const result = parser.parse(args.slice(), opts)
return result.argv
}
yargsParser.detailed = function (args, opts) {
return parser.parse(args.slice(), opts)
}
yargsParser.camelCase = camelCase
yargsParser.decamelize = decamelize
yargsParser.looksLikeNumber = looksLikeNumber
export default yargsParser

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,59 @@
/**
* @fileoverview Main entrypoint for libraries using yargs-parser in Node.js
* CJS and ESM environments.
*
* @license
* Copyright (c) 2016, Contributors
* SPDX-License-Identifier: ISC
*/
import { format } from 'util';
import { readFileSync } from 'fs';
import { normalize, resolve } from 'path';
import { camelCase, decamelize, looksLikeNumber } from './string-utils.js';
import { YargsParser } from './yargs-parser.js';
// See https://github.com/yargs/yargs-parser#supported-nodejs-versions for our
// version support policy. The YARGS_MIN_NODE_VERSION is used for testing only.
const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION)
? Number(process.env.YARGS_MIN_NODE_VERSION)
: 10;
if (process && process.version) {
const major = Number(process.version.match(/v([^.]+)/)[1]);
if (major < minNodeVersion) {
throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);
}
}
// Creates a yargs-parser instance using Node.js standard libraries:
const env = process ? process.env : {};
const parser = new YargsParser({
cwd: process.cwd,
env: () => {
return env;
},
format,
normalize,
resolve,
// TODO: figure out a way to combine ESM and CJS coverage, such that
// we can exercise all the lines below:
require: (path) => {
if (typeof require !== 'undefined') {
return require(path);
}
else if (path.match(/\.json$/)) {
return readFileSync(path, 'utf8');
}
else {
throw Error('only .json config files are supported in ESM');
}
}
});
const yargsParser = function Parser(args, opts) {
const result = parser.parse(args.slice(), opts);
return result.argv;
};
yargsParser.detailed = function (args, opts) {
return parser.parse(args.slice(), opts);
};
yargsParser.camelCase = camelCase;
yargsParser.decamelize = decamelize;
yargsParser.looksLikeNumber = looksLikeNumber;
export default yargsParser;

View File

@@ -0,0 +1,65 @@
/**
* @license
* Copyright (c) 2016, Contributors
* SPDX-License-Identifier: ISC
*/
export function camelCase(str) {
// Handle the case where an argument is provided as camel case, e.g., fooBar.
// by ensuring that the string isn't already mixed case:
const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase();
if (!isCamelCase) {
str = str.toLowerCase();
}
if (str.indexOf('-') === -1 && str.indexOf('_') === -1) {
return str;
}
else {
let camelcase = '';
let nextChrUpper = false;
const leadingHyphens = str.match(/^-+/);
for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) {
let chr = str.charAt(i);
if (nextChrUpper) {
nextChrUpper = false;
chr = chr.toUpperCase();
}
if (i !== 0 && (chr === '-' || chr === '_')) {
nextChrUpper = true;
}
else if (chr !== '-' && chr !== '_') {
camelcase += chr;
}
}
return camelcase;
}
}
export function decamelize(str, joinString) {
const lowercase = str.toLowerCase();
joinString = joinString || '-';
let notCamelcase = '';
for (let i = 0; i < str.length; i++) {
const chrLower = lowercase.charAt(i);
const chrString = str.charAt(i);
if (chrLower !== chrString && i > 0) {
notCamelcase += `${joinString}${lowercase.charAt(i)}`;
}
else {
notCamelcase += chrString;
}
}
return notCamelcase;
}
export function looksLikeNumber(x) {
if (x === null || x === undefined)
return false;
// if loaded from config, may already be a number.
if (typeof x === 'number')
return true;
// hexadecimal.
if (/^0x[0-9a-f]+$/i.test(x))
return true;
// don't treat 0123 as a number; as it drops the leading '0'.
if (/^0[^.]/.test(x))
return false;
return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
}

View File

@@ -0,0 +1,40 @@
/**
* @license
* Copyright (c) 2016, Contributors
* SPDX-License-Identifier: ISC
*/
// take an un-split argv string and tokenize it.
export function tokenizeArgString(argString) {
if (Array.isArray(argString)) {
return argString.map(e => typeof e !== 'string' ? e + '' : e);
}
argString = argString.trim();
let i = 0;
let prevC = null;
let c = null;
let opening = null;
const args = [];
for (let ii = 0; ii < argString.length; ii++) {
prevC = c;
c = argString.charAt(ii);
// split on spaces unless we're in quotes.
if (c === ' ' && !opening) {
if (!(prevC === ' ')) {
i++;
}
continue;
}
// don't split the string if we're in matching
// opening or closing single and double quotes.
if (c === opening) {
opening = null;
}
else if ((c === "'" || c === '"') && !opening) {
opening = c;
}
if (!args[i])
args[i] = '';
args[i] += c;
}
return args;
}

View File

@@ -0,0 +1,12 @@
/**
* @license
* Copyright (c) 2016, Contributors
* SPDX-License-Identifier: ISC
*/
export var DefaultValuesForTypeKey;
(function (DefaultValuesForTypeKey) {
DefaultValuesForTypeKey["BOOLEAN"] = "boolean";
DefaultValuesForTypeKey["STRING"] = "string";
DefaultValuesForTypeKey["NUMBER"] = "number";
DefaultValuesForTypeKey["ARRAY"] = "array";
})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {}));

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,87 @@
{
"name": "yargs-parser",
"version": "20.2.9",
"description": "the mighty option parser used by yargs",
"main": "build/index.cjs",
"exports": {
".": [
{
"import": "./build/lib/index.js",
"require": "./build/index.cjs"
},
"./build/index.cjs"
]
},
"type": "module",
"module": "./build/lib/index.js",
"scripts": {
"check": "standardx '**/*.ts' && standardx '**/*.js' && standardx '**/*.cjs'",
"fix": "standardx --fix '**/*.ts' && standardx --fix '**/*.js' && standardx --fix '**/*.cjs'",
"pretest": "rimraf build && tsc -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs",
"test": "c8 --reporter=text --reporter=html mocha test/*.cjs",
"test:browser": "start-server-and-test 'serve ./ -p 8080' http://127.0.0.1:8080/package.json 'node ./test/browser/yargs-test.cjs'",
"pretest:typescript": "npm run pretest",
"test:typescript": "c8 mocha ./build/test/typescript/*.js",
"coverage": "c8 report --check-coverage",
"precompile": "rimraf build",
"compile": "tsc",
"postcompile": "npm run build:cjs",
"build:cjs": "rollup -c",
"prepare": "npm run compile"
},
"repository": {
"type": "git",
"url": "https://github.com/yargs/yargs-parser.git"
},
"keywords": [
"argument",
"parser",
"yargs",
"command",
"cli",
"parsing",
"option",
"args",
"argument"
],
"author": "Ben Coe <ben@npmjs.com>",
"license": "ISC",
"devDependencies": {
"@types/chai": "^4.2.11",
"@types/mocha": "^8.0.0",
"@types/node": "^14.0.0",
"@typescript-eslint/eslint-plugin": "^3.10.1",
"@typescript-eslint/parser": "^3.10.1",
"@wessberg/rollup-plugin-ts": "^1.2.28",
"c8": "^7.3.0",
"chai": "^4.2.0",
"cross-env": "^7.0.2",
"eslint": "^7.0.0",
"eslint-plugin-import": "^2.20.1",
"eslint-plugin-node": "^11.0.0",
"gts": "^3.0.0",
"mocha": "^9.0.0",
"puppeteer": "^10.0.0",
"rimraf": "^3.0.2",
"rollup": "^2.22.1",
"rollup-plugin-cleanup": "^3.1.1",
"serve": "^12.0.0",
"standardx": "^7.0.0",
"start-server-and-test": "^1.11.2",
"ts-transform-default-export": "^1.0.2",
"typescript": "^4.0.0"
},
"files": [
"browser.js",
"build",
"!*.d.ts"
],
"engines": {
"node": ">=10"
},
"standardx": {
"ignore": [
"build"
]
}
}

88
node_modules/gulp-cli/node_modules/yargs/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,88 @@
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
## [16.2.0](https://www.github.com/yargs/yargs/compare/v16.1.1...v16.2.0) (2020-12-05)
### Features
* command() now accepts an array of modules ([f415388](https://www.github.com/yargs/yargs/commit/f415388cc454d02786c65c50dd6c7a0cf9d8b842))
### Bug Fixes
* add package.json to module exports ([#1818](https://www.github.com/yargs/yargs/issues/1818)) ([d783a49](https://www.github.com/yargs/yargs/commit/d783a49a7f21c9bbd4eec2990268f3244c4d5662)), closes [#1817](https://www.github.com/yargs/yargs/issues/1817)
### [16.1.1](https://www.github.com/yargs/yargs/compare/v16.1.0...v16.1.1) (2020-11-15)
### Bug Fixes
* expose helpers for legacy versions of Node.js ([#1801](https://www.github.com/yargs/yargs/issues/1801)) ([107deaa](https://www.github.com/yargs/yargs/commit/107deaa4f68b7bc3f2386041e1f4fe0272b29c0a))
* **deno:** get yargs working on deno@1.5.x ([#1799](https://www.github.com/yargs/yargs/issues/1799)) ([cb01c98](https://www.github.com/yargs/yargs/commit/cb01c98c44e30f55c2dc9434caef524ae433d9a4))
## [16.1.0](https://www.github.com/yargs/yargs/compare/v16.0.3...v16.1.0) (2020-10-15)
### Features
* expose hideBin helper for CJS ([#1768](https://www.github.com/yargs/yargs/issues/1768)) ([63e1173](https://www.github.com/yargs/yargs/commit/63e1173bb47dc651c151973a16ef659082a9ae66))
### Bug Fixes
* **deno:** update types for deno ^1.4.0 ([#1772](https://www.github.com/yargs/yargs/issues/1772)) ([0801752](https://www.github.com/yargs/yargs/commit/080175207d281be63edf90adfe4f0568700b0bf5))
* **exports:** node 13.0-13.6 require a string fallback ([#1776](https://www.github.com/yargs/yargs/issues/1776)) ([b45c43a](https://www.github.com/yargs/yargs/commit/b45c43a5f64b565c3794f9792150eaeec4e00b69))
* **modules:** module path was incorrect ([#1759](https://www.github.com/yargs/yargs/issues/1759)) ([95a4a0a](https://www.github.com/yargs/yargs/commit/95a4a0ac573cfe158e6e4bc8c8682ebd1644a198))
* **positional:** positional strings no longer drop decimals ([#1761](https://www.github.com/yargs/yargs/issues/1761)) ([e1a300f](https://www.github.com/yargs/yargs/commit/e1a300f1293ad821c900284616337f080b207980))
* make positionals in -- count towards validation ([#1752](https://www.github.com/yargs/yargs/issues/1752)) ([eb2b29d](https://www.github.com/yargs/yargs/commit/eb2b29d34f1a41e0fd6c4e841960e5bfc329dc3c))
### [16.0.3](https://www.github.com/yargs/yargs/compare/v16.0.2...v16.0.3) (2020-09-10)
### Bug Fixes
* move yargs.cjs to yargs to fix Node 10 imports ([#1747](https://www.github.com/yargs/yargs/issues/1747)) ([5bfb85b](https://www.github.com/yargs/yargs/commit/5bfb85b33b85db8a44b5f7a700a8e4dbaf022df0))
### [16.0.2](https://www.github.com/yargs/yargs/compare/v16.0.1...v16.0.2) (2020-09-09)
### Bug Fixes
* **typescript:** yargs-parser was breaking @types/yargs ([#1745](https://www.github.com/yargs/yargs/issues/1745)) ([2253284](https://www.github.com/yargs/yargs/commit/2253284b233cceabd8db677b81c5bf1755eef230))
### [16.0.1](https://www.github.com/yargs/yargs/compare/v16.0.0...v16.0.1) (2020-09-09)
### Bug Fixes
* code was not passed to process.exit ([#1742](https://www.github.com/yargs/yargs/issues/1742)) ([d1a9930](https://www.github.com/yargs/yargs/commit/d1a993035a2f76c138460052cf19425f9684b637))
## [16.0.0](https://www.github.com/yargs/yargs/compare/v15.4.2...v16.0.0) (2020-09-09)
### ⚠ BREAKING CHANGES
* tweaks to ESM/Deno API surface: now exports yargs function by default; getProcessArgvWithoutBin becomes hideBin; types now exported for Deno.
* find-up replaced with escalade; export map added (limits importable files in Node >= 12); yarser-parser@19.x.x (new decamelize/camelcase implementation).
* **usage:** single character aliases are now shown first in help output
* rebase helper is no longer provided on yargs instance.
* drop support for EOL Node 8 (#1686)
### Features
* adds strictOptions() ([#1738](https://www.github.com/yargs/yargs/issues/1738)) ([b215fba](https://www.github.com/yargs/yargs/commit/b215fba0ed6e124e5aad6cf22c8d5875661c63a3))
* **helpers:** rebase, Parser, applyExtends now blessed helpers ([#1733](https://www.github.com/yargs/yargs/issues/1733)) ([c7debe8](https://www.github.com/yargs/yargs/commit/c7debe8eb1e5bc6ea20b5ed68026c56e5ebec9e1))
* adds support for ESM and Deno ([#1708](https://www.github.com/yargs/yargs/issues/1708)) ([ac6d5d1](https://www.github.com/yargs/yargs/commit/ac6d5d105a75711fe703f6a39dad5181b383d6c6))
* drop support for EOL Node 8 ([#1686](https://www.github.com/yargs/yargs/issues/1686)) ([863937f](https://www.github.com/yargs/yargs/commit/863937f23c3102f804cdea78ee3097e28c7c289f))
* i18n for ESM and Deno ([#1735](https://www.github.com/yargs/yargs/issues/1735)) ([c71783a](https://www.github.com/yargs/yargs/commit/c71783a5a898a0c0e92ac501c939a3ec411ac0c1))
* tweaks to API surface based on user feedback ([#1726](https://www.github.com/yargs/yargs/issues/1726)) ([4151fee](https://www.github.com/yargs/yargs/commit/4151fee4c33a97d26bc40de7e623e5b0eb87e9bb))
* **usage:** single char aliases first in help ([#1574](https://www.github.com/yargs/yargs/issues/1574)) ([a552990](https://www.github.com/yargs/yargs/commit/a552990c120646c2d85a5c9b628e1ce92a68e797))
### Bug Fixes
* **yargs:** add missing command(module) signature ([#1707](https://www.github.com/yargs/yargs/issues/1707)) ([0f81024](https://www.github.com/yargs/yargs/commit/0f810245494ccf13a35b7786d021b30fc95ecad5)), closes [#1704](https://www.github.com/yargs/yargs/issues/1704)
[Older CHANGELOG Entries](https://github.com/yargs/yargs/blob/master/docs/CHANGELOG-historical.md)

21
node_modules/gulp-cli/node_modules/yargs/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright 2010 James Halliday (mail@substack.net); Modified work Copyright 2014 Contributors (ben@npmjs.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

202
node_modules/gulp-cli/node_modules/yargs/README.md generated vendored Normal file
View File

@@ -0,0 +1,202 @@
<p align="center">
<img width="250" src="https://raw.githubusercontent.com/yargs/yargs/master/yargs-logo.png">
</p>
<h1 align="center"> Yargs </h1>
<p align="center">
<b >Yargs be a node.js library fer hearties tryin' ter parse optstrings</b>
</p>
<br>
![ci](https://github.com/yargs/yargs/workflows/ci/badge.svg)
[![NPM version][npm-image]][npm-url]
[![js-standard-style][standard-image]][standard-url]
[![Coverage][coverage-image]][coverage-url]
[![Conventional Commits][conventional-commits-image]][conventional-commits-url]
[![Slack][slack-image]][slack-url]
## Description
Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface.
It gives you:
* commands and (grouped) options (`my-program.js serve --port=5000`).
* a dynamically generated help menu based on your arguments:
```
mocha [spec..]
Run tests with Mocha
Commands
mocha inspect [spec..] Run tests with Mocha [default]
mocha init <path> create a client-side Mocha setup at <path>
Rules & Behavior
--allow-uncaught Allow uncaught errors to propagate [boolean]
--async-only, -A Require all tests to use a callback (async) or
return a Promise [boolean]
```
* bash-completion shortcuts for commands and options.
* and [tons more](/docs/api.md).
## Installation
Stable version:
```bash
npm i yargs
```
Bleeding edge version with the most recent features:
```bash
npm i yargs@next
```
## Usage
### Simple Example
```javascript
#!/usr/bin/env node
const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers')
const argv = yargs(hideBin(process.argv)).argv
if (argv.ships > 3 && argv.distance < 53.5) {
console.log('Plunder more riffiwobbles!')
} else {
console.log('Retreat from the xupptumblers!')
}
```
```bash
$ ./plunder.js --ships=4 --distance=22
Plunder more riffiwobbles!
$ ./plunder.js --ships 12 --distance 98.7
Retreat from the xupptumblers!
```
### Complex Example
```javascript
#!/usr/bin/env node
const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers')
yargs(hideBin(process.argv))
.command('serve [port]', 'start the server', (yargs) => {
yargs
.positional('port', {
describe: 'port to bind on',
default: 5000
})
}, (argv) => {
if (argv.verbose) console.info(`start server on :${argv.port}`)
serve(argv.port)
})
.option('verbose', {
alias: 'v',
type: 'boolean',
description: 'Run with verbose logging'
})
.argv
```
Run the example above with `--help` to see the help for the application.
## Supported Platforms
### TypeScript
yargs has type definitions at [@types/yargs][type-definitions].
```
npm i @types/yargs --save-dev
```
See usage examples in [docs](/docs/typescript.md).
### Deno
As of `v16`, `yargs` supports [Deno](https://github.com/denoland/deno):
```typescript
import yargs from 'https://deno.land/x/yargs/deno.ts'
import { Arguments } from 'https://deno.land/x/yargs/deno-types.ts'
yargs(Deno.args)
.command('download <files...>', 'download a list of files', (yargs: any) => {
return yargs.positional('files', {
describe: 'a list of files to do something with'
})
}, (argv: Arguments) => {
console.info(argv)
})
.strictCommands()
.demandCommand(1)
.argv
```
### ESM
As of `v16`,`yargs` supports ESM imports:
```js
import yargs from 'yargs'
import { hideBin } from 'yargs/helpers'
yargs(hideBin(process.argv))
.command('curl <url>', 'fetch the contents of the URL', () => {}, (argv) => {
console.info(argv)
})
.demandCommand(1)
.argv
```
### Usage in Browser
See examples of using yargs in the browser in [docs](/docs/browser.md).
## Community
Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com).
## Documentation
### Table of Contents
* [Yargs' API](/docs/api.md)
* [Examples](/docs/examples.md)
* [Parsing Tricks](/docs/tricks.md)
* [Stop the Parser](/docs/tricks.md#stop)
* [Negating Boolean Arguments](/docs/tricks.md#negate)
* [Numbers](/docs/tricks.md#numbers)
* [Arrays](/docs/tricks.md#arrays)
* [Objects](/docs/tricks.md#objects)
* [Quotes](/docs/tricks.md#quotes)
* [Advanced Topics](/docs/advanced.md)
* [Composing Your App Using Commands](/docs/advanced.md#commands)
* [Building Configurable CLI Apps](/docs/advanced.md#configuration)
* [Customizing Yargs' Parser](/docs/advanced.md#customizing)
* [Bundling yargs](/docs/bundling.md)
* [Contributing](/contributing.md)
## Supported Node.js Versions
Libraries in this ecosystem make a best effort to track
[Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a
post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a).
[npm-url]: https://www.npmjs.com/package/yargs
[npm-image]: https://img.shields.io/npm/v/yargs.svg
[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg
[standard-url]: http://standardjs.com/
[conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg
[conventional-commits-url]: https://conventionalcommits.org/
[slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg
[slack-url]: http://devtoolscommunity.herokuapp.com
[type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs
[coverage-image]: https://img.shields.io/nycrc/yargs/yargs
[coverage-url]: https://github.com/yargs/yargs/blob/master/.nycrc

7
node_modules/gulp-cli/node_modules/yargs/browser.mjs generated vendored Normal file
View File

@@ -0,0 +1,7 @@
// Bootstrap yargs for browser:
import browserPlatformShim from './lib/platform-shims/browser.mjs';
import {YargsWithShim} from './build/lib/yargs-factory.js';
const Yargs = YargsWithShim(browserPlatformShim);
export default Yargs;

2920
node_modules/gulp-cli/node_modules/yargs/build/index.cjs generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,62 @@
import { YError } from './yerror.js';
import { parseCommand } from './parse-command.js';
const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];
export function argsert(arg1, arg2, arg3) {
function parseArgs() {
return typeof arg1 === 'object'
? [{ demanded: [], optional: [] }, arg1, arg2]
: [
parseCommand(`cmd ${arg1}`),
arg2,
arg3,
];
}
try {
let position = 0;
const [parsed, callerArguments, _length] = parseArgs();
const args = [].slice.call(callerArguments);
while (args.length && args[args.length - 1] === undefined)
args.pop();
const length = _length || args.length;
if (length < parsed.demanded.length) {
throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`);
}
const totalCommands = parsed.demanded.length + parsed.optional.length;
if (length > totalCommands) {
throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`);
}
parsed.demanded.forEach(demanded => {
const arg = args.shift();
const observedType = guessType(arg);
const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*');
if (matchingTypes.length === 0)
argumentTypeError(observedType, demanded.cmd, position);
position += 1;
});
parsed.optional.forEach(optional => {
if (args.length === 0)
return;
const arg = args.shift();
const observedType = guessType(arg);
const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*');
if (matchingTypes.length === 0)
argumentTypeError(observedType, optional.cmd, position);
position += 1;
});
}
catch (err) {
console.warn(err.stack);
}
}
function guessType(arg) {
if (Array.isArray(arg)) {
return 'array';
}
else if (arg === null) {
return 'null';
}
return typeof arg;
}
function argumentTypeError(observedType, allowedTypes, position) {
throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`);
}

View File

@@ -0,0 +1,382 @@
import { assertNotStrictEqual, } from './typings/common-types.js';
import { isPromise } from './utils/is-promise.js';
import { applyMiddleware, commandMiddlewareFactory, } from './middleware.js';
import { parseCommand } from './parse-command.js';
import { isYargsInstance, } from './yargs-factory.js';
import whichModule from './utils/which-module.js';
const DEFAULT_MARKER = /(^\*)|(^\$0)/;
export function command(yargs, usage, validation, globalMiddleware = [], shim) {
const self = {};
let handlers = {};
let aliasMap = {};
let defaultCommand;
self.addHandler = function addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) {
let aliases = [];
const middlewares = commandMiddlewareFactory(commandMiddleware);
handler = handler || (() => { });
if (Array.isArray(cmd)) {
if (isCommandAndAliases(cmd)) {
[cmd, ...aliases] = cmd;
}
else {
for (const command of cmd) {
self.addHandler(command);
}
}
}
else if (isCommandHandlerDefinition(cmd)) {
let command = Array.isArray(cmd.command) || typeof cmd.command === 'string'
? cmd.command
: moduleName(cmd);
if (cmd.aliases)
command = [].concat(command).concat(cmd.aliases);
self.addHandler(command, extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated);
return;
}
else if (isCommandBuilderDefinition(builder)) {
self.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated);
return;
}
if (typeof cmd === 'string') {
const parsedCommand = parseCommand(cmd);
aliases = aliases.map(alias => parseCommand(alias).cmd);
let isDefault = false;
const parsedAliases = [parsedCommand.cmd].concat(aliases).filter(c => {
if (DEFAULT_MARKER.test(c)) {
isDefault = true;
return false;
}
return true;
});
if (parsedAliases.length === 0 && isDefault)
parsedAliases.push('$0');
if (isDefault) {
parsedCommand.cmd = parsedAliases[0];
aliases = parsedAliases.slice(1);
cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd);
}
aliases.forEach(alias => {
aliasMap[alias] = parsedCommand.cmd;
});
if (description !== false) {
usage.command(cmd, description, isDefault, aliases, deprecated);
}
handlers[parsedCommand.cmd] = {
original: cmd,
description,
handler,
builder: builder || {},
middlewares,
deprecated,
demanded: parsedCommand.demanded,
optional: parsedCommand.optional,
};
if (isDefault)
defaultCommand = handlers[parsedCommand.cmd];
}
};
self.addDirectory = function addDirectory(dir, context, req, callerFile, opts) {
opts = opts || {};
if (typeof opts.recurse !== 'boolean')
opts.recurse = false;
if (!Array.isArray(opts.extensions))
opts.extensions = ['js'];
const parentVisit = typeof opts.visit === 'function' ? opts.visit : (o) => o;
opts.visit = function visit(obj, joined, filename) {
const visited = parentVisit(obj, joined, filename);
if (visited) {
if (~context.files.indexOf(joined))
return visited;
context.files.push(joined);
self.addHandler(visited);
}
return visited;
};
shim.requireDirectory({ require: req, filename: callerFile }, dir, opts);
};
function moduleName(obj) {
const mod = whichModule(obj);
if (!mod)
throw new Error(`No command name given for module: ${shim.inspect(obj)}`);
return commandFromFilename(mod.filename);
}
function commandFromFilename(filename) {
return shim.path.basename(filename, shim.path.extname(filename));
}
function extractDesc({ describe, description, desc, }) {
for (const test of [describe, description, desc]) {
if (typeof test === 'string' || test === false)
return test;
assertNotStrictEqual(test, true, shim);
}
return false;
}
self.getCommands = () => Object.keys(handlers).concat(Object.keys(aliasMap));
self.getCommandHandlers = () => handlers;
self.hasDefaultCommand = () => !!defaultCommand;
self.runCommand = function runCommand(command, yargs, parsed, commandIndex) {
let aliases = parsed.aliases;
const commandHandler = handlers[command] || handlers[aliasMap[command]] || defaultCommand;
const currentContext = yargs.getContext();
let numFiles = currentContext.files.length;
const parentCommands = currentContext.commands.slice();
let innerArgv = parsed.argv;
let positionalMap = {};
if (command) {
currentContext.commands.push(command);
currentContext.fullCommands.push(commandHandler.original);
}
const builder = commandHandler.builder;
if (isCommandBuilderCallback(builder)) {
const builderOutput = builder(yargs.reset(parsed.aliases));
const innerYargs = isYargsInstance(builderOutput) ? builderOutput : yargs;
if (shouldUpdateUsage(innerYargs)) {
innerYargs
.getUsageInstance()
.usage(usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description);
}
innerArgv = innerYargs._parseArgs(null, null, true, commandIndex);
aliases = innerYargs.parsed.aliases;
}
else if (isCommandBuilderOptionDefinitions(builder)) {
const innerYargs = yargs.reset(parsed.aliases);
if (shouldUpdateUsage(innerYargs)) {
innerYargs
.getUsageInstance()
.usage(usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description);
}
Object.keys(commandHandler.builder).forEach(key => {
innerYargs.option(key, builder[key]);
});
innerArgv = innerYargs._parseArgs(null, null, true, commandIndex);
aliases = innerYargs.parsed.aliases;
}
if (!yargs._hasOutput()) {
positionalMap = populatePositionals(commandHandler, innerArgv, currentContext);
}
const middlewares = globalMiddleware
.slice(0)
.concat(commandHandler.middlewares);
applyMiddleware(innerArgv, yargs, middlewares, true);
if (!yargs._hasOutput()) {
yargs._runValidation(innerArgv, aliases, positionalMap, yargs.parsed.error, !command);
}
if (commandHandler.handler && !yargs._hasOutput()) {
yargs._setHasOutput();
const populateDoubleDash = !!yargs.getOptions().configuration['populate--'];
yargs._postProcess(innerArgv, populateDoubleDash);
innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false);
let handlerResult;
if (isPromise(innerArgv)) {
handlerResult = innerArgv.then(argv => commandHandler.handler(argv));
}
else {
handlerResult = commandHandler.handler(innerArgv);
}
const handlerFinishCommand = yargs.getHandlerFinishCommand();
if (isPromise(handlerResult)) {
yargs.getUsageInstance().cacheHelpMessage();
handlerResult
.then(value => {
if (handlerFinishCommand) {
handlerFinishCommand(value);
}
})
.catch(error => {
try {
yargs.getUsageInstance().fail(null, error);
}
catch (err) {
}
})
.then(() => {
yargs.getUsageInstance().clearCachedHelpMessage();
});
}
else {
if (handlerFinishCommand) {
handlerFinishCommand(handlerResult);
}
}
}
if (command) {
currentContext.commands.pop();
currentContext.fullCommands.pop();
}
numFiles = currentContext.files.length - numFiles;
if (numFiles > 0)
currentContext.files.splice(numFiles * -1, numFiles);
return innerArgv;
};
function shouldUpdateUsage(yargs) {
return (!yargs.getUsageInstance().getUsageDisabled() &&
yargs.getUsageInstance().getUsage().length === 0);
}
function usageFromParentCommandsCommandHandler(parentCommands, commandHandler) {
const c = DEFAULT_MARKER.test(commandHandler.original)
? commandHandler.original.replace(DEFAULT_MARKER, '').trim()
: commandHandler.original;
const pc = parentCommands.filter(c => {
return !DEFAULT_MARKER.test(c);
});
pc.push(c);
return `$0 ${pc.join(' ')}`;
}
self.runDefaultBuilderOn = function (yargs) {
assertNotStrictEqual(defaultCommand, undefined, shim);
if (shouldUpdateUsage(yargs)) {
const commandString = DEFAULT_MARKER.test(defaultCommand.original)
? defaultCommand.original
: defaultCommand.original.replace(/^[^[\]<>]*/, '$0 ');
yargs.getUsageInstance().usage(commandString, defaultCommand.description);
}
const builder = defaultCommand.builder;
if (isCommandBuilderCallback(builder)) {
builder(yargs);
}
else if (!isCommandBuilderDefinition(builder)) {
Object.keys(builder).forEach(key => {
yargs.option(key, builder[key]);
});
}
};
function populatePositionals(commandHandler, argv, context) {
argv._ = argv._.slice(context.commands.length);
const demanded = commandHandler.demanded.slice(0);
const optional = commandHandler.optional.slice(0);
const positionalMap = {};
validation.positionalCount(demanded.length, argv._.length);
while (demanded.length) {
const demand = demanded.shift();
populatePositional(demand, argv, positionalMap);
}
while (optional.length) {
const maybe = optional.shift();
populatePositional(maybe, argv, positionalMap);
}
argv._ = context.commands.concat(argv._.map(a => '' + a));
postProcessPositionals(argv, positionalMap, self.cmdToParseOptions(commandHandler.original));
return positionalMap;
}
function populatePositional(positional, argv, positionalMap) {
const cmd = positional.cmd[0];
if (positional.variadic) {
positionalMap[cmd] = argv._.splice(0).map(String);
}
else {
if (argv._.length)
positionalMap[cmd] = [String(argv._.shift())];
}
}
function postProcessPositionals(argv, positionalMap, parseOptions) {
const options = Object.assign({}, yargs.getOptions());
options.default = Object.assign(parseOptions.default, options.default);
for (const key of Object.keys(parseOptions.alias)) {
options.alias[key] = (options.alias[key] || []).concat(parseOptions.alias[key]);
}
options.array = options.array.concat(parseOptions.array);
options.config = {};
const unparsed = [];
Object.keys(positionalMap).forEach(key => {
positionalMap[key].map(value => {
if (options.configuration['unknown-options-as-args'])
options.key[key] = true;
unparsed.push(`--${key}`);
unparsed.push(value);
});
});
if (!unparsed.length)
return;
const config = Object.assign({}, options.configuration, {
'populate--': true,
});
const parsed = shim.Parser.detailed(unparsed, Object.assign({}, options, {
configuration: config,
}));
if (parsed.error) {
yargs.getUsageInstance().fail(parsed.error.message, parsed.error);
}
else {
const positionalKeys = Object.keys(positionalMap);
Object.keys(positionalMap).forEach(key => {
positionalKeys.push(...parsed.aliases[key]);
});
Object.keys(parsed.argv).forEach(key => {
if (positionalKeys.indexOf(key) !== -1) {
if (!positionalMap[key])
positionalMap[key] = parsed.argv[key];
argv[key] = parsed.argv[key];
}
});
}
}
self.cmdToParseOptions = function (cmdString) {
const parseOptions = {
array: [],
default: {},
alias: {},
demand: {},
};
const parsed = parseCommand(cmdString);
parsed.demanded.forEach(d => {
const [cmd, ...aliases] = d.cmd;
if (d.variadic) {
parseOptions.array.push(cmd);
parseOptions.default[cmd] = [];
}
parseOptions.alias[cmd] = aliases;
parseOptions.demand[cmd] = true;
});
parsed.optional.forEach(o => {
const [cmd, ...aliases] = o.cmd;
if (o.variadic) {
parseOptions.array.push(cmd);
parseOptions.default[cmd] = [];
}
parseOptions.alias[cmd] = aliases;
});
return parseOptions;
};
self.reset = () => {
handlers = {};
aliasMap = {};
defaultCommand = undefined;
return self;
};
const frozens = [];
self.freeze = () => {
frozens.push({
handlers,
aliasMap,
defaultCommand,
});
};
self.unfreeze = () => {
const frozen = frozens.pop();
assertNotStrictEqual(frozen, undefined, shim);
({ handlers, aliasMap, defaultCommand } = frozen);
};
return self;
}
export function isCommandBuilderDefinition(builder) {
return (typeof builder === 'object' &&
!!builder.builder &&
typeof builder.handler === 'function');
}
function isCommandAndAliases(cmd) {
if (cmd.every(c => typeof c === 'string')) {
return true;
}
else {
return false;
}
}
export function isCommandBuilderCallback(builder) {
return typeof builder === 'function';
}
function isCommandBuilderOptionDefinitions(builder) {
return typeof builder === 'object';
}
export function isCommandHandlerDefinition(cmd) {
return typeof cmd === 'object' && !Array.isArray(cmd);
}

View File

@@ -0,0 +1,47 @@
export const completionShTemplate = `###-begin-{{app_name}}-completions-###
#
# yargs command completion script
#
# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc
# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.
#
_yargs_completions()
{
local cur_word args type_list
cur_word="\${COMP_WORDS[COMP_CWORD]}"
args=("\${COMP_WORDS[@]}")
# ask yargs to generate completions.
type_list=$({{app_path}} --get-yargs-completions "\${args[@]}")
COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) )
# if no match was found, fall back to filename completion
if [ \${#COMPREPLY[@]} -eq 0 ]; then
COMPREPLY=()
fi
return 0
}
complete -o default -F _yargs_completions {{app_name}}
###-end-{{app_name}}-completions-###
`;
export const completionZshTemplate = `###-begin-{{app_name}}-completions-###
#
# yargs command completion script
#
# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc
# or {{app_path}} {{completion_command}} >> ~/.zsh_profile on OSX.
#
_{{app_name}}_yargs_completions()
{
local reply
local si=$IFS
IFS=$'\n' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}"))
IFS=$si
_describe 'values' reply
}
compdef _{{app_name}}_yargs_completions {{app_name}}
###-end-{{app_name}}-completions-###
`;

View File

@@ -0,0 +1,128 @@
import { isCommandBuilderCallback } from './command.js';
import { assertNotStrictEqual } from './typings/common-types.js';
import * as templates from './completion-templates.js';
import { isPromise } from './utils/is-promise.js';
import { parseCommand } from './parse-command.js';
export function completion(yargs, usage, command, shim) {
const self = {
completionKey: 'get-yargs-completions',
};
let aliases;
self.setParsed = function setParsed(parsed) {
aliases = parsed.aliases;
};
const zshShell = (shim.getEnv('SHELL') && shim.getEnv('SHELL').indexOf('zsh') !== -1) ||
(shim.getEnv('ZSH_NAME') && shim.getEnv('ZSH_NAME').indexOf('zsh') !== -1);
self.getCompletion = function getCompletion(args, done) {
const completions = [];
const current = args.length ? args[args.length - 1] : '';
const argv = yargs.parse(args, true);
const parentCommands = yargs.getContext().commands;
function runCompletionFunction(argv) {
assertNotStrictEqual(completionFunction, null, shim);
if (isSyncCompletionFunction(completionFunction)) {
const result = completionFunction(current, argv);
if (isPromise(result)) {
return result
.then(list => {
shim.process.nextTick(() => {
done(list);
});
})
.catch(err => {
shim.process.nextTick(() => {
throw err;
});
});
}
return done(result);
}
else {
return completionFunction(current, argv, completions => {
done(completions);
});
}
}
if (completionFunction) {
return isPromise(argv)
? argv.then(runCompletionFunction)
: runCompletionFunction(argv);
}
const handlers = command.getCommandHandlers();
for (let i = 0, ii = args.length; i < ii; ++i) {
if (handlers[args[i]] && handlers[args[i]].builder) {
const builder = handlers[args[i]].builder;
if (isCommandBuilderCallback(builder)) {
const y = yargs.reset();
builder(y);
return y.argv;
}
}
}
if (!current.match(/^-/) &&
parentCommands[parentCommands.length - 1] !== current) {
usage.getCommands().forEach(usageCommand => {
const commandName = parseCommand(usageCommand[0]).cmd;
if (args.indexOf(commandName) === -1) {
if (!zshShell) {
completions.push(commandName);
}
else {
const desc = usageCommand[1] || '';
completions.push(commandName.replace(/:/g, '\\:') + ':' + desc);
}
}
});
}
if (current.match(/^-/) || (current === '' && completions.length === 0)) {
const descs = usage.getDescriptions();
const options = yargs.getOptions();
Object.keys(options.key).forEach(key => {
const negable = !!options.configuration['boolean-negation'] &&
options.boolean.includes(key);
let keyAndAliases = [key].concat(aliases[key] || []);
if (negable)
keyAndAliases = keyAndAliases.concat(keyAndAliases.map(key => `no-${key}`));
function completeOptionKey(key) {
const notInArgs = keyAndAliases.every(val => args.indexOf(`--${val}`) === -1);
if (notInArgs) {
const startsByTwoDashes = (s) => /^--/.test(s);
const isShortOption = (s) => /^[^0-9]$/.test(s);
const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--';
if (!zshShell) {
completions.push(dashes + key);
}
else {
const desc = descs[key] || '';
completions.push(dashes +
`${key.replace(/:/g, '\\:')}:${desc.replace('__yargsString__:', '')}`);
}
}
}
completeOptionKey(key);
if (negable && !!options.default[key])
completeOptionKey(`no-${key}`);
});
}
done(completions);
};
self.generateCompletionScript = function generateCompletionScript($0, cmd) {
let script = zshShell
? templates.completionZshTemplate
: templates.completionShTemplate;
const name = shim.path.basename($0);
if ($0.match(/\.js$/))
$0 = `./${$0}`;
script = script.replace(/{{app_name}}/g, name);
script = script.replace(/{{completion_command}}/g, cmd);
return script.replace(/{{app_path}}/g, $0);
};
let completionFunction = null;
self.registerFunction = fn => {
completionFunction = fn;
};
return self;
}
function isSyncCompletionFunction(completionFunction) {
return completionFunction.length < 3;
}

View File

@@ -0,0 +1,53 @@
import { argsert } from './argsert.js';
import { isPromise } from './utils/is-promise.js';
export function globalMiddlewareFactory(globalMiddleware, context) {
return function (callback, applyBeforeValidation = false) {
argsert('<array|function> [boolean]', [callback, applyBeforeValidation], arguments.length);
if (Array.isArray(callback)) {
for (let i = 0; i < callback.length; i++) {
if (typeof callback[i] !== 'function') {
throw Error('middleware must be a function');
}
callback[i].applyBeforeValidation = applyBeforeValidation;
}
Array.prototype.push.apply(globalMiddleware, callback);
}
else if (typeof callback === 'function') {
callback.applyBeforeValidation = applyBeforeValidation;
globalMiddleware.push(callback);
}
return context;
};
}
export function commandMiddlewareFactory(commandMiddleware) {
if (!commandMiddleware)
return [];
return commandMiddleware.map(middleware => {
middleware.applyBeforeValidation = false;
return middleware;
});
}
export function applyMiddleware(argv, yargs, middlewares, beforeValidation) {
const beforeValidationError = new Error('middleware cannot return a promise when applyBeforeValidation is true');
return middlewares.reduce((acc, middleware) => {
if (middleware.applyBeforeValidation !== beforeValidation) {
return acc;
}
if (isPromise(acc)) {
return acc
.then(initialObj => Promise.all([
initialObj,
middleware(initialObj, yargs),
]))
.then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj));
}
else {
const result = middleware(acc, yargs);
if (beforeValidation && isPromise(result))
throw beforeValidationError;
return isPromise(result)
? result.then(middlewareObj => Object.assign(acc, middlewareObj))
: Object.assign(acc, result);
}
}, argv);
}

View File

@@ -0,0 +1,32 @@
export function parseCommand(cmd) {
const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' ');
const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/);
const bregex = /\.*[\][<>]/g;
const firstCommand = splitCommand.shift();
if (!firstCommand)
throw new Error(`No command found in: ${cmd}`);
const parsedCommand = {
cmd: firstCommand.replace(bregex, ''),
demanded: [],
optional: [],
};
splitCommand.forEach((cmd, i) => {
let variadic = false;
cmd = cmd.replace(/\s/g, '');
if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1)
variadic = true;
if (/^\[/.test(cmd)) {
parsedCommand.optional.push({
cmd: cmd.replace(bregex, '').split('|'),
variadic,
});
}
else {
parsedCommand.demanded.push({
cmd: cmd.replace(bregex, '').split('|'),
variadic,
});
}
});
return parsedCommand;
}

View File

@@ -0,0 +1,9 @@
export function assertNotStrictEqual(actual, expected, shim, message) {
shim.assert.notStrictEqual(actual, expected, message);
}
export function assertSingleKey(actual, shim) {
shim.assert.strictEqual(typeof actual, 'string');
}
export function objectKeys(object) {
return Object.keys(object);
}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,548 @@
import { assertNotStrictEqual, } from './typings/common-types.js';
import { objFilter } from './utils/obj-filter.js';
import { YError } from './yerror.js';
import setBlocking from './utils/set-blocking.js';
export function usage(yargs, y18n, shim) {
const __ = y18n.__;
const self = {};
const fails = [];
self.failFn = function failFn(f) {
fails.push(f);
};
let failMessage = null;
let showHelpOnFail = true;
self.showHelpOnFail = function showHelpOnFailFn(arg1 = true, arg2) {
function parseFunctionArgs() {
return typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2];
}
const [enabled, message] = parseFunctionArgs();
failMessage = message;
showHelpOnFail = enabled;
return self;
};
let failureOutput = false;
self.fail = function fail(msg, err) {
const logger = yargs._getLoggerInstance();
if (fails.length) {
for (let i = fails.length - 1; i >= 0; --i) {
fails[i](msg, err, self);
}
}
else {
if (yargs.getExitProcess())
setBlocking(true);
if (!failureOutput) {
failureOutput = true;
if (showHelpOnFail) {
yargs.showHelp('error');
logger.error();
}
if (msg || err)
logger.error(msg || err);
if (failMessage) {
if (msg || err)
logger.error('');
logger.error(failMessage);
}
}
err = err || new YError(msg);
if (yargs.getExitProcess()) {
return yargs.exit(1);
}
else if (yargs._hasParseCallback()) {
return yargs.exit(1, err);
}
else {
throw err;
}
}
};
let usages = [];
let usageDisabled = false;
self.usage = (msg, description) => {
if (msg === null) {
usageDisabled = true;
usages = [];
return self;
}
usageDisabled = false;
usages.push([msg, description || '']);
return self;
};
self.getUsage = () => {
return usages;
};
self.getUsageDisabled = () => {
return usageDisabled;
};
self.getPositionalGroupName = () => {
return __('Positionals:');
};
let examples = [];
self.example = (cmd, description) => {
examples.push([cmd, description || '']);
};
let commands = [];
self.command = function command(cmd, description, isDefault, aliases, deprecated = false) {
if (isDefault) {
commands = commands.map(cmdArray => {
cmdArray[2] = false;
return cmdArray;
});
}
commands.push([cmd, description || '', isDefault, aliases, deprecated]);
};
self.getCommands = () => commands;
let descriptions = {};
self.describe = function describe(keyOrKeys, desc) {
if (Array.isArray(keyOrKeys)) {
keyOrKeys.forEach(k => {
self.describe(k, desc);
});
}
else if (typeof keyOrKeys === 'object') {
Object.keys(keyOrKeys).forEach(k => {
self.describe(k, keyOrKeys[k]);
});
}
else {
descriptions[keyOrKeys] = desc;
}
};
self.getDescriptions = () => descriptions;
let epilogs = [];
self.epilog = msg => {
epilogs.push(msg);
};
let wrapSet = false;
let wrap;
self.wrap = cols => {
wrapSet = true;
wrap = cols;
};
function getWrap() {
if (!wrapSet) {
wrap = windowWidth();
wrapSet = true;
}
return wrap;
}
const deferY18nLookupPrefix = '__yargsString__:';
self.deferY18nLookup = str => deferY18nLookupPrefix + str;
self.help = function help() {
if (cachedHelpMessage)
return cachedHelpMessage;
normalizeAliases();
const base$0 = yargs.customScriptName
? yargs.$0
: shim.path.basename(yargs.$0);
const demandedOptions = yargs.getDemandedOptions();
const demandedCommands = yargs.getDemandedCommands();
const deprecatedOptions = yargs.getDeprecatedOptions();
const groups = yargs.getGroups();
const options = yargs.getOptions();
let keys = [];
keys = keys.concat(Object.keys(descriptions));
keys = keys.concat(Object.keys(demandedOptions));
keys = keys.concat(Object.keys(demandedCommands));
keys = keys.concat(Object.keys(options.default));
keys = keys.filter(filterHiddenOptions);
keys = Object.keys(keys.reduce((acc, key) => {
if (key !== '_')
acc[key] = true;
return acc;
}, {}));
const theWrap = getWrap();
const ui = shim.cliui({
width: theWrap,
wrap: !!theWrap,
});
if (!usageDisabled) {
if (usages.length) {
usages.forEach(usage => {
ui.div(`${usage[0].replace(/\$0/g, base$0)}`);
if (usage[1]) {
ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] });
}
});
ui.div();
}
else if (commands.length) {
let u = null;
if (demandedCommands._) {
u = `${base$0} <${__('command')}>\n`;
}
else {
u = `${base$0} [${__('command')}]\n`;
}
ui.div(`${u}`);
}
}
if (commands.length) {
ui.div(__('Commands:'));
const context = yargs.getContext();
const parentCommands = context.commands.length
? `${context.commands.join(' ')} `
: '';
if (yargs.getParserConfiguration()['sort-commands'] === true) {
commands = commands.sort((a, b) => a[0].localeCompare(b[0]));
}
commands.forEach(command => {
const commandString = `${base$0} ${parentCommands}${command[0].replace(/^\$0 ?/, '')}`;
ui.span({
text: commandString,
padding: [0, 2, 0, 2],
width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4,
}, { text: command[1] });
const hints = [];
if (command[2])
hints.push(`[${__('default')}]`);
if (command[3] && command[3].length) {
hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`);
}
if (command[4]) {
if (typeof command[4] === 'string') {
hints.push(`[${__('deprecated: %s', command[4])}]`);
}
else {
hints.push(`[${__('deprecated')}]`);
}
}
if (hints.length) {
ui.div({
text: hints.join(' '),
padding: [0, 0, 0, 2],
align: 'right',
});
}
else {
ui.div();
}
});
ui.div();
}
const aliasKeys = (Object.keys(options.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []);
keys = keys.filter(key => !yargs.parsed.newAliases[key] &&
aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1));
const defaultGroup = __('Options:');
if (!groups[defaultGroup])
groups[defaultGroup] = [];
addUngroupedKeys(keys, options.alias, groups, defaultGroup);
const isLongSwitch = (sw) => /^--/.test(getText(sw));
const displayedGroups = Object.keys(groups)
.filter(groupName => groups[groupName].length > 0)
.map(groupName => {
const normalizedKeys = groups[groupName]
.filter(filterHiddenOptions)
.map(key => {
if (~aliasKeys.indexOf(key))
return key;
for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) {
if (~(options.alias[aliasKey] || []).indexOf(key))
return aliasKey;
}
return key;
});
return { groupName, normalizedKeys };
})
.filter(({ normalizedKeys }) => normalizedKeys.length > 0)
.map(({ groupName, normalizedKeys }) => {
const switches = normalizedKeys.reduce((acc, key) => {
acc[key] = [key]
.concat(options.alias[key] || [])
.map(sw => {
if (groupName === self.getPositionalGroupName())
return sw;
else {
return ((/^[0-9]$/.test(sw)
? ~options.boolean.indexOf(key)
? '-'
: '--'
: sw.length > 1
? '--'
: '-') + sw);
}
})
.sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2)
? 0
: isLongSwitch(sw1)
? 1
: -1)
.join(', ');
return acc;
}, {});
return { groupName, normalizedKeys, switches };
});
const shortSwitchesUsed = displayedGroups
.filter(({ groupName }) => groupName !== self.getPositionalGroupName())
.some(({ normalizedKeys, switches }) => !normalizedKeys.every(key => isLongSwitch(switches[key])));
if (shortSwitchesUsed) {
displayedGroups
.filter(({ groupName }) => groupName !== self.getPositionalGroupName())
.forEach(({ normalizedKeys, switches }) => {
normalizedKeys.forEach(key => {
if (isLongSwitch(switches[key])) {
switches[key] = addIndentation(switches[key], '-x, '.length);
}
});
});
}
displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => {
ui.div(groupName);
normalizedKeys.forEach(key => {
const kswitch = switches[key];
let desc = descriptions[key] || '';
let type = null;
if (~desc.lastIndexOf(deferY18nLookupPrefix))
desc = __(desc.substring(deferY18nLookupPrefix.length));
if (~options.boolean.indexOf(key))
type = `[${__('boolean')}]`;
if (~options.count.indexOf(key))
type = `[${__('count')}]`;
if (~options.string.indexOf(key))
type = `[${__('string')}]`;
if (~options.normalize.indexOf(key))
type = `[${__('string')}]`;
if (~options.array.indexOf(key))
type = `[${__('array')}]`;
if (~options.number.indexOf(key))
type = `[${__('number')}]`;
const deprecatedExtra = (deprecated) => typeof deprecated === 'string'
? `[${__('deprecated: %s', deprecated)}]`
: `[${__('deprecated')}]`;
const extra = [
key in deprecatedOptions
? deprecatedExtra(deprecatedOptions[key])
: null,
type,
key in demandedOptions ? `[${__('required')}]` : null,
options.choices && options.choices[key]
? `[${__('choices:')} ${self.stringifiedValues(options.choices[key])}]`
: null,
defaultString(options.default[key], options.defaultDescription[key]),
]
.filter(Boolean)
.join(' ');
ui.span({
text: getText(kswitch),
padding: [0, 2, 0, 2 + getIndentation(kswitch)],
width: maxWidth(switches, theWrap) + 4,
}, desc);
if (extra)
ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' });
else
ui.div();
});
ui.div();
});
if (examples.length) {
ui.div(__('Examples:'));
examples.forEach(example => {
example[0] = example[0].replace(/\$0/g, base$0);
});
examples.forEach(example => {
if (example[1] === '') {
ui.div({
text: example[0],
padding: [0, 2, 0, 2],
});
}
else {
ui.div({
text: example[0],
padding: [0, 2, 0, 2],
width: maxWidth(examples, theWrap) + 4,
}, {
text: example[1],
});
}
});
ui.div();
}
if (epilogs.length > 0) {
const e = epilogs
.map(epilog => epilog.replace(/\$0/g, base$0))
.join('\n');
ui.div(`${e}\n`);
}
return ui.toString().replace(/\s*$/, '');
};
function maxWidth(table, theWrap, modifier) {
let width = 0;
if (!Array.isArray(table)) {
table = Object.values(table).map(v => [v]);
}
table.forEach(v => {
width = Math.max(shim.stringWidth(modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])) + getIndentation(v[0]), width);
});
if (theWrap)
width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10));
return width;
}
function normalizeAliases() {
const demandedOptions = yargs.getDemandedOptions();
const options = yargs.getOptions();
(Object.keys(options.alias) || []).forEach(key => {
options.alias[key].forEach(alias => {
if (descriptions[alias])
self.describe(key, descriptions[alias]);
if (alias in demandedOptions)
yargs.demandOption(key, demandedOptions[alias]);
if (~options.boolean.indexOf(alias))
yargs.boolean(key);
if (~options.count.indexOf(alias))
yargs.count(key);
if (~options.string.indexOf(alias))
yargs.string(key);
if (~options.normalize.indexOf(alias))
yargs.normalize(key);
if (~options.array.indexOf(alias))
yargs.array(key);
if (~options.number.indexOf(alias))
yargs.number(key);
});
});
}
let cachedHelpMessage;
self.cacheHelpMessage = function () {
cachedHelpMessage = this.help();
};
self.clearCachedHelpMessage = function () {
cachedHelpMessage = undefined;
};
function addUngroupedKeys(keys, aliases, groups, defaultGroup) {
let groupedKeys = [];
let toCheck = null;
Object.keys(groups).forEach(group => {
groupedKeys = groupedKeys.concat(groups[group]);
});
keys.forEach(key => {
toCheck = [key].concat(aliases[key]);
if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) {
groups[defaultGroup].push(key);
}
});
return groupedKeys;
}
function filterHiddenOptions(key) {
return (yargs.getOptions().hiddenOptions.indexOf(key) < 0 ||
yargs.parsed.argv[yargs.getOptions().showHiddenOpt]);
}
self.showHelp = (level) => {
const logger = yargs._getLoggerInstance();
if (!level)
level = 'error';
const emit = typeof level === 'function' ? level : logger[level];
emit(self.help());
};
self.functionDescription = fn => {
const description = fn.name
? shim.Parser.decamelize(fn.name, '-')
: __('generated-value');
return ['(', description, ')'].join('');
};
self.stringifiedValues = function stringifiedValues(values, separator) {
let string = '';
const sep = separator || ', ';
const array = [].concat(values);
if (!values || !array.length)
return string;
array.forEach(value => {
if (string.length)
string += sep;
string += JSON.stringify(value);
});
return string;
};
function defaultString(value, defaultDescription) {
let string = `[${__('default:')} `;
if (value === undefined && !defaultDescription)
return null;
if (defaultDescription) {
string += defaultDescription;
}
else {
switch (typeof value) {
case 'string':
string += `"${value}"`;
break;
case 'object':
string += JSON.stringify(value);
break;
default:
string += value;
}
}
return `${string}]`;
}
function windowWidth() {
const maxWidth = 80;
if (shim.process.stdColumns) {
return Math.min(maxWidth, shim.process.stdColumns);
}
else {
return maxWidth;
}
}
let version = null;
self.version = ver => {
version = ver;
};
self.showVersion = () => {
const logger = yargs._getLoggerInstance();
logger.log(version);
};
self.reset = function reset(localLookup) {
failMessage = null;
failureOutput = false;
usages = [];
usageDisabled = false;
epilogs = [];
examples = [];
commands = [];
descriptions = objFilter(descriptions, k => !localLookup[k]);
return self;
};
const frozens = [];
self.freeze = function freeze() {
frozens.push({
failMessage,
failureOutput,
usages,
usageDisabled,
epilogs,
examples,
commands,
descriptions,
});
};
self.unfreeze = function unfreeze() {
const frozen = frozens.pop();
assertNotStrictEqual(frozen, undefined, shim);
({
failMessage,
failureOutput,
usages,
usageDisabled,
epilogs,
examples,
commands,
descriptions,
} = frozen);
};
return self;
}
function isIndentedText(text) {
return typeof text === 'object';
}
function addIndentation(text, indent) {
return isIndentedText(text)
? { text: text.text, indentation: text.indentation + indent }
: { text, indentation: indent };
}
function getIndentation(text) {
return isIndentedText(text) ? text.indentation : 0;
}
function getText(text) {
return isIndentedText(text) ? text.text : text;
}

View File

@@ -0,0 +1,59 @@
import { YError } from '../yerror.js';
let previouslyVisitedConfigs = [];
let shim;
export function applyExtends(config, cwd, mergeExtends, _shim) {
shim = _shim;
let defaultConfig = {};
if (Object.prototype.hasOwnProperty.call(config, 'extends')) {
if (typeof config.extends !== 'string')
return defaultConfig;
const isPath = /\.json|\..*rc$/.test(config.extends);
let pathToDefault = null;
if (!isPath) {
try {
pathToDefault = require.resolve(config.extends);
}
catch (_err) {
return config;
}
}
else {
pathToDefault = getPathToDefaultConfig(cwd, config.extends);
}
checkForCircularExtends(pathToDefault);
previouslyVisitedConfigs.push(pathToDefault);
defaultConfig = isPath
? JSON.parse(shim.readFileSync(pathToDefault, 'utf8'))
: require(config.extends);
delete config.extends;
defaultConfig = applyExtends(defaultConfig, shim.path.dirname(pathToDefault), mergeExtends, shim);
}
previouslyVisitedConfigs = [];
return mergeExtends
? mergeDeep(defaultConfig, config)
: Object.assign({}, defaultConfig, config);
}
function checkForCircularExtends(cfgPath) {
if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) {
throw new YError(`Circular extended configurations: '${cfgPath}'.`);
}
}
function getPathToDefaultConfig(cwd, pathToExtend) {
return shim.path.resolve(cwd, pathToExtend);
}
function mergeDeep(config1, config2) {
const target = {};
function isObject(obj) {
return obj && typeof obj === 'object' && !Array.isArray(obj);
}
Object.assign(target, config1);
for (const key of Object.keys(config2)) {
if (isObject(config2[key]) && isObject(target[key])) {
target[key] = mergeDeep(config1[key], config2[key]);
}
else {
target[key] = config2[key];
}
}
return target;
}

View File

@@ -0,0 +1,5 @@
export function isPromise(maybePromise) {
return (!!maybePromise &&
!!maybePromise.then &&
typeof maybePromise.then === 'function');
}

View File

@@ -0,0 +1,26 @@
export function levenshtein(a, b) {
if (a.length === 0)
return b.length;
if (b.length === 0)
return a.length;
const matrix = [];
let i;
for (i = 0; i <= b.length; i++) {
matrix[i] = [i];
}
let j;
for (j = 0; j <= a.length; j++) {
matrix[0][j] = j;
}
for (i = 1; i <= b.length; i++) {
for (j = 1; j <= a.length; j++) {
if (b.charAt(i - 1) === a.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1];
}
else {
matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1));
}
}
}
return matrix[b.length][a.length];
}

View File

@@ -0,0 +1,10 @@
import { objectKeys } from '../typings/common-types.js';
export function objFilter(original = {}, filter = () => true) {
const obj = {};
objectKeys(original).forEach(key => {
if (filter(key, original[key])) {
obj[key] = original[key];
}
});
return obj;
}

View File

@@ -0,0 +1,17 @@
function getProcessArgvBinIndex() {
if (isBundledElectronApp())
return 0;
return 1;
}
function isBundledElectronApp() {
return isElectronApp() && !process.defaultApp;
}
function isElectronApp() {
return !!process.versions.electron;
}
export function hideBin(argv) {
return argv.slice(getProcessArgvBinIndex() + 1);
}
export function getProcessArgvBin() {
return process.argv[getProcessArgvBinIndex()];
}

View File

@@ -0,0 +1,12 @@
export default function setBlocking(blocking) {
if (typeof process === 'undefined')
return;
[process.stdout, process.stderr].forEach(_stream => {
const stream = _stream;
if (stream._handle &&
stream.isTTY &&
typeof stream._handle.setBlocking === 'function') {
stream._handle.setBlocking(blocking);
}
});
}

View File

@@ -0,0 +1,10 @@
export default function whichModule(exported) {
if (typeof require === 'undefined')
return null;
for (let i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) {
mod = require.cache[files[i]];
if (mod.exports === exported)
return mod;
}
return null;
}

View File

@@ -0,0 +1,308 @@
import { argsert } from './argsert.js';
import { assertNotStrictEqual, } from './typings/common-types.js';
import { levenshtein as distance } from './utils/levenshtein.js';
import { objFilter } from './utils/obj-filter.js';
const specialKeys = ['$0', '--', '_'];
export function validation(yargs, usage, y18n, shim) {
const __ = y18n.__;
const __n = y18n.__n;
const self = {};
self.nonOptionCount = function nonOptionCount(argv) {
const demandedCommands = yargs.getDemandedCommands();
const positionalCount = argv._.length + (argv['--'] ? argv['--'].length : 0);
const _s = positionalCount - yargs.getContext().commands.length;
if (demandedCommands._ &&
(_s < demandedCommands._.min || _s > demandedCommands._.max)) {
if (_s < demandedCommands._.min) {
if (demandedCommands._.minMsg !== undefined) {
usage.fail(demandedCommands._.minMsg
? demandedCommands._.minMsg
.replace(/\$0/g, _s.toString())
.replace(/\$1/, demandedCommands._.min.toString())
: null);
}
else {
usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', _s, _s.toString(), demandedCommands._.min.toString()));
}
}
else if (_s > demandedCommands._.max) {
if (demandedCommands._.maxMsg !== undefined) {
usage.fail(demandedCommands._.maxMsg
? demandedCommands._.maxMsg
.replace(/\$0/g, _s.toString())
.replace(/\$1/, demandedCommands._.max.toString())
: null);
}
else {
usage.fail(__n('Too many non-option arguments: got %s, maximum of %s', 'Too many non-option arguments: got %s, maximum of %s', _s, _s.toString(), demandedCommands._.max.toString()));
}
}
}
};
self.positionalCount = function positionalCount(required, observed) {
if (observed < required) {
usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', observed, observed + '', required + ''));
}
};
self.requiredArguments = function requiredArguments(argv) {
const demandedOptions = yargs.getDemandedOptions();
let missing = null;
for (const key of Object.keys(demandedOptions)) {
if (!Object.prototype.hasOwnProperty.call(argv, key) ||
typeof argv[key] === 'undefined') {
missing = missing || {};
missing[key] = demandedOptions[key];
}
}
if (missing) {
const customMsgs = [];
for (const key of Object.keys(missing)) {
const msg = missing[key];
if (msg && customMsgs.indexOf(msg) < 0) {
customMsgs.push(msg);
}
}
const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : '';
usage.fail(__n('Missing required argument: %s', 'Missing required arguments: %s', Object.keys(missing).length, Object.keys(missing).join(', ') + customMsg));
}
};
self.unknownArguments = function unknownArguments(argv, aliases, positionalMap, isDefaultCommand, checkPositionals = true) {
const commandKeys = yargs.getCommandInstance().getCommands();
const unknown = [];
const currentContext = yargs.getContext();
Object.keys(argv).forEach(key => {
if (specialKeys.indexOf(key) === -1 &&
!Object.prototype.hasOwnProperty.call(positionalMap, key) &&
!Object.prototype.hasOwnProperty.call(yargs._getParseContext(), key) &&
!self.isValidAndSomeAliasIsNotNew(key, aliases)) {
unknown.push(key);
}
});
if (checkPositionals &&
(currentContext.commands.length > 0 ||
commandKeys.length > 0 ||
isDefaultCommand)) {
argv._.slice(currentContext.commands.length).forEach(key => {
if (commandKeys.indexOf('' + key) === -1) {
unknown.push('' + key);
}
});
}
if (unknown.length > 0) {
usage.fail(__n('Unknown argument: %s', 'Unknown arguments: %s', unknown.length, unknown.join(', ')));
}
};
self.unknownCommands = function unknownCommands(argv) {
const commandKeys = yargs.getCommandInstance().getCommands();
const unknown = [];
const currentContext = yargs.getContext();
if (currentContext.commands.length > 0 || commandKeys.length > 0) {
argv._.slice(currentContext.commands.length).forEach(key => {
if (commandKeys.indexOf('' + key) === -1) {
unknown.push('' + key);
}
});
}
if (unknown.length > 0) {
usage.fail(__n('Unknown command: %s', 'Unknown commands: %s', unknown.length, unknown.join(', ')));
return true;
}
else {
return false;
}
};
self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(key, aliases) {
if (!Object.prototype.hasOwnProperty.call(aliases, key)) {
return false;
}
const newAliases = yargs.parsed.newAliases;
for (const a of [key, ...aliases[key]]) {
if (!Object.prototype.hasOwnProperty.call(newAliases, a) ||
!newAliases[key]) {
return true;
}
}
return false;
};
self.limitedChoices = function limitedChoices(argv) {
const options = yargs.getOptions();
const invalid = {};
if (!Object.keys(options.choices).length)
return;
Object.keys(argv).forEach(key => {
if (specialKeys.indexOf(key) === -1 &&
Object.prototype.hasOwnProperty.call(options.choices, key)) {
[].concat(argv[key]).forEach(value => {
if (options.choices[key].indexOf(value) === -1 &&
value !== undefined) {
invalid[key] = (invalid[key] || []).concat(value);
}
});
}
});
const invalidKeys = Object.keys(invalid);
if (!invalidKeys.length)
return;
let msg = __('Invalid values:');
invalidKeys.forEach(key => {
msg += `\n ${__('Argument: %s, Given: %s, Choices: %s', key, usage.stringifiedValues(invalid[key]), usage.stringifiedValues(options.choices[key]))}`;
});
usage.fail(msg);
};
let checks = [];
self.check = function check(f, global) {
checks.push({
func: f,
global,
});
};
self.customChecks = function customChecks(argv, aliases) {
for (let i = 0, f; (f = checks[i]) !== undefined; i++) {
const func = f.func;
let result = null;
try {
result = func(argv, aliases);
}
catch (err) {
usage.fail(err.message ? err.message : err, err);
continue;
}
if (!result) {
usage.fail(__('Argument check failed: %s', func.toString()));
}
else if (typeof result === 'string' || result instanceof Error) {
usage.fail(result.toString(), result);
}
}
};
let implied = {};
self.implies = function implies(key, value) {
argsert('<string|object> [array|number|string]', [key, value], arguments.length);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
self.implies(k, key[k]);
});
}
else {
yargs.global(key);
if (!implied[key]) {
implied[key] = [];
}
if (Array.isArray(value)) {
value.forEach(i => self.implies(key, i));
}
else {
assertNotStrictEqual(value, undefined, shim);
implied[key].push(value);
}
}
};
self.getImplied = function getImplied() {
return implied;
};
function keyExists(argv, val) {
const num = Number(val);
val = isNaN(num) ? val : num;
if (typeof val === 'number') {
val = argv._.length >= val;
}
else if (val.match(/^--no-.+/)) {
val = val.match(/^--no-(.+)/)[1];
val = !argv[val];
}
else {
val = argv[val];
}
return val;
}
self.implications = function implications(argv) {
const implyFail = [];
Object.keys(implied).forEach(key => {
const origKey = key;
(implied[key] || []).forEach(value => {
let key = origKey;
const origValue = value;
key = keyExists(argv, key);
value = keyExists(argv, value);
if (key && !value) {
implyFail.push(` ${origKey} -> ${origValue}`);
}
});
});
if (implyFail.length) {
let msg = `${__('Implications failed:')}\n`;
implyFail.forEach(value => {
msg += value;
});
usage.fail(msg);
}
};
let conflicting = {};
self.conflicts = function conflicts(key, value) {
argsert('<string|object> [array|string]', [key, value], arguments.length);
if (typeof key === 'object') {
Object.keys(key).forEach(k => {
self.conflicts(k, key[k]);
});
}
else {
yargs.global(key);
if (!conflicting[key]) {
conflicting[key] = [];
}
if (Array.isArray(value)) {
value.forEach(i => self.conflicts(key, i));
}
else {
conflicting[key].push(value);
}
}
};
self.getConflicting = () => conflicting;
self.conflicting = function conflictingFn(argv) {
Object.keys(argv).forEach(key => {
if (conflicting[key]) {
conflicting[key].forEach(value => {
if (value && argv[key] !== undefined && argv[value] !== undefined) {
usage.fail(__('Arguments %s and %s are mutually exclusive', key, value));
}
});
}
});
};
self.recommendCommands = function recommendCommands(cmd, potentialCommands) {
const threshold = 3;
potentialCommands = potentialCommands.sort((a, b) => b.length - a.length);
let recommended = null;
let bestDistance = Infinity;
for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) {
const d = distance(cmd, candidate);
if (d <= threshold && d < bestDistance) {
bestDistance = d;
recommended = candidate;
}
}
if (recommended)
usage.fail(__('Did you mean %s?', recommended));
};
self.reset = function reset(localLookup) {
implied = objFilter(implied, k => !localLookup[k]);
conflicting = objFilter(conflicting, k => !localLookup[k]);
checks = checks.filter(c => c.global);
return self;
};
const frozens = [];
self.freeze = function freeze() {
frozens.push({
implied,
checks,
conflicting,
});
};
self.unfreeze = function unfreeze() {
const frozen = frozens.pop();
assertNotStrictEqual(frozen, undefined, shim);
({ implied, checks, conflicting } = frozen);
};
return self;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,7 @@
export class YError extends Error {
constructor(msg) {
super(msg || 'yargs error');
this.name = 'YError';
Error.captureStackTrace(this, YError);
}
}

View File

@@ -0,0 +1,10 @@
import {applyExtends as _applyExtends} from '../build/lib/utils/apply-extends.js';
import {hideBin} from '../build/lib/utils/process-argv.js';
import Parser from 'yargs-parser';
import shim from '../lib/platform-shims/esm.mjs';
const applyExtends = (config, cwd, mergeExtends) => {
return _applyExtends(config, cwd, mergeExtends, shim);
};
export {applyExtends, hideBin, Parser};

View File

@@ -0,0 +1,14 @@
const {
applyExtends,
cjsPlatformShim,
Parser,
processArgv,
} = require('../build/index.cjs');
module.exports = {
applyExtends: (config, cwd, mergeExtends) => {
return applyExtends(config, cwd, mergeExtends, cjsPlatformShim);
},
hideBin: processArgv.hideBin,
Parser,
};

View File

@@ -0,0 +1,3 @@
{
"type": "commonjs"
}

39
node_modules/gulp-cli/node_modules/yargs/index.cjs generated vendored Normal file
View File

@@ -0,0 +1,39 @@
'use strict';
// classic singleton yargs API, to use yargs
// without running as a singleton do:
// require('yargs/yargs')(process.argv.slice(2))
const {Yargs, processArgv} = require('./build/index.cjs');
Argv(processArgv.hideBin(process.argv));
module.exports = Argv;
function Argv(processArgs, cwd) {
const argv = Yargs(processArgs, cwd, require);
singletonify(argv);
return argv;
}
/* Hack an instance of Argv with process.argv into Argv
so people can do
require('yargs')(['--beeble=1','-z','zizzle']).argv
to parse a list of args and
require('yargs').argv
to get a parsed version of process.argv.
*/
function singletonify(inst) {
Object.keys(inst).forEach(key => {
if (key === 'argv') {
Argv.__defineGetter__(key, inst.__lookupGetter__(key));
} else if (typeof inst[key] === 'function') {
Argv[key] = inst[key].bind(inst);
} else {
Argv.__defineGetter__('$0', () => {
return inst.$0;
});
Argv.__defineGetter__('parsed', () => {
return inst.parsed;
});
}
});
}

8
node_modules/gulp-cli/node_modules/yargs/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,8 @@
'use strict';
// Bootstraps yargs for ESM:
import esmPlatformShim from './lib/platform-shims/esm.mjs';
import {YargsWithShim} from './build/lib/yargs-factory.js';
const Yargs = YargsWithShim(esmPlatformShim);
export default Yargs;

View File

@@ -0,0 +1,92 @@
'use strict';
import cliui from 'https://unpkg.com/cliui@7.0.1/index.mjs'; // eslint-disable-line
import Parser from 'https://unpkg.com/yargs-parser@19.0.0/browser.js'; // eslint-disable-line
import {getProcessArgvBin} from '../../build/lib/utils/process-argv.js';
import {YError} from '../../build/lib/yerror.js';
const REQUIRE_ERROR = 'require is not supported in browser';
const REQUIRE_DIRECTORY_ERROR =
'loading a directory of commands is not supported in browser';
export default {
assert: {
notStrictEqual: (a, b) => {
// noop.
},
strictEqual: (a, b) => {
// noop.
},
},
cliui,
findUp: () => undefined,
getEnv: key => {
// There is no environment in browser:
return undefined;
},
inspect: console.log,
getCallerFile: () => {
throw new YError(REQUIRE_DIRECTORY_ERROR);
},
getProcessArgvBin,
mainFilename: 'yargs',
Parser,
path: {
basename: str => str,
dirname: str => str,
extname: str => str,
relative: str => str,
},
process: {
argv: () => [],
cwd: () => '',
execPath: () => '',
// exit is noop browser:
exit: () => {},
nextTick: cb => {
window.setTimeout(cb, 1);
},
stdColumns: 80,
},
readFileSync: () => {
return '';
},
require: () => {
throw new YError(REQUIRE_ERROR);
},
requireDirectory: () => {
throw new YError(REQUIRE_DIRECTORY_ERROR);
},
stringWidth: str => {
return [...str].length;
},
// TODO: replace this with y18n once it's ported to ESM:
y18n: {
__: (...str) => {
if (str.length === 0) return '';
const args = str.slice(1);
return sprintf(str[0], ...args);
},
__n: (str1, str2, count, ...args) => {
if (count === 1) {
return sprintf(str1, ...args);
} else {
return sprintf(str2, ...args);
}
},
getLocale: () => {
return 'en_US';
},
setLocale: () => {},
updateLocale: () => {},
},
};
function sprintf(_str, ...args) {
let str = '';
const split = _str.split('%s');
split.forEach((token, i) => {
str += `${token}${split[i + 1] !== undefined && args[i] ? args[i] : ''}`;
});
return str;
}

Some files were not shown because too many files have changed in this diff Show More