fix: prevent asset conflicts between React and Grid.js versions

Add coexistence checks to all enqueue methods to prevent loading
both React and Grid.js assets simultaneously.

Changes:
- ReactAdmin.php: Only enqueue React assets when ?react=1
- Init.php: Skip Grid.js when React active on admin pages
- Form.php, Coupon.php, Access.php: Restore classic assets when ?react=0
- Customer.php, Product.php, License.php: Add coexistence checks

Now the toggle between Classic and React versions works correctly.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
dwindown
2026-04-18 17:02:14 +07:00
parent bd9cdac02e
commit e8fbfb14c1
74973 changed files with 6658406 additions and 71 deletions

52
node_modules/check-node-version/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,52 @@
## Releases
### 4.0.3
* Fix crash due to non-semver valid version strings
### 4.0.2
* Make notfound-catch locale-independent on Windows
### 4.0.1
* Fix CLI by restoring shebang to new bin file
### 4.0.0
* **Breaking:** Drop support for node versions before 8.3.0
* **Breaking:** Remove `options.getVersion` option from api (no
cli change)
* Improve test suite
* Make CLI treat versions arguments as strings
* Fix message for missing binary of Windows
* Check global versions only
* Make instructions valid for version ranges
* Only suggest using nvm if nvm is installed
### 3.3.0
* Add NPX support
### 3.2.0
* Add `index.ts` TypeScript typings file
### 3.1.1
* Fix bug with npm warnings causing errors.
### 3.1.0
* Add colors to terminal output.
### 3.0.0
This release changes the default output behavior to only print
*unsatisfied* versions. If all checked versions pass, there is no
output. A `--print` option has been added to get the old behavior of
always printing versions.
* **Breaking**: Remove `--quiet` option, add `--print` option.
* **Breaking**: Move versions under versions key in result object.
* Fix bug when version command outputs more than one line.

24
node_modules/check-node-version/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
For more information, please refer to <http://unlicense.org>

221
node_modules/check-node-version/README.md generated vendored Normal file
View File

@@ -0,0 +1,221 @@
<a name="check-node-version"></a>
# check-node-version
[![NPM version](http://img.shields.io/npm/v/check-node-version.svg?style=flat-square)](https://www.npmjs.org/package/check-node-version)
[![AppVeyor build status](https://img.shields.io/appveyor/ci/parshap/check-node-version/master.svg?style=flat-square)](https://ci.appveyor.com/project/parshap/check-node-version/branch/master)
[![Travis build status](http://img.shields.io/travis/parshap/check-node-version/master.svg?style=flat-square)](https://travis-ci.org/parshap/check-node-version)
Check installed versions of `node`, `npm`, `npx`, `yarn`, and `pnpm`.
* [check-node-version](#check-node-version)
* [Install](#check-node-version-install)
* [Command Line Usage](#check-node-version-command-line-usage)
* [Examples](#check-node-version-command-line-usage-examples)
* [API Usage](#check-node-version-api-usage)
<a name="check-node-version-install"></a>
## Install
[npm: *check-node-version*](https://www.npmjs.com/package/check-node-version)
```bash
npm install check-node-version
```
<a name="check-node-version-command-line-usage"></a>
## Command Line Usage
```
SYNOPSIS
check-node-version [OPTIONS]
DESCRIPTION
check-node-version will check if the current node, npm, npx, yarn and pnpm
versions match the given semver version ranges.
If the given version is not satisfied, information about
installing the needed version is printed and the program exits
with an error code.
OPTIONS
--node VERSION
Check that the current node version matches the given semver
version range.
--npm VERSION
Check that the current npm version matches the given semver
version range.
--npx VERSION
Check that the current npx version matches the given semver
version range.
--yarn VERSION
Check that the current yarn version matches the given semver
version range.
--pnpm VERSION
Check that the current pnpm version matches the given semver
version range.
--package
Use the "engines" key in the current package.json for the
semver version ranges.
--volta
Use the versions pinned by Volta in the package.json
-p, --print
Print installed versions.
-h, --help
Print this message.
```
<a name="check-node-version-command-line-usage-examples"></a>
### Examples
<a name="check-node-version-command-line-usage-examples-check-for-node-6-failing"></a>
#### Check for node 6, failing
Check for node 6, but have 8.2.1 installed.
```bash
$ check-node-version --node 6
node: 8.2.1
Error: Wanted node version 6 (>=6.0.0 <7.0.0)
To install node, run `nvm install 6` or see https://nodejs.org/
$ echo $?
1
```
<a name="check-node-version-command-line-usage-examples-check-for-node-6-passing"></a>
#### Check for node 6, passing
If all versions match, there is no output:
```bash
$ check-node-version --node 6
$ echo $?
0
```
<a name="check-node-version-command-line-usage-examples-check-for-multiple-versions-simultaneously"></a>
#### Check for multiple versions simultaneously
You can check versions of any combinations of `node`, `npm`, `npx`, `yarn`, and `pnpm`
at one time.
```bash
$ check-node-version --node 4 --npm 2.14 --npx 6 --yarn 0.17.1 --pnpm 6.20.1
```
<a name="check-node-version-command-line-usage-examples-check-for-volta-pinned-versions"></a>
#### Check for volta pinned versions
You can check versions pinned by [Volta](https://volta.sh/):
```bash
$ check-node-version --volta
```
<a name="check-node-version-command-line-usage-examples-print-installed-versions"></a>
#### Print installed versions
Use the `--print` option to print currently installed versions.
If given a tool to check, only that will be printed.
Otherwise, all known tools will be printed.
Notes a missing tool.
```bash
$ check-node-version --print --node 11.12
node: 11.12.0
$ echo $?
0
```
```powershell
$ check-node-version --print
yarn: not found
node: 11.12.0
npm: 6.9.0
npx: 10.2.0
$ $LASTEXITCODE
0
```
> **NOTE:**
> Both preceding examples show that this works equally cross-platform,
> the first one being a *nix shell, the second one running on Windows.
> **NOTE:**
> As per [Issue 36](https://github.com/parshap/check-node-version/issues/36),
> non-semver-compliant versions (looking at yarn here) will be handled similarly to missing tools,
> just with a different error message.
>
> At the time of writing, we think that
> 1. all tools should always use semver
> 2. exceptions are bound too be very rare
> 3. preventing a crash is sufficient
>
> Consequently, we do not intend to support non-compliant versions to any further extent.
<a name="check-node-version-command-line-usage-examples-use-with-a-nvmrc-file"></a>
#### Use with a <code>.nvmrc</code> file
```bash
$ check-node-version --node $(cat .nvmrc) --npm 2.14
```
<a name="check-node-version-command-line-usage-examples-use-with-npm-test"></a>
#### Use with <code>npm test</code>
```json
{
"name": "my-package",
"devDependencies": {
"check-node-version": "^1.0.0"
},
"scripts": {
"test": "check-node-version --node '>= 4.2.3' && node my-tests.js"
}
}
```
<a name="check-node-version-api-usage"></a>
## API Usage
This module can also be used programmatically.
Pass it an object with the required versions of `node`, `npm`, `npx`, `yarn` and/or `pnpm` followed by a results handler.
```javascript
const check = require("check-node-version");
check(
{ node: ">= 18.3", },
(error, result) => {
if (error) {
console.error(error);
return;
}
if (result.isSatisfied) {
console.log("All is well.");
return;
}
console.error("Some package version(s) failed!");
for (const packageName of Object.keys(result.versions)) {
if (!result.versions[packageName].isSatisfied) {
console.error(`Missing ${packageName}.`);
}
}
}
);
```
See `index.d.ts` for the full input and output type definitions.

4
node_modules/check-node-version/bin.js generated vendored Executable file
View File

@@ -0,0 +1,4 @@
#!/usr/bin/env node
require("./gatekeeper");
require("./cli");

177
node_modules/check-node-version/cli.js generated vendored Normal file
View File

@@ -0,0 +1,177 @@
"use strict";
const fs = require("fs");
const path = require("path");
const chalk = require("chalk");
const minimist = require("minimist");
const semver = require('semver');
const check = require(".");
const tools = require("./tools");
const argv = minimist(process.argv.slice(2), {
alias: {
"print": "p",
"help": "h",
},
boolean: [
"print",
"help",
"volta",
"package",
],
string: [
"node",
"npm",
"npx",
"yarn",
"pnpm",
],
unknown: function (arg) {
console.error(`Unknown option: ${arg}`);
process.exit(1);
}
});
if (argv.help) {
const usage = fs.readFileSync(path.join(__dirname, "usage.txt"), {
encoding: "utf8",
});
process.stdout.write(usage);
process.exit(0);
}
let options;
if (argv.package) {
options = optionsFromPackage();
} else if (argv.volta) {
options = optionsFromVolta();
} else {
options = optionsFromCommandLine();
}
check(options, (err, result) => {
if (err) {
throw err;
}
printVersions(result, argv.print);
process.exit(result.isSatisfied ? 0 : 1);
});
//
function optionsFromCommandLine() {
return Object.keys(tools).reduce((memo, name) => ({
...memo,
[name]: argv[name],
}), {});
}
function optionsFromPackage() {
let packageJson;
try {
packageJson = require(path.join(process.cwd(), 'package.json'));
} catch (e) {
console.log('Error: When running with --package, a package.json file is expected in the current working directory');
console.log('Current working directory is: ' + process.cwd());
process.exit(1);
}
if (!packageJson.engines) {
console.log('Error: When running with --package, your package.json is expected to contain the "engines" key');
console.log('See https://docs.npmjs.com/files/package.json#engines for the supported syntax');
process.exit(1);
}
return Object.keys(tools).reduce((memo, name) => ({
...memo,
[name]: packageJson.engines[name],
}), {});
}
function optionsFromVolta() {
let packageJson;
try {
packageJson = require(path.join(process.cwd(), 'package.json'));
} catch (e) {
console.log('Error: When running with --volta, a package.json file is expected in the current working directory');
console.log('Current working directory is: ' + process.cwd());
process.exit(1);
}
if (!packageJson.volta) {
console.log('Error: When running with --volta, your package.json is expected to contain the "volta" key');
console.log('See https://docs.volta.sh/guide/understanding#pinning-node-engines');
process.exit(1);
}
console.log(packageJson.volta);
return Object.keys(tools).reduce((memo, name) => ({
...memo,
[name]: packageJson.volta[name],
}), {});
}
//
function printVersions(result, print) {
Object.keys(result.versions).forEach(name => {
const info = result.versions[name];
const isSatisfied = info.isSatisfied;
// print installed version
if (print || !isSatisfied) {
printInstalledVersion(name, info);
}
if (isSatisfied) return;
// report any non-compliant versions
const { raw, range } = info.wanted;
console.error(chalk.red(`Wanted ${name} version ` + chalk.bold(`${raw} (${range})`)));
console.log(chalk.yellow.bold(
tools[name]
.getInstallInstructions(
semver.minVersion(info.wanted)
)
));
});
}
function printInstalledVersion(name, { version, isSatisfied, invalid, notfound }) {
let versionNote = "";
if (version) {
versionNote = name + ": " + chalk.bold(version);
}
if (invalid) {
versionNote = name + ": " + chalk.bold("given version not semver-compliant");
}
if (notfound) {
versionNote = name + ": not found";
}
if (isSatisfied) {
if (version) console.log(versionNote);
else console.log(chalk.gray(versionNote));
} else {
console.log(chalk.red(versionNote));
}
}

19
node_modules/check-node-version/gatekeeper.js generated vendored Normal file
View File

@@ -0,0 +1,19 @@
var semver = require('semver');
var current = process.version;
var supported = require('./package.json').engines.node;
if (!semver.satisfies(current, supported)) {
console.error(
'\n' +
'You are using node version ' + semver.valid(current) + '.\n\n' +
'check-node-version supports node verion ' + semver.valid(semver.minVersion(supported)) + ' and newer.\n\n' +
'Please do one of the following:\n' +
' 1. update your version of node\n' +
' 2. downgrade to version 3.3.0 of check-node-version\n\n' +
'We are sorry for the inconvenience.' +
'\n'
);
process.exit(1);
}

145
node_modules/check-node-version/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,145 @@
/**
* Which versions of which packages are required.
*/
interface WantedVersions {
/**
* Required version of Node.js.
*/
node?: string;
/**
* Required version of npm.
*/
npm?: string;
/**
* Required version of yarn.
*/
yarn?: string;
/**
* Required version of pnpm.
*/
pnpm?: string;
}
type OnGetVersion = (error: Error | null, info: VersionInfo) => void;
/**
* Gets the version of a package.
*
* @param packageName Name of the package.
* @param onComplete Handler for the package name.
*/
type GetVersion = (packageName: string, onComplete: OnGetVersion) => void;
/**
* Requested version range of a package.
*/
interface Wanted {
/**
* Resolved semver equivalent of the raw version.
*/
range: string;
/**
* Raw semver requirement for the version.
*/
raw: string;
}
/**
* Positive result of checking a program version.
*/
interface SatisfiedVersionInfo {
/**
* Whether the version was known to satisfy its requirements (true).
*/
isSatisfied: true;
/**
* Retrieved version.
*/
version: string;
/**
* Requested version range of the package, if any.
*/
wanted?: Wanted;
}
/**
* Negative result of checking a program version.
*/
interface UnsatisfiedVersionInfo {
/**
* Whether the version was known to satisfy its requirements (false).
*/
isSatisfied: false;
/**
* Whether the program version was unable to be found.
*/
notfound?: boolean;
/**
* Whether the program version string is non-compliant with semver.
*/
invalid?: boolean;
/**
* Retrieved version, if available.
*/
version?: string;
/**
* Requested version range of the package, if any.
*/
wanted?: Wanted;
}
/**
* Result of checking a program version.
*/
type VersionInfo = SatisfiedVersionInfo | UnsatisfiedVersionInfo;
/**
* Versions for each package, keyed by package name.
*/
interface VersionInfos {
[i: string]: VersionInfo;
}
/**
* Results from checking versions.
*/
interface Results {
/**
* Versions for each package, keyed by package name.
*/
versions: VersionInfos;
/**
* Whether all versions were satisfied.
*/
isSatisfied: boolean;
}
/**
* Handles results from checking versions.
*
* @param error Error from version checking, if any.
* @param results Results from checking versions.
*/
type OnComplete = (error: Error | null, results: Results) => void;
/**
* Checks package versions.
*
* @param [wanted] Which versions of programs are required.
* @param onComplete Handles results from checking versions.
*/
declare function check(onComplete: OnComplete): void;
declare function check(wanted: WantedVersions, onComplete: OnComplete): void;
export = check;

239
node_modules/check-node-version/index.js generated vendored Normal file
View File

@@ -0,0 +1,239 @@
"use strict";
const { exec } = require("child_process");
const path = require("path");
const filterObject = require("object-filter");
const mapValues = require("map-values");
const parallel = require("run-parallel");
const semver = require("semver");
const tools = require("./tools");
const runningOnWindows = (process.platform === "win32");
const originalPath = process.env.PATH;
const pathSeparator = runningOnWindows ? ";" : ":";
const localBinPath = path.resolve("node_modules/.bin")
// ignore locally installed packages
const globalPath = originalPath
.split(pathSeparator)
.filter(p => path.resolve(p)!==localBinPath)
.join(pathSeparator)
;
module.exports = function check(wanted, callback) {
// Normalize arguments
if (typeof wanted === "function") {
callback = wanted;
wanted = null;
}
const options = { callback };
options.wanted = normalizeWanted(wanted);
options.commands = mapValues(
(
Object.keys(options.wanted).length
? filterObject(tools, (_, key) => options.wanted[key])
: tools
),
({ getVersion }) => ( runVersionCommand.bind(null, getVersion) )
);
if (runningOnWindows) {
runForWindows(options);
} else {
run(options);
}
}
function runForWindows(options) {
// See and understand https://github.com/parshap/check-node-version/issues/35
// before trying to optimize this function
//
// `chcp` is used instead of `where` on account of its more extensive availablity
// chcp: MS-DOS 6.22+, Windows 95+; where: Windows 7+
//
// Plus, in order to be absolutely certain, the error message of `where` would still need evaluation.
exec("chcp", (error, stdout) => {
const finalCallback = options.callback;
if (error) {
finalCallback(chcpError(error, 1));
return;
}
const codepage = stdout.match(/\d+/)[0];
if (codepage === "65001" || codepage === "437") {
// need not switch codepage
return run(options);
}
// reset codepage before exiting
options.callback = (...args) => exec(`chcp ${codepage}`, (error) => {
if (error) {
finalCallback(chcpError(error, 3));
return;
}
finalCallback(...args);
});
// switch to Unicode
exec("chcp 65001", (error) => {
if (error) {
finalCallback(chcpError(error, 2));
return;
}
run(options);
});
function chcpError(error, step) {
switch (step) {
case 1:
error.message = `[CHCP] error while getting current codepage:\n${error.message}`;
break;
case 2:
error.message = `[CHCP] error while switching to Unicode codepage:\n${error.message}`;
break;
case 3:
error.message = `
[CHCP] error while resetting current codepage:
${error.message}
Please note that your terminal is now using the Unicode codepage.
Therefore, codepage-dependent actions may work in an unusual manner.
You can run \`chcp ${codepage}\` yourself in order to reset your codepage,
or just close this terminal and work in another.
`.trim().replace(/^ +/gm,'') // strip indentation
break;
// no default
}
return error
}
});
}
function run({ commands, callback, wanted }) {
parallel(commands, (err, versionsResult) => {
if (err) {
callback(err);
return;
}
const versions = mapValues(versionsResult, ({ version, notfound, invalid }, name) => {
const programInfo = {
isSatisfied: true,
};
if (version) {
programInfo.version = semver(version);
}
if (invalid) {
programInfo.invalid = invalid;
}
if (notfound) {
programInfo.notfound = notfound;
}
if (wanted[name]) {
programInfo.wanted = new semver.Range(wanted[name]);
programInfo.isSatisfied = Boolean(
programInfo.version
&&
semver.satisfies(programInfo.version, programInfo.wanted)
);
}
return programInfo;
});
callback(null, {
versions: versions,
isSatisfied: Object.keys(wanted).every(name => versions[name].isSatisfied),
});
});
};
// Return object containing only keys that a program exists for and
// something valid was given.
function normalizeWanted(wanted) {
if (!wanted) {
return {};
}
// Validate keys
wanted = filterObject(wanted, Boolean);
// Normalize to strings
wanted = mapValues(wanted, String);
// Filter existing programs
wanted = filterObject(wanted, (_, key) => tools[key]);
return wanted;
}
function runVersionCommand(command, callback) {
process.env.PATH = globalPath;
exec(command, (execError, stdout, stderr) => {
const commandDescription = JSON.stringify(command);
if (!execError) {
const version = stdout.trim();
if (semver.valid(version)) {
return callback(null, {
version,
});
} else {
return callback(null, {
invalid: true,
})
}
}
if (toolNotFound(execError)) {
return callback(null, {
notfound: true,
});
}
// something went very wrong during execution
let errorMessage = `Command failed: ${commandDescription}`
if (stderr) {
errorMessage += `\n\nstderr:\n${stderr.toString().trim()}\n`;
}
errorMessage += `\n\noriginal error message:\n${execError.message}\n`;
return callback(new Error(errorMessage));
});
process.env.PATH = originalPath;
}
function toolNotFound(execError) {
if (runningOnWindows) {
return execError.message.includes("is not recognized");
}
return execError.code === 127;
}

View File

@@ -0,0 +1,411 @@
declare const enum LevelEnum {
/**
All colors disabled.
*/
None = 0,
/**
Basic 16 colors support.
*/
Basic = 1,
/**
ANSI 256 colors support.
*/
Ansi256 = 2,
/**
Truecolor 16 million colors support.
*/
TrueColor = 3
}
/**
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 {
type Level = LevelEnum;
interface Options {
/**
Specify the color support for Chalk.
By default, color support is automatically detected based on the environment.
*/
level?: Level;
}
interface Instance {
/**
Return a new Chalk 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}%}
`);
```
*/
(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.
*/
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: typeof LevelEnum;
Color: Color;
ForegroundColor: ForegroundColor;
BackgroundColor: BackgroundColor;
Modifiers: Modifiers;
stderr: chalk.Chalk & {supportsColor: chalk.ColorSupport | false};
};
export = chalk;

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.

View File

@@ -0,0 +1,63 @@
{
"name": "chalk",
"version": "3.0.0",
"description": "Terminal string styling done right",
"license": "MIT",
"repository": "chalk/chalk",
"main": "source",
"engines": {
"node": ">=8"
},
"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": "^3.2.0",
"import-fresh": "^3.1.0",
"matcha": "^0.7.0",
"nyc": "^14.1.1",
"resolve-from": "^5.0.0",
"tsd": "^0.7.4",
"xo": "^0.25.3"
},
"xo": {
"rules": {
"unicorn/prefer-string-slice": "off",
"unicorn/prefer-includes": "off"
}
}
}

View File

@@ -0,0 +1,304 @@
<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)
<img src="https://cdn.jsdelivr.net/gh/chalk/ansi-styles@8261697c95bf34b6c7767e2cbe9941a851d59385/screenshot.svg" width="900">
## 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 ~46,000 packages](https://www.npmjs.com/browse/depended/chalk) as of October 1, 2019
## 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](http://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 two statements are equivalent:
```js
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,233 @@
'use strict';
const ansiStyles = require('ansi-styles');
const {stdout: stdoutColor, stderr: stderrColor} = require('supports-color');
const {
stringReplaceAll,
stringEncaseCRLFWithFirstIndex
} = require('./util');
// `supportsColor.level` → `ansiStyles.color[name]` mapping
const levelMapping = [
'ansi',
'ansi',
'ansi256',
'ansi16m'
];
const styles = Object.create(null);
const applyOptions = (object, options = {}) => {
if (options.level > 3 || options.level < 0) {
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) {
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_) => {
// 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(' '));
};
// `__proto__` is used because we must return a function, but there is
// no way to create a function with a different prototype
builder.__proto__ = proto; // eslint-disable-line no-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 (!Array.isArray(firstString)) {
// 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;
// For TypeScript
chalk.Level = {
None: 0,
Basic: 1,
Ansi256: 2,
TrueColor: 3,
0: 'None',
1: 'Basic',
2: 'Ansi256',
3: 'TrueColor'
};
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 errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
throw new Error(errMsg);
}
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
};

53
node_modules/check-node-version/package.json generated vendored Normal file
View File

@@ -0,0 +1,53 @@
{
"name": "check-node-version",
"version": "4.2.1",
"engines": {
"node": ">=8.3.0"
},
"description": "Check installed versions of node and npm",
"main": "index.js",
"bin": {
"check-node-version": "bin.js"
},
"scripts": {
"add-docs": "git add README.md",
"build-readme": "gitdown ./README_src.md --output-file ./README.md",
"test": "ava -v"
},
"husky": {
"hooks": {
"pre-commit": "npx run-s test build-readme add-docs"
}
},
"repository": {
"type": "git",
"url": "git+https://github.com/parshap/check-node-version.git"
},
"keywords": [
"version",
"semver"
],
"author": "Parsha Pourkhomami",
"license": "Unlicense",
"types": "./index.d.ts",
"bugs": {
"url": "https://github.com/parshap/check-node-version/issues"
},
"homepage": "https://github.com/parshap/check-node-version#readme",
"dependencies": {
"chalk": "^3.0.0",
"map-values": "^1.0.1",
"minimist": "^1.2.0",
"object-filter": "^1.0.2",
"run-parallel": "^1.1.4",
"semver": "^6.3.0"
},
"devDependencies": {
"ava": "^2.4.0",
"gitdown": "^3.1.2",
"husky": "^3.1.0",
"npm": "6.14.6",
"npm-run-all": "^4.1.5",
"proxyquire": "^2.1.3"
}
}

53
node_modules/check-node-version/tools.js generated vendored Normal file
View File

@@ -0,0 +1,53 @@
const { execSync } = require("child_process");
module.exports = {
node: {
getVersion: "node --version",
getInstallInstructions(v) {
if (hasNvm()) {
return `To install node, run \`nvm install ${v}\``;
}
return `To install node, see https://nodejs.org/download/release/v${v}/`;
}
},
npm: {
getVersion: "npm --version",
getInstallInstructions(v) {
return `To install npm, run \`npm install -g npm@${v}\``;
}
},
npx: {
getVersion: "npx --version",
getInstallInstructions(v) {
return `To install npx, run \`npm install -g npx@${v}\``;
}
},
yarn: {
getVersion: "yarn --version",
getInstallInstructions(v) {
return `To install yarn, see https://github.com/yarnpkg/yarn/releases/tag/v${v}`;
}
},
pnpm: {
getVersion: "pnpm --version",
getInstallInstructions(v) {
return `To install pnpm, run \`npm install -g pnpm@${v}\``;
}
},
};
function hasNvm() {
try {
// check for existance of nvm
execSync(
'nvm',
{ stdio:[] } // don't care about output
);
} catch (e) {
// no nvm,
return false;
}
return true;
}

45
node_modules/check-node-version/usage.txt generated vendored Normal file
View File

@@ -0,0 +1,45 @@
SYNOPSIS
check-node-version [OPTIONS]
DESCRIPTION
check-node-version will check if the current node, npm, npx, yarn and pnpm
versions match the given semver version ranges.
If the given version is not satisfied, information about
installing the needed version is printed and the program exits
with an error code.
OPTIONS
--node VERSION
Check that the current node version matches the given semver
version range.
--npm VERSION
Check that the current npm version matches the given semver
version range.
--npx VERSION
Check that the current npx version matches the given semver
version range.
--yarn VERSION
Check that the current yarn version matches the given semver
version range.
--pnpm VERSION
Check that the current pnpm version matches the given semver
version range.
--package
Use the "engines" key in the current package.json for the
semver version ranges.
--volta
Use the versions pinned by Volta in the package.json
-p, --print
Print installed versions.
-h, --help
Print this message.