Compare commits

...

155 commits
v2.3.0 ... main

Author SHA1 Message Date
Mohamed Hamed
aa06bb5ac3
Fix typos (#664) 2026-01-27 13:30:36 +07:00
Sindre Sorhus
51557784b8 5.6.2 2025-09-08 21:47:34 +07:00
Sindre Sorhus
5c91505e18 5.6.0 2025-08-17 14:26:22 +07:00
Sindre Sorhus
a8f5bf7a67 Make WezTerm terminal use true color 2025-08-17 14:25:29 +07:00
Sindre Sorhus
67db246ae0 5.5.0 2025-08-04 01:17:43 +02:00
Brice
79ee2d386c
Make Ghostty terminal use true color (#653) 2025-08-04 01:14:54 +02:00
Sindre Sorhus
5dbc1e2633 5.4.1 2024-12-21 18:04:25 +01:00
Edwin Kofler
4ebb62d1ca
Fix navigator not defined ReferenceError (#642) 2024-12-21 18:01:49 +01:00
Sindre Sorhus
fc809b686d Readme tweak 2024-12-18 19:10:23 +01:00
Sindre Sorhus
83acfcf8cb 5.4.0 2024-12-18 18:59:38 +01:00
Sindre Sorhus
f8381204fb Update CIRCLECI environments to return level 3 color support
89a52f4a8e
2024-12-18 18:58:03 +01:00
Sindre Sorhus
4a10354857 Add FAQ to readme 2024-08-13 17:43:03 +02:00
Sindre Sorhus
77126fba13 Meta tweaks 2024-08-08 00:00:20 +02:00
Lightner
795273f17a
Update dependents number in readme (#629) 2024-07-05 12:41:35 +02:00
Richie Bendall
386909ee0b
Tweak example (#623) 2024-01-19 21:36:11 +07:00
Edwin Kofler
2db3c7701e
Remove .replit file (#622) 2024-01-06 02:08:07 +01:00
Sindre Sorhus
f7b29ae8ef Remove repl.it badge
Fixes #587
2023-08-16 12:14:40 +02:00
Sindre Sorhus
f399cd0ff6 Meta tweaks 2023-06-29 14:45:41 +02:00
Sindre Sorhus
72c742d471 5.3.0 2023-06-29 12:56:55 +02:00
Sindre Sorhus
5aafc0af74 Add sideEffects field to package.json
Fixes #585
2023-06-29 12:52:59 +02:00
Sindre Sorhus
df0e69df51 Fix CI 2023-06-29 12:50:22 +02:00
silverwind
29b856959f
Update supports-color to 9.4.0 (#603)
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
2023-06-29 12:47:28 +02:00
Sindre Sorhus
a370f468a4 5.2.0 2022-12-08 19:46:06 +01:00
idanran
7443e9faa0
Update supports-color dependency (#579) 2022-12-08 19:43:43 +01:00
Sindre Sorhus
a027e3c1e0 Minor tweaks 2022-11-28 14:15:46 +07:00
LitoMore
79c56dfc1e
Update Replit badge (#576) 2022-10-30 23:54:53 +07:00
Daniel Li
c3d14f9ea8
Update link to Truecolor in the readme (#573) 2022-10-20 17:29:51 +07:00
Sindre Sorhus
158bf4429e 5.1.2 2022-10-12 23:31:43 +07:00
LitoMore
a34bcf6327
Fix exported styles names (#569) 2022-10-12 23:30:36 +07:00
Sindre Sorhus
1b4cd21fb1 5.1.1 2022-10-12 16:36:43 +07:00
LitoMore
6e0df055f4
Export styles from ansi-styles (#567) 2022-10-12 16:35:02 +07:00
Sindre Sorhus
92c55db46f 5.1.0 2022-10-05 21:45:55 +07:00
LitoMore
d7d75717b3
Expose style names (#566)
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
2022-10-05 21:44:40 +07:00
Sindre Sorhus
96f44c976b Meta tweaks 2022-10-05 21:43:01 +07:00
Matt Schlenker
c2311622c3
Use template literal types for simple color name transformations in the TypeScript types (#564) 2022-09-25 12:24:19 +07:00
Sindre Sorhus
ba5c385ecf Update screenshot
Fixes #554
2022-07-03 00:36:34 +02:00
LitoMore
503b9d35cd
Update Replit badge (#551) 2022-06-26 14:58:46 +02:00
Richie Bendall
b17d862944
Improve browser detection (#542) 2022-03-30 12:41:57 +07:00
CommanderRoot
d28690e66b
Refactor: Replace deprecated String#substr() (#541) 2022-03-28 01:11:02 +07:00
Sindre Sorhus
bccde97f8a 5.0.1 2022-03-09 01:43:33 +07:00
Sindre Sorhus
85f7e96f75 Add main field to package.json for backwards compatibiltiy
Fixes #536
2022-03-09 01:42:04 +07:00
Sindre Sorhus
4d5c4795ad 5.0.0 2021-11-26 16:57:26 +07:00
Sindre Sorhus
7a6893551d Fix code coverage 2021-11-26 16:55:15 +07:00
Sindre Sorhus
04fdbd6d8d Bundle dependencies 2021-11-26 16:34:27 +07:00
Sindre Sorhus
d7c4aac07e Upgrade dependencies 2021-11-26 16:00:01 +07:00
Richie Bendall
09fd5c4ba8
Re-export types from supports-color (#526) 2021-11-21 13:51:24 +07:00
Richie Bendall
c987c61486
Remove support for tagged template literals (#524) 2021-11-10 16:12:33 +07:00
LightnerDev
f478655c3c
Update dependents number in readme (#521) 2021-10-27 01:22:37 +07:00
Richie Bendall
3761e455a1
Meta tweak (#520) 2021-10-25 02:07:02 +07:00
Sindre Sorhus
95217429be Minor tweaks 2021-10-02 00:02:38 +07:00
Sindre Sorhus
625a285772 Add types field to package.json
Fixes #500
2021-07-30 17:35:30 +02:00
Sindre Sorhus
48d25d156a Meta tweaks 2021-07-30 13:58:57 +02:00
Sindre Sorhus
b68c8b5102 Meta tweaks 2021-05-05 21:40:56 +07:00
Richie Bendall
f8a3642a81
Minor tweaks (#437)
Co-authored-by: Qix <Qix-@users.noreply.github.com>
2021-04-22 15:03:48 +07:00
Richie Bendall
4cf2e40e07
Add overline style and remove keyword, hsl, hsv, hwb and ansi color spaces (#433) 2021-04-22 10:54:42 +07:00
Richie Bendall
0fba91b037
Keep function prototype methods (#434) 2021-04-20 13:48:30 +07:00
Richie Bendall
d798222a5a
Add named exports (#432) 2021-04-17 19:33:03 +07:00
Sindre Sorhus
fa16f4ec37 Require Node.js 12 and move to ESM 2021-04-16 16:22:53 +07:00
Sindre Sorhus
4dab5e1fb6
Meta tweaks 2021-03-13 00:51:42 +07:00
Sindre Sorhus
9bf298571e Meta tweaks 2021-01-30 16:59:16 +07:00
Sindre Sorhus
2a9abb18f4 Rename master branch to main 2021-01-24 14:27:41 +07:00
Sindre Sorhus
97a0861848 Update badge 2021-01-21 10:19:50 +07:00
Sindre Sorhus
0433fcff2a Update a link 2021-01-20 14:45:02 +07:00
Richie Bendall
d5fb377019
Move to GitHub Actions (#426)
* Move to GitHub Actions

* Update readme.md
2021-01-02 20:38:53 +07:00
Sindre Sorhus
ca330532ec
Add @Qix- to funding.yml 2020-12-16 10:09:08 +07:00
Sindre Sorhus
e304e8c230 Add Dev badge 2020-12-08 21:45:51 +07:00
Richie Bendall
02abeebac3
Only iterate through models once (#421) 2020-11-21 20:07:13 +07:00
Toon Baeyens
72299f99a0
remove fixed number of iterations (#406) 2020-11-20 15:26:28 +01:00
Richie Bendall
c0d8e7ed8a
Update test dependencies (#414) 2020-10-03 23:56:24 +02:00
Richie Bendall
b31d6fb48a
Add browser support information (#415) 2020-10-03 23:55:17 +02:00
Sindre Sorhus
445092f9af
Update readme.md 2020-09-09 17:48:28 +02:00
Sindre Sorhus
4c3df88472 4.1.0 2020-06-09 15:43:27 +08:00
Toon Baeyens
09ddbadcb5
Support template literals for nested calls (#392)
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
2020-06-09 15:36:34 +08:00
Steven
55816cdd4d
Update readme links to use https (#396) 2020-04-16 05:56:23 +02:00
Sindre Sorhus
31fa942080 4.0.0 2020-04-02 16:17:06 +08:00
Sindre Sorhus
61999a4e77 Require Node.js 10 2020-04-02 16:10:07 +08:00
Sindre Sorhus
f0f4638a92 Change the TypeScript Level type to be a union instead of enum
Fixes #373
Fixes #382
2020-04-02 15:51:17 +08:00
Richie Bendall
7f21f209da
Properly check if level is an integer (#393) 2020-04-02 15:49:20 +08:00
Bradley Farias
63469d30e4
Use Object.setPrototypeOf as __proto__ could potentially be disabled (#387) 2020-04-02 15:47:12 +08:00
Sindre Sorhus
797461ee32 Meta tweaks 2020-01-01 19:40:12 +01:00
Edwin Kofler
0e6fecc7f7 Add link to replit run (#379) 2019-12-12 21:12:22 +01:00
Sindre Sorhus
20002d8bd1 3.0.0 2019-11-09 13:58:44 +07:00
Sindre Sorhus
b3930189a5 Meta tweaks 2019-11-09 13:57:31 +07:00
Mark Pedrotti
18c280da2e Add ansi and bgAnsi to TypeScript declaration (#369) 2019-11-09 11:22:55 +05:00
Sindre Sorhus
628b5954cf Tidelift tasks 2019-10-30 19:38:56 +07:00
Sindre Sorhus
4de1841129 3.0.0-beta.2 2019-10-08 16:21:40 +07:00
Mark Pedrotti
fb8e85ab87 Add ansi256 and bgAnsi256 to TypeScript declarations (#368) 2019-10-08 16:02:34 +07:00
Mark Pedrotti
eef8c8c191 Replace level list with table in readme.md (#367)
* Replace level list with table in readme.md

* Capitalize table headings and center level numbers
2019-10-01 03:13:15 +02:00
Sindre Sorhus
48905d0805 3.0.0-beta.1 2019-09-27 12:07:07 +07:00
Sindre Sorhus
1953816afd Update dependencies 2019-09-27 11:16:49 +07:00
Yanis Benson
61aca7cb76 Improve require speed (#358) 2019-09-27 10:55:19 +07:00
Khải
4e65299e7b Fix const enum for TypeScript (#364) 2019-09-27 10:53:54 +07:00
Yanis Benson
2a53389d72 Add chalk.stderr (#359) 2019-09-22 16:07:33 +07:00
Simen Bekkhus
6b4d20683f Export TypeScript types for colors and modifiers (#357)
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
2019-08-22 15:28:25 +02:00
Qix
1f77953f1a Remove the .enabled property in favor of .level (#356) 2019-07-13 12:45:31 +07:00
Ahad Birang
87156ce8e2 Fix support for nested styles (#335) 2019-07-13 01:49:56 +07:00
Sindre Sorhus
c25c32a25f Update dependencies 2019-07-12 14:13:58 +07:00
Sindre Sorhus
655653bb0c Meta tweaks 2019-07-12 14:13:02 +07:00
Boris K
af4a078245 Update docs for FORCE_COLOR environment variable (#315) 2019-07-12 14:11:25 +07:00
Yanis Benson
c08417e88c Improve performance greatly (#337) 2019-07-12 13:40:23 +07:00
Qix
983094883c Fix support for bracketed Unicode escapes in template literals (#350) 2019-07-12 13:35:11 +07:00
Marcos Marado
e2dd171597 Remove outdated info in the readme (#351) 2019-06-30 23:11:52 +07:00
Florian Reuschel
d82b2a6638 Add missing false type to chalk.supportsColor (#347) 2019-06-11 00:47:16 +07:00
Sindre Sorhus
4ab4665994 Tidelift tasks 2019-05-31 14:53:04 +07:00
Sindre Sorhus
4990a3578a Add GitHub Sponsors button to the repo 2019-05-23 16:47:28 +07:00
ExE Boss
b3e9b91405 Fix TypeScript types for supportsColor which is top‑level only (#342)
Co-Authored-By: Dimitri Benin <BendingBender@users.noreply.github.com>
2019-05-11 15:04:20 +07:00
Sindre Sorhus
d3be9c65b1 Drop built-in Flow type definition
I don't want to be responsible for maintaining it.

Submit it to https://github.com/flow-typed/flow-typed if you need it.
2019-05-03 15:03:53 +07:00
Dimitri Benin
98628d9f08 Use CommonJS-compatible export in TypeScript definition (#344) 2019-04-28 11:10:44 +07:00
Sindre Sorhus
7b9211be50 Minor refactoring 2019-03-15 00:08:50 +07:00
Sindre Sorhus
cd5de7a2f6
Remove dim style workaround for Windows (#331)
See: https://github.com/chalk/chalk/pull/330/#issuecomment-471977551

The issue seems to have been fixed in newer Windows 10 builds. We're not interested in adding a conditional for older Windows versions as the fix severely complicates the codebase, and it also creates problems for consumers as it makes the output unpredictable.
2019-03-13 00:24:34 +07:00
Sindre Sorhus
2ca015c4c5
Remove the blue color workaround for Windows (#330)
The illegible blue color has been fixed in Windows 10 build 16257: https://blogs.msdn.microsoft.com/commandline/2017/08/02/updating-the-windows-console-colors/

The workaround causes all kinds of problems, so better to remove it than adding conditionals for older Windows versions.

Fixes #329
2019-03-12 20:31:33 +07:00
Sindre Sorhus
3ef170b457 Require Node.js 8 2019-03-12 20:15:36 +07:00
Tom Sherman
de2f4cd606 Deprecate chalk.constructor() in favor of new chalk.Instance() (#322) 2019-03-12 19:53:03 +07:00
Richie Bendall
60959e05cf Update depended packages count 2019-03-01 07:18:47 +01:00
Jonathan Van Buren
7f6e5630b0 Change tagged template literal argument type to accept unknown instead of just string (#316) 2018-12-28 12:13:56 +01:00
Sindre Sorhus
587a5fbcbb Code style tweaks 2018-12-26 03:13:52 +01:00
Chris Harwood
076f0c9eb6 Add extra level/enabled property info in the readme (#308) 2018-12-26 02:29:32 +01:00
Sindre Sorhus
1284415013 Enforce chalk.constructor to be called with new in TypeScript 2018-12-26 02:27:57 +01:00
Sindre Sorhus
cf6615647a Type definition improvements 2018-12-26 02:27:02 +01:00
Sindre Sorhus
4726b1bfda Update dependencies and meta tweaks 2018-12-26 02:18:40 +01:00
George Gkasdrogkas
90c7a92ff1 Add docs comments and tests for TypeScript definitions (#299)
Fixes #293
2018-12-26 02:06:00 +01:00
Sindre Sorhus
f590a65489
Add security section 2018-12-25 14:45:17 +01:00
Timothy Yung
70bb378e8e Strict mode in Flow definition (#309) 2018-11-30 11:34:09 +07:00
Atif Aziz
b827cb0817 Fix ignore chars regex flags in rainbow example (#306)
Use global matches rather than stopping after the first match.
2018-10-27 21:09:54 +07:00
Sindre Sorhus
1542c85f1b Replace RawGit URL
Fixes #305
2018-10-13 12:32:09 +07:00
Sindre Sorhus
8a090d7885 Add Tidelift mention in the readme 2018-09-30 01:41:55 +07:00
Paul Melnikow
b9c95dbfd2 Add type definitions badge (#286) 2018-09-19 02:20:53 +07:00
Chris Harwood
6a14c58e54 Add failing test for #234 (#235) 2018-09-18 15:48:47 +07:00
Sindre Sorhus
2a678789b1 Validate the level option
Fixes #248
2018-09-18 15:33:20 +07:00
Sindre Sorhus
0307f263cb Require Node.js 6 2018-09-18 14:32:14 +07:00
Sindre Sorhus
70f22d87ba Tiny travis.yml tweak 2018-09-01 02:50:53 +07:00
Sindre Sorhus
a2b5fa22dc
Add some badges to the readme 2018-08-06 15:53:00 +07:00
Sindre Sorhus
a6ad945452 Fix XO linting and update some dev dependencies
Fixes #275
2018-05-28 09:16:44 +07:00
Sindre Sorhus
48ba5b0b9b 2.4.1 2018-04-26 12:15:49 +07:00
Jamie
01cfb5c888 Improve Flow type definition for CommonJS interop (#268) 2018-04-26 12:14:22 +07:00
Sindre Sorhus
fc9a7e369b GitHub now natively supports SVG 2018-04-20 13:42:59 +07:00
Sindre Sorhus
af8b3657e9 2.4.0 2018-04-17 11:28:35 +07:00
Saad Quadri
7c6f83f719 Add Flow type definitions (#260) 2018-04-17 11:26:17 +07:00
Sindre Sorhus
58483b5ab1 Add a related package to the readme 2018-04-05 00:43:46 +07:00
Sindre Sorhus
0dae4c28e1
Add Patreon badge 2018-04-02 14:35:53 +07:00
Sindre Sorhus
84f27d4bd8 2.3.2 2018-03-03 00:43:48 +07:00
Sindre Sorhus
245dfa5c6f Bump dependencies
Closes #255
Fixes #254
Fixes #224
2018-03-03 00:42:56 +07:00
Josh Junon
e80f02e2dd Disable unicorn/no-hex-escape for template tests 2018-02-14 18:30:52 -08:00
Josh Junon
925397a0f5 Disable unicorn/no-unsafe-regex for template parser 2018-02-14 18:30:50 -08:00
Josh Junon
52823001a5 Revert "Fix linting"
This reverts commit 12d1276b36.
2018-02-14 18:28:22 -08:00
Sindre Sorhus
12d1276b36 Fix linting 2018-02-15 00:41:45 +07:00
Sindre Sorhus
576d8d2171 Update URL to XO 2018-02-15 00:15:28 +07:00
Sindre Sorhus
ae8a03f2c5 2.3.1 2018-02-11 20:18:25 +07:00
Sindre Sorhus
b55dd79f8b Force bump dependencies
npm is buggy, so doing this just to be sure.
2018-02-11 20:04:55 +07:00
Kayla Washburn
678152cf19 Update chalk to use the latest updates to supports-color (#247) 2018-02-11 16:59:24 +07:00
Aman Pratap Singh
011dd0421e Fix usage example in the readme (#251) 2018-02-11 16:03:50 +07:00
Mario Nebl
6554030550 Use svg screenshot 2018-01-29 07:20:23 -08:00
Samarth Verma
bc3dd75329 Update usage stats in the readme (#242) 2017-12-31 16:20:49 +01:00
Brandon Smith
a8c60e37fa Fix spelling error in readme (#232) 2017-12-09 11:20:28 +01:00
Andrew
5392313414 Correct HSV and HWB examples 2017-10-25 23:33:12 -07:00
38 changed files with 1915 additions and 1097 deletions

3
.gitattributes vendored
View file

@ -1,2 +1 @@
* text=auto
*.js text eol=lf
* text=auto eol=lf

4
.github/funding.yml vendored Normal file
View file

@ -0,0 +1,4 @@
github: [sindresorhus, Qix-]
open_collective: sindresorhus
tidelift: npm/chalk
custom: https://sindresorhus.com/donate

3
.github/security.md vendored Normal file
View file

@ -0,0 +1,3 @@
# Security Policy
To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure.

26
.github/workflows/main.yml vendored Normal file
View file

@ -0,0 +1,26 @@
name: CI
on:
- push
- pull_request
jobs:
test:
name: Node.js ${{ matrix.node-version }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
node-version:
- 18
- 16
- 14
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npm test
- uses: codecov/codecov-action@v2
if: matrix.node-version == 16
with:
fail_ci_if_error: true

View file

@ -1,6 +0,0 @@
language: node_js
node_js:
- '8'
- '6'
- '4'
after_success: npm run coveralls

View file

@ -1,24 +1,57 @@
/* globals set bench */
'use strict';
const chalk = require('.');
/* globals suite, bench */
import chalk from './index.js';
suite('chalk', () => {
set('iterations', 100000);
const chalkRed = chalk.red;
const chalkBgRed = chalk.bgRed;
const chalkBlueBgRed = chalk.blue.bgRed;
const chalkBlueBgRedBold = chalk.blue.bgRed.bold;
bench('single style', () => {
const blueStyledString = 'the fox jumps' + chalk.blue('over the lazy dog') + '!';
bench('1 style', () => {
chalk.red('the fox jumps over the lazy dog');
});
bench('several styles', () => {
bench('2 styles', () => {
chalk.blue.bgRed('the fox jumps over the lazy dog');
});
bench('3 styles', () => {
chalk.blue.bgRed.bold('the fox jumps over the lazy dog');
});
const cached = chalk.blue.bgRed.bold;
bench('cached styles', () => {
cached('the fox jumps over the lazy dog');
bench('cached: 1 style', () => {
chalkRed('the fox jumps over the lazy dog');
});
bench('nested styles', () => {
chalk.red('the fox jumps', chalk.underline.bgBlue('over the lazy dog') + '!');
bench('cached: 2 styles', () => {
chalkBlueBgRed('the fox jumps over the lazy dog');
});
bench('cached: 3 styles', () => {
chalkBlueBgRedBold('the fox jumps over the lazy dog');
});
bench('cached: 1 style with newline', () => {
chalkRed('the fox jumps\nover the lazy dog');
});
bench('cached: 1 style nested intersecting', () => {
chalkRed(blueStyledString);
});
bench('cached: 1 style nested non-intersecting', () => {
chalkBgRed(blueStyledString);
});
bench('cached: 1 style template literal', () => {
// eslint-disable-next-line no-unused-expressions
chalkRed`the fox jumps over the lazy dog`;
});
bench('cached: nested styles template literal', () => {
// eslint-disable-next-line no-unused-expressions
chalkRed`the fox {bold jumps} over the {underline lazy} dog`;
});
});

View file

@ -1,38 +1,38 @@
'use strict';
const chalk = require('..');
import {setTimeout as delay} from 'node:timers/promises';
import convertColor from 'color-convert';
import updateLog from 'log-update';
import chalk from '../source/index.js';
const ignoreChars = /[^!-~]/;
const ignoreChars = /[^!-~]/g;
function rainbow(str, offset) {
if (!str || str.length === 0) {
return str;
function rainbow(string, offset) {
if (!string || string.length === 0) {
return string;
}
const hueStep = 360 / str.replace(ignoreChars, '').length;
const hueStep = 360 / string.replaceAll(ignoreChars, '').length;
let hue = offset % 360;
const chars = [];
for (const c of str) {
if (c.match(ignoreChars)) {
chars.push(c);
const characters = [];
for (const character of string) {
if (ignoreChars.test(character)) {
characters.push(character);
} else {
chars.push(chalk.hsl(hue, 100, 50)(c));
characters.push(chalk.hex(convertColor.hsl.hex(hue, 100, 50))(character));
hue = (hue + hueStep) % 360;
}
}
return chars.join('');
return characters.join('');
}
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function animateString(str) {
console.log();
for (let i = 0; i < 360 * 5; i++) {
console.log('\u001B[1F\u001B[G ', rainbow(str, i));
await sleep(2); // eslint-disable-line no-await-in-loop
async function animateString(string) {
for (let index = 0; index < 360 * 5; index++) {
updateLog(rainbow(string, index));
await delay(2); // eslint-disable-line no-await-in-loop
}
}
console.log();
animateString('We hope you enjoy the new version of Chalk 2! <3').then(() => console.log());
await animateString('We hope you enjoy Chalk! <3');
console.log();

View file

@ -1,18 +1,27 @@
'use strict';
const chalk = require('..');
const styles = require('ansi-styles');
import process from 'node:process';
import styles from 'ansi-styles';
import chalk from '../source/index.js';
// Generates screenshot
for (const key of Object.keys(styles)) {
let ret = key;
let returnValue = key;
if (key === 'reset' || key === 'hidden' || key === 'grey') {
// We skip `overline` as almost no terminal supports it so we cannot show it off.
if (
key === 'reset'
|| key === 'hidden'
|| key === 'grey'
|| key === 'bgGray'
|| key === 'bgGrey'
|| key === 'overline'
|| key.endsWith('Bright')
) {
continue;
}
if (/^bg[^B]/.test(key)) {
ret = chalk.black(ret);
returnValue = chalk.black(returnValue);
}
process.stdout.write(chalk[key](ret) + ' ');
process.stdout.write(chalk[key](returnValue) + ' ');
}

228
index.js
View file

@ -1,228 +0,0 @@
'use strict';
const escapeStringRegexp = require('escape-string-regexp');
const ansiStyles = require('ansi-styles');
const supportsColor = require('supports-color');
const template = require('./templates.js');
const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm');
// `supportsColor.level` → `ansiStyles.color[name]` mapping
const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
// `color-convert` models to exclude from the Chalk API due to conflicts and such
const skipModels = new Set(['gray']);
const styles = Object.create(null);
function applyOptions(obj, options) {
options = options || {};
// Detect level if not set manually
const scLevel = supportsColor ? supportsColor.level : 0;
obj.level = options.level === undefined ? scLevel : options.level;
obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
}
function Chalk(options) {
// We check for this.template here since calling `chalk.constructor()`
// by itself will have a `this` of a previously constructed chalk object
if (!this || !(this instanceof Chalk) || this.template) {
const chalk = {};
applyOptions(chalk, options);
chalk.template = function () {
const args = [].slice.call(arguments);
return chalkTag.apply(null, [chalk.template].concat(args));
};
Object.setPrototypeOf(chalk, Chalk.prototype);
Object.setPrototypeOf(chalk.template, chalk);
chalk.template.constructor = Chalk;
return chalk.template;
}
applyOptions(this, options);
}
// Use bright blue on Windows as the normal blue color is illegible
if (isSimpleWindowsTerm) {
ansiStyles.blue.open = '\u001B[94m';
}
for (const key of Object.keys(ansiStyles)) {
ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
styles[key] = {
get() {
const codes = ansiStyles[key];
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
}
};
}
styles.visible = {
get() {
return build.call(this, this._styles || [], true, 'visible');
}
};
ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
for (const model of Object.keys(ansiStyles.color.ansi)) {
if (skipModels.has(model)) {
continue;
}
styles[model] = {
get() {
const level = this.level;
return function () {
const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
const codes = {
open,
close: ansiStyles.color.close,
closeRe: ansiStyles.color.closeRe
};
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
};
}
};
}
ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
if (skipModels.has(model)) {
continue;
}
const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
styles[bgModel] = {
get() {
const level = this.level;
return function () {
const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
const codes = {
open,
close: ansiStyles.bgColor.close,
closeRe: ansiStyles.bgColor.closeRe
};
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
};
}
};
}
const proto = Object.defineProperties(() => {}, styles);
function build(_styles, _empty, key) {
const builder = function () {
return applyStyle.apply(builder, arguments);
};
builder._styles = _styles;
builder._empty = _empty;
const self = this;
Object.defineProperty(builder, 'level', {
enumerable: true,
get() {
return self.level;
},
set(level) {
self.level = level;
}
});
Object.defineProperty(builder, 'enabled', {
enumerable: true,
get() {
return self.enabled;
},
set(enabled) {
self.enabled = enabled;
}
});
// See below for fix regarding invisible grey/dim combination on Windows
builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey';
// `__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
return builder;
}
function applyStyle() {
// Support varags, but simply cast to string in case there's only one arg
const args = arguments;
const argsLen = args.length;
let str = String(arguments[0]);
if (argsLen === 0) {
return '';
}
if (argsLen > 1) {
// Don't slice `arguments`, it prevents V8 optimizations
for (let a = 1; a < argsLen; a++) {
str += ' ' + args[a];
}
}
if (!this.enabled || this.level <= 0 || !str) {
return this._empty ? '' : str;
}
// Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
// see https://github.com/chalk/chalk/issues/58
// If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
const originalDim = ansiStyles.dim.open;
if (isSimpleWindowsTerm && this.hasGrey) {
ansiStyles.dim.open = '';
}
for (const code of this._styles.slice().reverse()) {
// 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'.
str = code.open + str.replace(code.closeRe, code.open) + code.close;
// 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
str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
}
// Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
ansiStyles.dim.open = originalDim;
return str;
}
function chalkTag(chalk, strings) {
if (!Array.isArray(strings)) {
// If chalk() was called by itself or with a string,
// return the string itself as a string.
return [].slice.call(arguments, 1).join(' ');
}
const args = [].slice.call(arguments, 2);
const parts = [strings.raw[0]];
for (let i = 1; i < strings.length; i++) {
parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
parts.push(String(strings.raw[i]));
}
return template(chalk, parts.join(''));
}
Object.defineProperties(Chalk.prototype, styles);
module.exports = Chalk(); // eslint-disable-line new-cap
module.exports.supportsColor = supportsColor;
module.exports.default = module.exports; // For TypeScript

View file

@ -1,6 +1,6 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://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:

BIN
media/screenshot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 235 KiB

View file

@ -1,21 +1,32 @@
{
"name": "chalk",
"version": "2.3.0",
"version": "5.6.2",
"description": "Terminal string styling done right",
"license": "MIT",
"repository": "chalk/chalk",
"funding": "https://github.com/chalk/chalk?sponsor=1",
"type": "module",
"main": "./source/index.js",
"exports": "./source/index.js",
"imports": {
"#ansi-styles": "./source/vendor/ansi-styles/index.js",
"#supports-color": {
"node": "./source/vendor/supports-color/index.js",
"default": "./source/vendor/supports-color/browser.js"
}
},
"types": "./source/index.d.ts",
"sideEffects": false,
"engines": {
"node": ">=4"
"node": "^12.17.0 || ^14.13 || >=16.0.0"
},
"scripts": {
"test": "xo && tsc --project types && nyc ava",
"bench": "matcha benchmark.js",
"coveralls": "nyc report --reporter=text-lcov | coveralls"
"test": "xo && c8 ava && tsd",
"bench": "matcha benchmark.js"
},
"files": [
"index.js",
"templates.js",
"types/index.d.ts"
"source",
"!source/index.test-d.ts"
],
"keywords": [
"color",
@ -25,7 +36,6 @@
"console",
"cli",
"string",
"str",
"ansi",
"style",
"styles",
@ -40,27 +50,34 @@
"command-line",
"text"
],
"dependencies": {
"ansi-styles": "^3.1.0",
"escape-string-regexp": "^1.0.5",
"supports-color": "^4.0.0"
},
"devDependencies": {
"ava": "*",
"coveralls": "^3.0.0",
"execa": "^0.8.0",
"import-fresh": "^2.0.0",
"@types/node": "^16.11.10",
"ava": "^3.15.0",
"c8": "^7.10.0",
"color-convert": "^2.0.1",
"execa": "^6.0.0",
"log-update": "^5.0.0",
"matcha": "^0.7.0",
"nyc": "^11.0.2",
"resolve-from": "^4.0.0",
"typescript": "^2.5.3",
"xo": "*"
"tsd": "^0.19.0",
"xo": "^0.57.0",
"yoctodelay": "^2.0.0"
},
"types": "types/index.d.ts",
"xo": {
"envs": [
"node",
"mocha"
"rules": {
"unicorn/prefer-string-slice": "off",
"@typescript-eslint/consistent-type-imports": "off",
"@typescript-eslint/consistent-type-exports": "off",
"@typescript-eslint/consistent-type-definitions": "off",
"unicorn/expiring-todo-comments": "off"
}
},
"c8": {
"reporter": [
"text",
"lcov"
],
"exclude": [
"source/vendor"
]
}
}

196
readme.md
View file

@ -1,7 +1,7 @@
<h1 align="center">
<br>
<br>
<img width="320" src="https://cdn.rawgit.com/chalk/chalk/19935d6484811c5e468817f846b7b3d417d7bf4a/logo.svg" alt="chalk">
<img width="320" src="media/logo.svg" alt="Chalk">
<br>
<br>
<br>
@ -9,37 +9,42 @@
> 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) [![](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/sindresorhus/xo) [![Mentioned in Awesome Node.js](https://awesome.re/mentioned-badge.svg)](https://github.com/sindresorhus/awesome-nodejs)
[![Coverage Status](https://codecov.io/gh/chalk/chalk/branch/main/graph/badge.svg)](https://codecov.io/gh/chalk/chalk)
[![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)
### [See what's new in Chalk 2](https://github.com/chalk/chalk/releases/tag/v2.0.0)
![](media/screenshot.png)
![](https://github.com/chalk/ansi-styles/raw/master/screenshot.png)
## Info
- [Why not switch to a smaller coloring package?](https://github.com/chalk/chalk?tab=readme-ov-file#why-not-switch-to-a-smaller-coloring-package)
- See [yoctocolors](https://github.com/sindresorhus/yoctocolors) for a smaller alternative
## Highlights
- Expressive API
- Highly performant
- No dependencies
- 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 ~17,000 packages](https://www.npmjs.com/browse/depended/chalk) as of June 20th, 2017
- [Used by ~115,000 packages](https://www.npmjs.com/browse/depended/chalk) as of July 4, 2024
## Install
```console
$ npm install chalk
```sh
npm install chalk
```
**IMPORTANT:** Chalk 5 is ESM. If you want to use Chalk with TypeScript or a build tool, you will probably want to use Chalk 4 for now. [Read more.](https://github.com/chalk/chalk/releases/tag/v5.0.0)
## Usage
```js
const chalk = require('chalk');
import chalk from 'chalk';
console.log(chalk.blue('Hello world!'));
```
@ -47,11 +52,12 @@ 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');
import chalk from 'chalk';
const log = console.log;
// Combine styled and normal strings
log(chalk.blue('Hello') + 'World' + chalk.red('!'));
log(chalk.blue('Hello') + ' World' + chalk.red('!'));
// Compose multiple styles using the chainable API
log(chalk.blue.bgRed.bold('Hello world!'));
@ -76,15 +82,7 @@ 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!'));
```
@ -92,10 +90,10 @@ log(chalk.hex('#DEADED').bold('Bold gray!'));
Easily define your own themes:
```js
const chalk = require('chalk');
import chalk from 'chalk';
const error = chalk.bold.red;
const warning = chalk.keyword('orange');
const warning = chalk.hex('#FFA500'); // Orange color
console.log(error('Error!'));
console.log(warning('Warning!'));
@ -104,12 +102,13 @@ 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
import chalk from 'chalk';
const name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
//=> 'Hello Sindre'
```
## API
### chalk.`<style>[.<style>...](string, [string...])`
@ -120,57 +119,69 @@ Chain [styles](#styles) and call the last one as a method with a string argument
Multiple arguments will be separated by space.
### chalk.enabled
Color support is automatically detected, as is the level (see `chalk.level`). However, if you'd like to simply enable/disable Chalk, you can do so via the `.enabled` property.
Chalk is enabled by default unless expicitly disabled via the constructor or `chalk.level` is `0`.
If you need to change this in a reusable module, create a new instance:
```js
const ctx = new chalk.constructor({enabled: false});
```
### 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.constructor({level: 0});
import {Chalk} from 'chalk';
const customChalk = new Chalk({level: 0});
```
Levels are as follows:
| Level | Description |
| :---: | :--- |
| `0` | All colors disabled |
| `1` | Basic color support (16 colors) |
| `2` | 256 color support |
| `3` | Truecolor support (16 million colors) |
0. All colors disabled
1. Basic color support (16 colors)
2. 256 color support
3. Truecolor support (16 million colors)
### chalk.supportsColor
### 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, add the environment variable `FORCE_COLOR=1` to forcefully enable color or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks.
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.
### chalkStderr and supportsColorStderr
`chalkStderr` contains a separate instance configured with color support detected for `stderr` stream instead of `stdout`. Override rules from `supportsColor` apply to this too. `supportsColorStderr` is exposed for convenience.
### modifierNames, foregroundColorNames, backgroundColorNames, and colorNames
All supported style strings are exposed as an array of strings for convenience. `colorNames` is the combination of `foregroundColorNames` and `backgroundColorNames`.
This can be useful if you wrap Chalk and need to validate input:
```js
import {modifierNames, foregroundColorNames} from 'chalk';
console.log(modifierNames.includes('bold'));
//=> true
console.log(foregroundColorNames.includes('pink'));
//=> false
```
## Styles
### Modifiers
- `reset`
- `bold`
- `dim`
- `italic` *(Not widely supported)*
- `underline`
- `inverse`
- `hidden`
- `strikethrough` *(Not widely supported)*
- `visible` (Text is emitted only if enabled)
- `reset` - Reset the current style.
- `bold` - Make the text bold.
- `dim` - Make the text have lower opacity.
- `italic` - Make the text italic. *(Not widely supported)*
- `underline` - Put a horizontal line below the text. *(Not widely supported)*
- `overline` - Put a horizontal line above the text. *(Not widely supported)*
- `inverse` - Invert background and foreground colors.
- `hidden` - Print the text but make it invisible.
- `strikethrough` - Puts a horizontal line through the center of the text. *(Not widely supported)*
- `visible` - Print the text only when Chalk has a color level above zero. Can be useful for things that are purely cosmetic.
### Colors
@ -178,11 +189,11 @@ Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=
- `red`
- `green`
- `yellow`
- `blue` *(On Windows the bright version is used since normal blue is illegible)*
- `blue`
- `magenta`
- `cyan`
- `white`
- `gray` ("bright black")
- `blackBright` (alias: `gray`, `grey`)
- `redBright`
- `greenBright`
- `yellowBright`
@ -201,7 +212,7 @@ Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=
- `bgMagenta`
- `bgCyan`
- `bgWhite`
- `bgBlackBright`
- `bgBlackBright` (alias: `bgGray`, `bgGrey`)
- `bgRedBright`
- `bgGreenBright`
- `bgYellowBright`
@ -210,79 +221,59 @@ Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=
- `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.
Chalk supports 256 colors and [Truecolor](https://github.com/termstandard/colors) (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).
Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `hex` for foreground colors and `bgHex` 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.hsl(32, 1, 1).bold('Orange!')`
- [`hwb`](https://en.wikipedia.org/wiki/HWB_color_model) - Example: `chalk.hsl(32, 0, 50).bold('Orange!')`
- `ansi16`
- `ansi256`
- [`ansi256`](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) - Example: `chalk.bgAnsi256(194)('Honeydew, more or less')`
## Browser support
Since Chrome 69, ANSI escape codes are natively supported in the developer console.
## Windows
If you're on Windows, do yourself a favor and use [`cmder`](http://cmder.net/) instead of `cmd.exe`.
If you're on Windows, do yourself a favor and use [Windows Terminal](https://github.com/microsoft/terminal) instead of `cmd.exe`.
## FAQ
## Origin story
### Why not switch to a smaller coloring package?
[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 may be larger, but there is a reason for that. It offers a more user-friendly API, well-documented types, supports millions of colors, and covers edge cases that smaller alternatives miss. Chalk is mature, reliable, and built to last.
But beyond the technical aspects, there's something more critical: trust and long-term maintenance. I have been active in open source for over a decade, and I'm committed to keeping Chalk maintained. Smaller packages might seem appealing now, but there's no guarantee they will be around for the long term, or that they won't become malicious over time.
Chalk is also likely already in your dependency tree (since 100K+ packages depend on it), so switching wont save space—in fact, it might increase it. npm deduplicates dependencies, so multiple Chalk instances turn into one, but adding another package alongside it will increase your overall size.
If the goal is to clean up the ecosystem, switching away from Chalk wont even make a dent. The real problem lies with packages that have very deep dependency trees (for example, those including a lot of polyfills). Chalk has no dependencies. It's better to focus on impactful changes rather than minor optimizations.
If absolute package size is important to you, I also maintain [yoctocolors](https://github.com/sindresorhus/yoctocolors), one of the smallest color packages out there.
*\- [Sindre](https://github.com/sindresorhus)*
### But the smaller coloring package has benchmarks showing it is faster
[Micro-benchmarks are flawed](https://sindresorhus.com/blog/micro-benchmark-fallacy) because they measure performance in unrealistic, isolated scenarios, often giving a distorted view of real-world performance. Don't believe marketing fluff. All the coloring packages are more than fast enough.
## Related
- [chalk-template](https://github.com/chalk/chalk-template) - [Tagged template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates) support for this module
- [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
@ -296,14 +287,11 @@ If you're on Windows, do yourself a favor and use [`cmder`](http://cmder.net/) i
- [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
*(Not accepting additional entries)*
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)
## License
MIT

325
source/index.d.ts vendored Normal file
View file

@ -0,0 +1,325 @@
// TODO: Make it this when TS suports that.
// import {ModifierName, ForegroundColor, BackgroundColor, ColorName} from '#ansi-styles';
// import {ColorInfo, ColorSupportLevel} from '#supports-color';
import {
ModifierName,
ForegroundColorName,
BackgroundColorName,
ColorName,
} from './vendor/ansi-styles/index.js';
import {ColorInfo, ColorSupportLevel} from './vendor/supports-color/index.js';
export 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.
*/
readonly level?: ColorSupportLevel;
}
/**
Return a new Chalk instance.
*/
export const Chalk: new (options?: Options) => ChalkInstance; // eslint-disable-line @typescript-eslint/naming-convention
export interface ChalkInstance {
(...text: unknown[]): string;
/**
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: ColorSupportLevel;
/**
Use RGB values to set text color.
@example
```
import chalk from 'chalk';
chalk.rgb(222, 173, 237);
```
*/
rgb: (red: number, green: number, blue: number) => this;
/**
Use HEX value to set text color.
@param color - Hexadecimal value representing the desired color.
@example
```
import chalk from 'chalk';
chalk.hex('#DEADED');
```
*/
hex: (color: string) => this;
/**
Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color.
@example
```
import chalk from 'chalk';
chalk.ansi256(201);
```
*/
ansi256: (index: number) => this;
/**
Use RGB values to set background color.
@example
```
import chalk from 'chalk';
chalk.bgRgb(222, 173, 237);
```
*/
bgRgb: (red: number, green: number, blue: number) => this;
/**
Use HEX value to set background color.
@param color - Hexadecimal value representing the desired color.
@example
```
import chalk from 'chalk';
chalk.bgHex('#DEADED');
```
*/
bgHex: (color: string) => this;
/**
Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color.
@example
```
import chalk from 'chalk';
chalk.bgAnsi256(201);
```
*/
bgAnsi256: (index: number) => this;
/**
Modifier: Reset the current style.
*/
readonly reset: this;
/**
Modifier: Make the text bold.
*/
readonly bold: this;
/**
Modifier: Make the text have lower opacity.
*/
readonly dim: this;
/**
Modifier: Make the text italic. *(Not widely supported)*
*/
readonly italic: this;
/**
Modifier: Put a horizontal line below the text. *(Not widely supported)*
*/
readonly underline: this;
/**
Modifier: Put a horizontal line above the text. *(Not widely supported)*
*/
readonly overline: this;
/**
Modifier: Invert background and foreground colors.
*/
readonly inverse: this;
/**
Modifier: Print the text but make it invisible.
*/
readonly hidden: this;
/**
Modifier: Puts a horizontal line through the center of the text. *(Not widely supported)*
*/
readonly strikethrough: this;
/**
Modifier: Print the text only when Chalk has a color level above zero.
Can be useful for things that are purely cosmetic.
*/
readonly visible: this;
readonly black: this;
readonly red: this;
readonly green: this;
readonly yellow: this;
readonly blue: this;
readonly magenta: this;
readonly cyan: this;
readonly white: this;
/*
Alias for `blackBright`.
*/
readonly gray: this;
/*
Alias for `blackBright`.
*/
readonly grey: this;
readonly blackBright: this;
readonly redBright: this;
readonly greenBright: this;
readonly yellowBright: this;
readonly blueBright: this;
readonly magentaBright: this;
readonly cyanBright: this;
readonly whiteBright: this;
readonly bgBlack: this;
readonly bgRed: this;
readonly bgGreen: this;
readonly bgYellow: this;
readonly bgBlue: this;
readonly bgMagenta: this;
readonly bgCyan: this;
readonly bgWhite: this;
/*
Alias for `bgBlackBright`.
*/
readonly bgGray: this;
/*
Alias for `bgBlackBright`.
*/
readonly bgGrey: this;
readonly bgBlackBright: this;
readonly bgRedBright: this;
readonly bgGreenBright: this;
readonly bgYellowBright: this;
readonly bgBlueBright: this;
readonly bgMagentaBright: this;
readonly bgCyanBright: this;
readonly bgWhiteBright: this;
}
/**
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: ChalkInstance;
export const supportsColor: ColorInfo;
export const chalkStderr: typeof chalk;
export const supportsColorStderr: typeof supportsColor;
export {
ModifierName, ForegroundColorName, BackgroundColorName, ColorName,
modifierNames, foregroundColorNames, backgroundColorNames, colorNames,
// } from '#ansi-styles';
} from './vendor/ansi-styles/index.js';
export {
ColorInfo,
ColorSupport,
ColorSupportLevel,
// } from '#supports-color';
} from './vendor/supports-color/index.js';
// TODO: Remove these aliases in the next major version
/**
@deprecated Use `ModifierName` instead.
Basic modifier names.
*/
export type Modifiers = ModifierName;
/**
@deprecated Use `ForegroundColorName` instead.
Basic foreground color names.
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
*/
export type ForegroundColor = ForegroundColorName;
/**
@deprecated Use `BackgroundColorName` instead.
Basic background color names.
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
*/
export type BackgroundColor = BackgroundColorName;
/**
@deprecated Use `ColorName` instead.
Basic color names. The combination of foreground and background color names.
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
*/
export type Color = ColorName;
/**
@deprecated Use `modifierNames` instead.
Basic modifier names.
*/
export const modifiers: readonly Modifiers[];
/**
@deprecated Use `foregroundColorNames` instead.
Basic foreground color names.
*/
export const foregroundColors: readonly ForegroundColor[];
/**
@deprecated Use `backgroundColorNames` instead.
Basic background color names.
*/
export const backgroundColors: readonly BackgroundColor[];
/**
@deprecated Use `colorNames` instead.
Basic color names. The combination of foreground and background color names.
*/
export const colors: readonly Color[];
export default chalk;

225
source/index.js Normal file
View file

@ -0,0 +1,225 @@
import ansiStyles from '#ansi-styles';
import supportsColor from '#supports-color';
import { // eslint-disable-line import/order
stringReplaceAll,
stringEncaseCRLFWithFirstIndex,
} from './utilities.js';
const {stdout: stdoutColor, stderr: stderrColor} = supportsColor;
const GENERATOR = Symbol('GENERATOR');
const STYLER = Symbol('STYLER');
const IS_EMPTY = Symbol('IS_EMPTY');
// `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;
};
export class Chalk {
constructor(options) {
// eslint-disable-next-line no-constructor-return
return chalkFactory(options);
}
}
const chalkFactory = options => {
const chalk = (...strings) => strings.join(' ');
applyOptions(chalk, options);
Object.setPrototypeOf(chalk, createChalk.prototype);
return chalk;
};
function createChalk(options) {
return chalkFactory(options);
}
Object.setPrototypeOf(createChalk.prototype, Function.prototype);
for (const [styleName, style] of Object.entries(ansiStyles)) {
styles[styleName] = {
get() {
const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
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 getModelAnsi = (model, level, type, ...arguments_) => {
if (model === 'rgb') {
if (level === 'ansi16m') {
return ansiStyles[type].ansi16m(...arguments_);
}
if (level === 'ansi256') {
return ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_));
}
return ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_));
}
if (model === 'hex') {
return getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_));
}
return ansiStyles[type][model](...arguments_);
};
const usedModels = ['rgb', 'hex', 'ansi256'];
for (const model of usedModels) {
styles[model] = {
get() {
const {level} = this;
return function (...arguments_) {
const styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]);
return createBuilder(this, styler, this[IS_EMPTY]);
};
},
};
const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
styles[bgModel] = {
get() {
const {level} = this;
return function (...arguments_) {
const styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]);
return createBuilder(this, styler, this[IS_EMPTY]);
};
},
};
}
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) => {
// Single argument is hot path, implicit coercion is faster than anything
// eslint-disable-next-line no-implicit-coercion
const builder = (...arguments_) => 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[IS_EMPTY] = _isEmpty;
return builder;
};
const applyStyle = (self, string) => {
if (self.level <= 0 || !string) {
return self[IS_EMPTY] ? '' : string;
}
let styler = self[STYLER];
if (styler === undefined) {
return string;
}
const {openAll, closeAll} = styler;
if (string.includes('\u001B')) {
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;
};
Object.defineProperties(createChalk.prototype, styles);
const chalk = createChalk();
export const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0});
export {
modifierNames,
foregroundColorNames,
backgroundColorNames,
colorNames,
// TODO: Remove these aliases in the next major version
modifierNames as modifiers,
foregroundColorNames as foregroundColors,
backgroundColorNames as backgroundColors,
colorNames as colors,
} from './vendor/ansi-styles/index.js';
export {
stdoutColor as supportsColor,
stderrColor as supportsColorStderr,
};
export default chalk;

179
source/index.test-d.ts Normal file
View file

@ -0,0 +1,179 @@
import {
expectType,
expectAssignable,
expectError,
expectDeprecated,
} from 'tsd';
import chalk, {
Chalk,
ChalkInstance,
ColorInfo,
ColorSupport,
ColorSupportLevel,
chalkStderr,
supportsColor,
supportsColorStderr,
ModifierName,
ForegroundColorName,
BackgroundColorName,
ColorName,
Modifiers,
} from './index.js';
// - supportsColor -
expectType<ColorInfo>(supportsColor);
if (supportsColor) {
expectType<ColorSupport>(supportsColor);
expectType<ColorSupportLevel>(supportsColor.level);
expectType<boolean>(supportsColor.hasBasic);
expectType<boolean>(supportsColor.has256);
expectType<boolean>(supportsColor.has16m);
}
// - stderr -
expectAssignable<ChalkInstance>(chalkStderr);
expectType<ColorInfo>(supportsColorStderr);
if (supportsColorStderr) {
expectType<boolean>(supportsColorStderr.hasBasic);
expectType<boolean>(supportsColorStderr.has256);
expectType<boolean>(supportsColorStderr.has16m);
}
// -- `supportsColorStderr` is not a member of the Chalk interface --
expectError(chalk.reset.supportsColorStderr);
// -- `supportsColor` is not a member of the Chalk interface --
expectError(chalk.reset.supportsColor);
// - Chalk -
// -- Instance --
expectType<ChalkInstance>(new Chalk({level: 1}));
// -- Properties --
expectType<ColorSupportLevel>(chalk.level);
// -- Color methods --
expectType<ChalkInstance>(chalk.rgb(0, 0, 0));
expectType<ChalkInstance>(chalk.hex('#DEADED'));
expectType<ChalkInstance>(chalk.ansi256(0));
expectType<ChalkInstance>(chalk.bgRgb(0, 0, 0));
expectType<ChalkInstance>(chalk.bgHex('#DEADED'));
expectType<ChalkInstance>(chalk.bgAnsi256(0));
// -- Modifiers --
expectType<string>(chalk.reset('foo'));
expectType<string>(chalk.bold('foo'));
expectType<string>(chalk.dim('foo'));
expectType<string>(chalk.italic('foo'));
expectType<string>(chalk.underline('foo'));
expectType<string>(chalk.overline('foo'));
expectType<string>(chalk.inverse('foo'));
expectType<string>(chalk.hidden('foo'));
expectType<string>(chalk.strikethrough('foo'));
expectType<string>(chalk.visible('foo'));
expectType<string>(chalk.reset`foo`);
expectType<string>(chalk.bold`foo`);
expectType<string>(chalk.dim`foo`);
expectType<string>(chalk.italic`foo`);
expectType<string>(chalk.underline`foo`);
expectType<string>(chalk.inverse`foo`);
expectType<string>(chalk.hidden`foo`);
expectType<string>(chalk.strikethrough`foo`);
expectType<string>(chalk.visible`foo`);
// -- Colors --
expectType<string>(chalk.black('foo'));
expectType<string>(chalk.red('foo'));
expectType<string>(chalk.green('foo'));
expectType<string>(chalk.yellow('foo'));
expectType<string>(chalk.blue('foo'));
expectType<string>(chalk.magenta('foo'));
expectType<string>(chalk.cyan('foo'));
expectType<string>(chalk.white('foo'));
expectType<string>(chalk.gray('foo'));
expectType<string>(chalk.grey('foo'));
expectType<string>(chalk.blackBright('foo'));
expectType<string>(chalk.redBright('foo'));
expectType<string>(chalk.greenBright('foo'));
expectType<string>(chalk.yellowBright('foo'));
expectType<string>(chalk.blueBright('foo'));
expectType<string>(chalk.magentaBright('foo'));
expectType<string>(chalk.cyanBright('foo'));
expectType<string>(chalk.whiteBright('foo'));
expectType<string>(chalk.bgBlack('foo'));
expectType<string>(chalk.bgRed('foo'));
expectType<string>(chalk.bgGreen('foo'));
expectType<string>(chalk.bgYellow('foo'));
expectType<string>(chalk.bgBlue('foo'));
expectType<string>(chalk.bgMagenta('foo'));
expectType<string>(chalk.bgCyan('foo'));
expectType<string>(chalk.bgWhite('foo'));
expectType<string>(chalk.bgBlackBright('foo'));
expectType<string>(chalk.bgRedBright('foo'));
expectType<string>(chalk.bgGreenBright('foo'));
expectType<string>(chalk.bgYellowBright('foo'));
expectType<string>(chalk.bgBlueBright('foo'));
expectType<string>(chalk.bgMagentaBright('foo'));
expectType<string>(chalk.bgCyanBright('foo'));
expectType<string>(chalk.bgWhiteBright('foo'));
expectType<string>(chalk.black`foo`);
expectType<string>(chalk.red`foo`);
expectType<string>(chalk.green`foo`);
expectType<string>(chalk.yellow`foo`);
expectType<string>(chalk.blue`foo`);
expectType<string>(chalk.magenta`foo`);
expectType<string>(chalk.cyan`foo`);
expectType<string>(chalk.white`foo`);
expectType<string>(chalk.gray`foo`);
expectType<string>(chalk.grey`foo`);
expectType<string>(chalk.blackBright`foo`);
expectType<string>(chalk.redBright`foo`);
expectType<string>(chalk.greenBright`foo`);
expectType<string>(chalk.yellowBright`foo`);
expectType<string>(chalk.blueBright`foo`);
expectType<string>(chalk.magentaBright`foo`);
expectType<string>(chalk.cyanBright`foo`);
expectType<string>(chalk.whiteBright`foo`);
expectType<string>(chalk.bgBlack`foo`);
expectType<string>(chalk.bgRed`foo`);
expectType<string>(chalk.bgGreen`foo`);
expectType<string>(chalk.bgYellow`foo`);
expectType<string>(chalk.bgBlue`foo`);
expectType<string>(chalk.bgMagenta`foo`);
expectType<string>(chalk.bgCyan`foo`);
expectType<string>(chalk.bgWhite`foo`);
expectType<string>(chalk.bgBlackBright`foo`);
expectType<string>(chalk.bgRedBright`foo`);
expectType<string>(chalk.bgGreenBright`foo`);
expectType<string>(chalk.bgYellowBright`foo`);
expectType<string>(chalk.bgBlueBright`foo`);
expectType<string>(chalk.bgMagentaBright`foo`);
expectType<string>(chalk.bgCyanBright`foo`);
expectType<string>(chalk.bgWhiteBright`foo`);
// -- Complex --
expectType<string>(chalk.red.bgGreen.underline('foo'));
expectType<string>(chalk.underline.red.bgGreen('foo'));
// -- Complex template literal --
expectType<string>(chalk.underline``);
expectType<string>(chalk.red.bgGreen.bold`Hello {italic.blue ${name}}`);
expectType<string>(chalk.strikethrough.cyanBright.bgBlack`Works with {reset {bold numbers}} {bold.red ${1}}`);
// -- Modifiers types
expectAssignable<ModifierName>('strikethrough');
expectError<ModifierName>('delete');
// -- Foreground types
expectAssignable<ForegroundColorName>('red');
expectError<ForegroundColorName>('pink');
// -- Background types
expectAssignable<BackgroundColorName>('bgRed');
expectError<BackgroundColorName>('bgPink');
// -- Color types --
expectAssignable<ColorName>('red');
expectAssignable<ColorName>('bgRed');
expectError<ColorName>('hotpink');
expectError<ColorName>('bgHotpink');

33
source/utilities.js Normal file
View file

@ -0,0 +1,33 @@
// TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.
export function 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.slice(endIndex, index) + substring + replacer;
endIndex = index + substringLength;
index = string.indexOf(substring, endIndex);
} while (index !== -1);
returnValue += string.slice(endIndex);
return returnValue;
}
export function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
let endIndex = 0;
let returnValue = '';
do {
const gotCR = string[index - 1] === '\r';
returnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
endIndex = index + 1;
index = string.indexOf('\n', endIndex);
} while (index !== -1);
returnValue += string.slice(endIndex);
return returnValue;
}

236
source/vendor/ansi-styles/index.d.ts vendored Normal file
View file

@ -0,0 +1,236 @@
export interface CSPair { // eslint-disable-line @typescript-eslint/naming-convention
/**
The ANSI terminal control sequence for starting this style.
*/
readonly open: string;
/**
The ANSI terminal control sequence for ending this style.
*/
readonly close: string;
}
export interface ColorBase {
/**
The ANSI terminal control sequence for ending this color.
*/
readonly close: string;
ansi(code: number): string;
ansi256(code: number): string;
ansi16m(red: number, green: number, blue: number): string;
}
export interface Modifier {
/**
Resets the current color chain.
*/
readonly reset: CSPair;
/**
Make text bold.
*/
readonly bold: CSPair;
/**
Emitting only a small amount of light.
*/
readonly dim: CSPair;
/**
Make text italic. (Not widely supported)
*/
readonly italic: CSPair;
/**
Make text underline. (Not widely supported)
*/
readonly underline: CSPair;
/**
Make text overline.
Supported on VTE-based terminals, the GNOME terminal, mintty, and Git Bash.
*/
readonly overline: CSPair;
/**
Inverse background and foreground colors.
*/
readonly inverse: CSPair;
/**
Prints the text, but makes it invisible.
*/
readonly hidden: CSPair;
/**
Puts a horizontal line through the center of the text. (Not widely supported)
*/
readonly strikethrough: CSPair;
}
export interface ForegroundColor {
readonly black: CSPair;
readonly red: CSPair;
readonly green: CSPair;
readonly yellow: CSPair;
readonly blue: CSPair;
readonly cyan: CSPair;
readonly magenta: CSPair;
readonly white: CSPair;
/**
Alias for `blackBright`.
*/
readonly gray: CSPair;
/**
Alias for `blackBright`.
*/
readonly grey: CSPair;
readonly blackBright: CSPair;
readonly redBright: CSPair;
readonly greenBright: CSPair;
readonly yellowBright: CSPair;
readonly blueBright: CSPair;
readonly cyanBright: CSPair;
readonly magentaBright: CSPair;
readonly whiteBright: CSPair;
}
export interface BackgroundColor {
readonly bgBlack: CSPair;
readonly bgRed: CSPair;
readonly bgGreen: CSPair;
readonly bgYellow: CSPair;
readonly bgBlue: CSPair;
readonly bgCyan: CSPair;
readonly bgMagenta: CSPair;
readonly bgWhite: CSPair;
/**
Alias for `bgBlackBright`.
*/
readonly bgGray: CSPair;
/**
Alias for `bgBlackBright`.
*/
readonly bgGrey: CSPair;
readonly bgBlackBright: CSPair;
readonly bgRedBright: CSPair;
readonly bgGreenBright: CSPair;
readonly bgYellowBright: CSPair;
readonly bgBlueBright: CSPair;
readonly bgCyanBright: CSPair;
readonly bgMagentaBright: CSPair;
readonly bgWhiteBright: CSPair;
}
export interface ConvertColor {
/**
Convert from the RGB color space to the ANSI 256 color space.
@param red - (`0...255`)
@param green - (`0...255`)
@param blue - (`0...255`)
*/
rgbToAnsi256(red: number, green: number, blue: number): number;
/**
Convert from the RGB HEX color space to the RGB color space.
@param hex - A hexadecimal string containing RGB data.
*/
hexToRgb(hex: string): [red: number, green: number, blue: number];
/**
Convert from the RGB HEX color space to the ANSI 256 color space.
@param hex - A hexadecimal string containing RGB data.
*/
hexToAnsi256(hex: string): number;
/**
Convert from the ANSI 256 color space to the ANSI 16 color space.
@param code - A number representing the ANSI 256 color.
*/
ansi256ToAnsi(code: number): number;
/**
Convert from the RGB color space to the ANSI 16 color space.
@param red - (`0...255`)
@param green - (`0...255`)
@param blue - (`0...255`)
*/
rgbToAnsi(red: number, green: number, blue: number): number;
/**
Convert from the RGB HEX color space to the ANSI 16 color space.
@param hex - A hexadecimal string containing RGB data.
*/
hexToAnsi(hex: string): number;
}
/**
Basic modifier names.
*/
export type ModifierName = keyof Modifier;
/**
Basic foreground color names.
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
*/
export type ForegroundColorName = keyof ForegroundColor;
/**
Basic background color names.
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
*/
export type BackgroundColorName = keyof BackgroundColor;
/**
Basic color names. The combination of foreground and background color names.
[More colors here.](https://github.com/chalk/chalk/blob/main/readme.md#256-and-truecolor-color-support)
*/
export type ColorName = ForegroundColorName | BackgroundColorName;
/**
Basic modifier names.
*/
export const modifierNames: readonly ModifierName[];
/**
Basic foreground color names.
*/
export const foregroundColorNames: readonly ForegroundColorName[];
/**
Basic background color names.
*/
export const backgroundColorNames: readonly BackgroundColorName[];
/*
Basic color names. The combination of foreground and background color names.
*/
export const colorNames: readonly ColorName[];
declare const ansiStyles: {
readonly modifier: Modifier;
readonly color: ColorBase & ForegroundColor;
readonly bgColor: ColorBase & BackgroundColor;
readonly codes: ReadonlyMap<number, number>;
} & ForegroundColor & BackgroundColor & Modifier & ConvertColor;
export default ansiStyles;

223
source/vendor/ansi-styles/index.js vendored Normal file
View file

@ -0,0 +1,223 @@
const ANSI_BACKGROUND_OFFSET = 10;
const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`;
const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`;
const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`;
const styles = {
modifier: {
reset: [0, 0],
// 21 isn't widely supported and 22 does the same thing
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
overline: [53, 55],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29],
},
color: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
// Bright color
blackBright: [90, 39],
gray: [90, 39], // Alias of `blackBright`
grey: [90, 39], // Alias of `blackBright`
redBright: [91, 39],
greenBright: [92, 39],
yellowBright: [93, 39],
blueBright: [94, 39],
magentaBright: [95, 39],
cyanBright: [96, 39],
whiteBright: [97, 39],
},
bgColor: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
// Bright color
bgBlackBright: [100, 49],
bgGray: [100, 49], // Alias of `bgBlackBright`
bgGrey: [100, 49], // Alias of `bgBlackBright`
bgRedBright: [101, 49],
bgGreenBright: [102, 49],
bgYellowBright: [103, 49],
bgBlueBright: [104, 49],
bgMagentaBright: [105, 49],
bgCyanBright: [106, 49],
bgWhiteBright: [107, 49],
},
};
export const modifierNames = Object.keys(styles.modifier);
export const foregroundColorNames = Object.keys(styles.color);
export const backgroundColorNames = Object.keys(styles.bgColor);
export const colorNames = [...foregroundColorNames, ...backgroundColorNames];
function assembleStyles() {
const codes = new Map();
for (const [groupName, group] of Object.entries(styles)) {
for (const [styleName, style] of Object.entries(group)) {
styles[styleName] = {
open: `\u001B[${style[0]}m`,
close: `\u001B[${style[1]}m`,
};
group[styleName] = styles[styleName];
codes.set(style[0], style[1]);
}
Object.defineProperty(styles, groupName, {
value: group,
enumerable: false,
});
}
Object.defineProperty(styles, 'codes', {
value: codes,
enumerable: false,
});
styles.color.close = '\u001B[39m';
styles.bgColor.close = '\u001B[49m';
styles.color.ansi = wrapAnsi16();
styles.color.ansi256 = wrapAnsi256();
styles.color.ansi16m = wrapAnsi16m();
styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
// From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js
Object.defineProperties(styles, {
rgbToAnsi256: {
value(red, green, blue) {
// We use the extended greyscale palette here, with the exception of
// black and white. normal palette only has 4 greyscale shades.
if (red === green && green === blue) {
if (red < 8) {
return 16;
}
if (red > 248) {
return 231;
}
return Math.round(((red - 8) / 247) * 24) + 232;
}
return 16
+ (36 * Math.round(red / 255 * 5))
+ (6 * Math.round(green / 255 * 5))
+ Math.round(blue / 255 * 5);
},
enumerable: false,
},
hexToRgb: {
value(hex) {
const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
if (!matches) {
return [0, 0, 0];
}
let [colorString] = matches;
if (colorString.length === 3) {
colorString = [...colorString].map(character => character + character).join('');
}
const integer = Number.parseInt(colorString, 16);
return [
/* eslint-disable no-bitwise */
(integer >> 16) & 0xFF,
(integer >> 8) & 0xFF,
integer & 0xFF,
/* eslint-enable no-bitwise */
];
},
enumerable: false,
},
hexToAnsi256: {
value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
enumerable: false,
},
ansi256ToAnsi: {
value(code) {
if (code < 8) {
return 30 + code;
}
if (code < 16) {
return 90 + (code - 8);
}
let red;
let green;
let blue;
if (code >= 232) {
red = (((code - 232) * 10) + 8) / 255;
green = red;
blue = red;
} else {
code -= 16;
const remainder = code % 36;
red = Math.floor(code / 36) / 5;
green = Math.floor(remainder / 6) / 5;
blue = (remainder % 6) / 5;
}
const value = Math.max(red, green, blue) * 2;
if (value === 0) {
return 30;
}
// eslint-disable-next-line no-bitwise
let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red));
if (value === 2) {
result += 60;
}
return result;
},
enumerable: false,
},
rgbToAnsi: {
value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
enumerable: false,
},
hexToAnsi: {
value: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
enumerable: false,
},
});
return styles;
}
const ansiStyles = assembleStyles();
export default ansiStyles;

View file

@ -0,0 +1 @@
export {default} from './index.js';

34
source/vendor/supports-color/browser.js vendored Normal file
View file

@ -0,0 +1,34 @@
/* eslint-env browser */
const level = (() => {
if (!('navigator' in globalThis)) {
return 0;
}
if (globalThis.navigator.userAgentData) {
const brand = navigator.userAgentData.brands.find(({brand}) => brand === 'Chromium');
if (brand && brand.version > 93) {
return 3;
}
}
if (/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)) {
return 1;
}
return 0;
})();
const colorSupport = level !== 0 && {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3,
};
const supportsColor = {
stdout: colorSupport,
stderr: colorSupport,
};
export default supportsColor;

55
source/vendor/supports-color/index.d.ts vendored Normal file
View file

@ -0,0 +1,55 @@
import type {WriteStream} from 'node:tty';
export type Options = {
/**
Whether `process.argv` should be sniffed for `--color` and `--no-color` flags.
@default true
*/
readonly sniffFlags?: boolean;
};
/**
Levels:
- `0` - All colors disabled.
- `1` - Basic 16 colors support.
- `2` - ANSI 256 colors support.
- `3` - Truecolor 16 million colors support.
*/
export type ColorSupportLevel = 0 | 1 | 2 | 3;
/**
Detect whether the terminal supports color.
*/
export type ColorSupport = {
/**
The color level.
*/
level: ColorSupportLevel;
/**
Whether basic 16 colors are supported.
*/
hasBasic: boolean;
/**
Whether ANSI 256 colors are supported.
*/
has256: boolean;
/**
Whether Truecolor 16 million colors are supported.
*/
has16m: boolean;
};
export type ColorInfo = ColorSupport | false;
export function createSupportsColor(stream?: WriteStream, options?: Options): ColorInfo;
declare const supportsColor: {
stdout: ColorInfo;
stderr: ColorInfo;
};
export default supportsColor;

190
source/vendor/supports-color/index.js vendored Normal file
View file

@ -0,0 +1,190 @@
import process from 'node:process';
import os from 'node:os';
import tty from 'node:tty';
// From: https://github.com/sindresorhus/has-flag/blob/main/index.js
/// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) {
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) {
const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
const position = argv.indexOf(prefix + flag);
const terminatorPosition = argv.indexOf('--');
return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
}
const {env} = process;
let flagForceColor;
if (
hasFlag('no-color')
|| hasFlag('no-colors')
|| hasFlag('color=false')
|| hasFlag('color=never')
) {
flagForceColor = 0;
} else if (
hasFlag('color')
|| hasFlag('colors')
|| hasFlag('color=true')
|| hasFlag('color=always')
) {
flagForceColor = 1;
}
function envForceColor() {
if ('FORCE_COLOR' in env) {
if (env.FORCE_COLOR === 'true') {
return 1;
}
if (env.FORCE_COLOR === 'false') {
return 0;
}
return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
}
}
function translateLevel(level) {
if (level === 0) {
return false;
}
return {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3,
};
}
function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) {
const noFlagForceColor = envForceColor();
if (noFlagForceColor !== undefined) {
flagForceColor = noFlagForceColor;
}
const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
if (forceColor === 0) {
return 0;
}
if (sniffFlags) {
if (hasFlag('color=16m')
|| hasFlag('color=full')
|| hasFlag('color=truecolor')) {
return 3;
}
if (hasFlag('color=256')) {
return 2;
}
}
// Check for Azure DevOps pipelines.
// Has to be above the `!streamIsTTY` check.
if ('TF_BUILD' in env && 'AGENT_NAME' in env) {
return 1;
}
if (haveStream && !streamIsTTY && forceColor === undefined) {
return 0;
}
const min = forceColor || 0;
if (env.TERM === 'dumb') {
return min;
}
if (process.platform === 'win32') {
// Windows 10 build 10586 is the first Windows release that supports 256 colors.
// Windows 10 build 14931 is the first release that supports 16m/TrueColor.
const osRelease = os.release().split('.');
if (
Number(osRelease[0]) >= 10
&& Number(osRelease[2]) >= 10_586
) {
return Number(osRelease[2]) >= 14_931 ? 3 : 2;
}
return 1;
}
if ('CI' in env) {
if (['GITHUB_ACTIONS', 'GITEA_ACTIONS', 'CIRCLECI'].some(key => key in env)) {
return 3;
}
if (['TRAVIS', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
return 1;
}
return min;
}
if ('TEAMCITY_VERSION' in env) {
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
}
if (env.COLORTERM === 'truecolor') {
return 3;
}
if (env.TERM === 'xterm-kitty') {
return 3;
}
if (env.TERM === 'xterm-ghostty') {
return 3;
}
if (env.TERM === 'wezterm') {
return 3;
}
if ('TERM_PROGRAM' in env) {
const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
switch (env.TERM_PROGRAM) {
case 'iTerm.app': {
return version >= 3 ? 3 : 2;
}
case 'Apple_Terminal': {
return 2;
}
// No default
}
}
if (/-256(color)?$/i.test(env.TERM)) {
return 2;
}
if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
return 1;
}
if ('COLORTERM' in env) {
return 1;
}
return min;
}
export function createSupportsColor(stream, options = {}) {
const level = _supportsColor(stream, {
streamIsTTY: stream && stream.isTTY,
...options,
});
return translateLevel(level);
}
const supportsColor = {
stdout: createSupportsColor({isTTY: tty.isatty(1)}),
stderr: createSupportsColor({isTTY: tty.isatty(2)}),
};
export default supportsColor;

View file

@ -1,128 +0,0 @@
'use strict';
const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|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}|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) {
if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
return String.fromCharCode(parseInt(c.slice(1), 16));
}
return ESCAPES.get(c) || c;
}
function parseArguments(name, args) {
const results = [];
const chunks = args.trim().split(/\s*,\s*/g);
let matches;
for (const chunk of chunks) {
if (!isNaN(chunk)) {
results.push(Number(chunk));
} else if ((matches = chunk.match(STRING_REGEX))) {
results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));
} 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 of Object.keys(enabled)) {
if (Array.isArray(enabled[styleName])) {
if (!(styleName in current)) {
throw new Error(`Unknown Chalk style: ${styleName}`);
}
if (enabled[styleName].length > 0) {
current = current[styleName].apply(current, enabled[styleName]);
} else {
current = current[styleName];
}
}
}
return current;
}
module.exports = (chalk, tmp) => {
const styles = [];
const chunks = [];
let chunk = [];
// eslint-disable-next-line max-params
tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
if (escapeChar) {
chunk.push(unescape(escapeChar));
} else if (style) {
const str = chunk.join('');
chunk = [];
chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
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(chr);
}
});
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

@ -1,4 +1,3 @@
'use strict';
const chalk = require('..');
import chalk, {chalkStderr} from '../source/index.js';
console.log(chalk.hex('#ff6159')('test'));
console.log(`${chalk.hex('#ff6159')('testout')} ${chalkStderr.hex('#ff6159')('testerr')}`);

View file

@ -1,13 +0,0 @@
'use strict';
const resolveFrom = require('resolve-from');
module.exports = dir => {
require.cache[resolveFrom(dir, 'supports-color')] = {
exports: {
level: 3,
hasBasic: true,
has256: true,
has16m: true
}
};
};

View file

@ -1,53 +1,60 @@
import process from 'node:process';
import test from 'ava';
import chalk, {Chalk, chalkStderr} from '../source/index.js';
// Spoof supports-color
require('./_supports-color')(__dirname);
const m = require('..');
chalk.level = 3;
chalkStderr.level = 3;
console.log('TERM:', process.env.TERM || '[none]');
console.log('platform:', process.platform || '[unknown]');
test('don\'t add any styling when called as the base function', t => {
t.is(m('foo'), 'foo');
t.is(chalk('foo'), 'foo');
});
test('support multiple arguments in base function', t => {
t.is(m('hello', 'there'), 'hello there');
t.is(chalk('hello', 'there'), 'hello there');
});
test('support automatic casting to string', t => {
t.is(chalk(['hello', 'there']), 'hello,there');
t.is(chalk(123), '123');
t.is(chalk.bold(['foo', 'bar']), '\u001B[1mfoo,bar\u001B[22m');
t.is(chalk.green(98_765), '\u001B[32m98765\u001B[39m');
});
test('style string', t => {
t.is(m.underline('foo'), '\u001B[4mfoo\u001B[24m');
t.is(m.red('foo'), '\u001B[31mfoo\u001B[39m');
t.is(m.bgRed('foo'), '\u001B[41mfoo\u001B[49m');
t.is(chalk.underline('foo'), '\u001B[4mfoo\u001B[24m');
t.is(chalk.red('foo'), '\u001B[31mfoo\u001B[39m');
t.is(chalk.bgRed('foo'), '\u001B[41mfoo\u001B[49m');
});
test('support applying multiple styles at once', t => {
t.is(m.red.bgGreen.underline('foo'), '\u001B[31m\u001B[42m\u001B[4mfoo\u001B[24m\u001B[49m\u001B[39m');
t.is(m.underline.red.bgGreen('foo'), '\u001B[4m\u001B[31m\u001B[42mfoo\u001B[49m\u001B[39m\u001B[24m');
t.is(chalk.red.bgGreen.underline('foo'), '\u001B[31m\u001B[42m\u001B[4mfoo\u001B[24m\u001B[49m\u001B[39m');
t.is(chalk.underline.red.bgGreen('foo'), '\u001B[4m\u001B[31m\u001B[42mfoo\u001B[49m\u001B[39m\u001B[24m');
});
test('support nesting styles', t => {
t.is(
m.red('foo' + m.underline.bgBlue('bar') + '!'),
'\u001B[31mfoo\u001B[4m\u001B[44mbar\u001B[49m\u001B[24m!\u001B[39m'
chalk.red('foo' + chalk.underline.bgBlue('bar') + '!'),
'\u001B[31mfoo\u001B[4m\u001B[44mbar\u001B[49m\u001B[24m!\u001B[39m',
);
});
test('support nesting styles of the same type (color, underline, bg)', t => {
t.is(
m.red('a' + m.yellow('b' + m.green('c') + 'b') + 'c'),
'\u001B[31ma\u001B[33mb\u001B[32mc\u001B[33mb\u001B[31mc\u001B[39m'
chalk.red('a' + chalk.yellow('b' + chalk.green('c') + 'b') + 'c'),
'\u001B[31ma\u001B[33mb\u001B[32mc\u001B[39m\u001B[31m\u001B[33mb\u001B[39m\u001B[31mc\u001B[39m',
);
});
test('reset all styles with `.reset()`', t => {
t.is(m.reset(m.red.bgGreen.underline('foo') + 'foo'), '\u001B[0m\u001B[31m\u001B[42m\u001B[4mfoo\u001B[24m\u001B[49m\u001B[39mfoo\u001B[0m');
t.is(chalk.reset(chalk.red.bgGreen.underline('foo') + 'foo'), '\u001B[0m\u001B[31m\u001B[42m\u001B[4mfoo\u001B[24m\u001B[49m\u001B[39mfoo\u001B[0m');
});
test('support caching multiple styles', t => {
const red = m.red;
const green = m.green;
const {red, green} = chalk.red;
const redBold = red.bold;
const greenBold = green.bold;
@ -57,44 +64,63 @@ test('support caching multiple styles', t => {
});
test('alias gray to grey', t => {
t.is(m.grey('foo'), '\u001B[90mfoo\u001B[39m');
t.is(chalk.grey('foo'), '\u001B[90mfoo\u001B[39m');
});
test('support variable number of arguments', t => {
t.is(m.red('foo', 'bar'), '\u001B[31mfoo bar\u001B[39m');
t.is(chalk.red('foo', 'bar'), '\u001B[31mfoo bar\u001B[39m');
});
test('support falsy values', t => {
t.is(m.red(0), '\u001B[31m0\u001B[39m');
t.is(chalk.red(0), '\u001B[31m0\u001B[39m');
});
test('don\'t output escape codes if the input is empty', t => {
t.is(m.red(), '');
t.is(m.red.blue.black(), '');
t.is(chalk.red(), '');
t.is(chalk.red.blue.black(), '');
});
test('keep Function.prototype methods', t => {
t.is(m.grey.apply(null, ['foo']), '\u001B[90mfoo\u001B[39m');
t.is(m.reset(m.red.bgGreen.underline.bind(null)('foo') + 'foo'), '\u001B[0m\u001B[31m\u001B[42m\u001B[4mfoo\u001B[24m\u001B[49m\u001B[39mfoo\u001B[0m');
t.is(m.red.blue.black.call(null), '');
t.is(Reflect.apply(chalk.grey, null, ['foo']), '\u001B[90mfoo\u001B[39m');
t.is(chalk.reset(chalk.red.bgGreen.underline.bind(null)('foo') + 'foo'), '\u001B[0m\u001B[31m\u001B[42m\u001B[4mfoo\u001B[24m\u001B[49m\u001B[39mfoo\u001B[0m');
t.is(chalk.red.blue.black.call(null), '');
});
test('line breaks should open and close colors', t => {
t.is(m.grey('hello\nworld'), '\u001B[90mhello\u001B[39m\n\u001B[90mworld\u001B[39m');
t.is(chalk.grey('hello\nworld'), '\u001B[90mhello\u001B[39m\n\u001B[90mworld\u001B[39m');
});
test('line breaks should open and close colors with CRLF', t => {
t.is(chalk.grey('hello\r\nworld'), '\u001B[90mhello\u001B[39m\r\n\u001B[90mworld\u001B[39m');
});
test('properly convert RGB to 16 colors on basic color terminals', t => {
t.is(new m.constructor({level: 1}).hex('#FF0000')('hello'), '\u001B[91mhello\u001B[39m');
t.is(new m.constructor({level: 1}).bgHex('#FF0000')('hello'), '\u001B[101mhello\u001B[49m');
t.is(new Chalk({level: 1}).hex('#FF0000')('hello'), '\u001B[91mhello\u001B[39m');
t.is(new Chalk({level: 1}).bgHex('#FF0000')('hello'), '\u001B[101mhello\u001B[49m');
});
test('properly convert RGB to 256 colors on basic color terminals', t => {
t.is(new m.constructor({level: 2}).hex('#FF0000')('hello'), '\u001B[38;5;196mhello\u001B[39m');
t.is(new m.constructor({level: 2}).bgHex('#FF0000')('hello'), '\u001B[48;5;196mhello\u001B[49m');
t.is(new m.constructor({level: 3}).bgHex('#FF0000')('hello'), '\u001B[48;2;255;0;0mhello\u001B[49m');
t.is(new Chalk({level: 2}).hex('#FF0000')('hello'), '\u001B[38;5;196mhello\u001B[39m');
t.is(new Chalk({level: 2}).bgHex('#FF0000')('hello'), '\u001B[48;5;196mhello\u001B[49m');
t.is(new Chalk({level: 3}).bgHex('#FF0000')('hello'), '\u001B[48;2;255;0;0mhello\u001B[49m');
});
test('don\'t emit RGB codes if level is 0', t => {
t.is(new m.constructor({level: 0}).hex('#FF0000')('hello'), 'hello');
t.is(new m.constructor({level: 0}).bgHex('#FF0000')('hello'), 'hello');
t.is(new Chalk({level: 0}).hex('#FF0000')('hello'), 'hello');
t.is(new Chalk({level: 0}).bgHex('#FF0000')('hello'), 'hello');
});
test('supports blackBright color', t => {
t.is(chalk.blackBright('foo'), '\u001B[90mfoo\u001B[39m');
});
test('sets correct level for chalkStderr and respects it', t => {
t.is(chalkStderr.level, 3);
t.is(chalkStderr.red.bold('foo'), '\u001B[31m\u001B[1mfoo\u001B[22m\u001B[39m');
});
test('keeps function prototype methods', t => {
t.is(chalk.apply(chalk, ['foo']), 'foo');
t.is(chalk.bind(chalk, 'foo')(), 'foo');
t.is(chalk.call(chalk, 'foo'), 'foo');
});

View file

@ -1,22 +0,0 @@
import test from 'ava';
// Spoof supports-color
require('./_supports-color')(__dirname);
const m = require('..');
test('create an isolated context where colors can be disabled (by level)', t => {
const ctx = new m.constructor({level: 0, enabled: true});
t.is(ctx.red('foo'), 'foo');
t.is(m.red('foo'), '\u001B[31mfoo\u001B[39m');
ctx.level = 2;
t.is(ctx.red('foo'), '\u001B[31mfoo\u001B[39m');
});
test('create an isolated context where colors can be disabled (by enabled flag)', t => {
const ctx = new m.constructor({enabled: false});
t.is(ctx.red('foo'), 'foo');
t.is(m.red('foo'), '\u001B[31mfoo\u001B[39m');
ctx.enabled = true;
t.is(ctx.red('foo'), '\u001B[31mfoo\u001B[39m');
});

View file

@ -1,35 +0,0 @@
import test from 'ava';
// Spoof supports-color
require('./_supports-color')(__dirname);
const m = require('..');
test('don\'t output colors when manually disabled', t => {
m.enabled = false;
t.is(m.red('foo'), 'foo');
m.enabled = true;
});
test('enable/disable colors based on overall chalk enabled property, not individual instances', t => {
m.enabled = false;
const red = m.red;
t.false(red.enabled);
m.enabled = true;
t.true(red.enabled);
m.enabled = true;
});
test('propagate enable/disable changes from child colors', t => {
m.enabled = false;
const red = m.red;
t.false(red.enabled);
t.false(m.enabled);
red.enabled = true;
t.true(red.enabled);
t.true(m.enabled);
m.enabled = false;
t.false(red.enabled);
t.false(m.enabled);
m.enabled = true;
});

24
test/instance.js Normal file
View file

@ -0,0 +1,24 @@
import test from 'ava';
import chalk, {Chalk} from '../source/index.js';
chalk.level = 1;
test('create an isolated context where colors can be disabled (by level)', t => {
const instance = new Chalk({level: 0});
t.is(instance.red('foo'), 'foo');
t.is(chalk.red('foo'), '\u001B[31mfoo\u001B[39m');
instance.level = 2;
t.is(instance.red('foo'), '\u001B[31mfoo\u001B[39m');
});
test('the `level` option should be a number from 0 to 3', t => {
/* eslint-disable no-new */
t.throws(() => {
new Chalk({level: 10});
}, {message: /should be an integer from 0 to 3/});
t.throws(() => {
new Chalk({level: -1});
}, {message: /should be an integer from 0 to 3/});
/* eslint-enable no-new */
});

View file

@ -1,44 +1,43 @@
import path from 'path';
import {fileURLToPath} from 'node:url';
import test from 'ava';
import execa from 'execa';
import {execaNode} from 'execa';
import chalk from '../source/index.js';
// Spoof supports-color
require('./_supports-color')(__dirname);
const m = require('..');
chalk.level = 1;
test('don\'t output colors when manually disabled', t => {
const oldLevel = m.level;
m.level = 0;
t.is(m.red('foo'), 'foo');
m.level = oldLevel;
const oldLevel = chalk.level;
chalk.level = 0;
t.is(chalk.red('foo'), 'foo');
chalk.level = oldLevel;
});
test('enable/disable colors based on overall chalk enabled property, not individual instances', t => {
const oldLevel = m.level;
m.level = 1;
const red = m.red;
test('enable/disable colors based on overall chalk .level property, not individual instances', t => {
const oldLevel = chalk.level;
chalk.level = 1;
const {red} = chalk;
t.is(red.level, 1);
m.level = 0;
t.is(red.level, m.level);
m.level = oldLevel;
chalk.level = 0;
t.is(red.level, chalk.level);
chalk.level = oldLevel;
});
test('propagate enable/disable changes from child colors', t => {
const oldLevel = m.level;
m.level = 1;
const red = m.red;
const oldLevel = chalk.level;
chalk.level = 1;
const {red} = chalk;
t.is(red.level, 1);
t.is(m.level, 1);
t.is(chalk.level, 1);
red.level = 0;
t.is(red.level, 0);
t.is(m.level, 0);
m.level = 1;
t.is(chalk.level, 0);
chalk.level = 1;
t.is(red.level, 1);
t.is(m.level, 1);
m.level = oldLevel;
t.is(chalk.level, 1);
chalk.level = oldLevel;
});
test('disable colors if they are not supported', async t => {
t.is(await execa.stdout('node', [path.join(__dirname, '_fixture')]), 'test');
const {stdout} = await execaNode(fileURLToPath(new URL('_fixture.js', import.meta.url)));
t.is(stdout, 'testout testerr');
});

24
test/no-color-support.js Normal file
View file

@ -0,0 +1,24 @@
import test from 'ava';
import chalk from '../source/index.js';
// TODO: Do this when ESM supports loader hooks
// Spoof supports-color
// require('./_supports-color')(__dirname, {
// stdout: {
// level: 0,
// hasBasic: false,
// has256: false,
// has16m: false
// },
// stderr: {
// level: 0,
// hasBasic: false,
// has256: false,
// has16m: false
// }
// });
test('colors can be forced by using chalk.level', t => {
chalk.level = 1;
t.is(chalk.green('hello'), '\u001B[32mhello\u001B[39m');
});

View file

@ -1,169 +0,0 @@
import test from 'ava';
// Spoof supports-color
require('./_supports-color')(__dirname);
const m = require('..');
test('return an empty string for an empty literal', t => {
const ctx = m.constructor();
t.is(ctx``, '');
});
test('return a regular string for a literal with no templates', t => {
const ctx = m.constructor({level: 0});
t.is(ctx`hello`, 'hello');
});
test('correctly perform template parsing', t => {
const ctx = m.constructor({level: 0});
t.is(ctx`{bold Hello, {cyan World!} This is a} test. {green Woo!}`,
ctx.bold('Hello,', ctx.cyan('World!'), 'This is a') + ' test. ' + ctx.green('Woo!'));
});
test('correctly perform template substitutions', t => {
const ctx = m.constructor({level: 0});
const name = 'Sindre';
const exclamation = 'Neat';
t.is(ctx`{bold Hello, {cyan.inverse ${name}!} This is a} test. {green ${exclamation}!}`,
ctx.bold('Hello,', ctx.cyan.inverse(name + '!'), 'This is a') + ' test. ' + ctx.green(exclamation + '!'));
});
test('correctly parse and evaluate color-convert functions', t => {
const ctx = m.constructor({level: 3});
t.is(ctx`{bold.rgb(144,10,178).inverse Hello, {~inverse there!}}`,
'\u001B[1m\u001B[38;2;144;10;178m\u001B[7mHello, ' +
'\u001B[27m\u001B[39m\u001B[22m\u001B[1m' +
'\u001B[38;2;144;10;178mthere!\u001B[39m\u001B[22m');
t.is(ctx`{bold.bgRgb(144,10,178).inverse Hello, {~inverse there!}}`,
'\u001B[1m\u001B[48;2;144;10;178m\u001B[7mHello, ' +
'\u001B[27m\u001B[49m\u001B[22m\u001B[1m' +
'\u001B[48;2;144;10;178mthere!\u001B[49m\u001B[22m');
});
test('properly handle escapes', t => {
const ctx = m.constructor({level: 3});
t.is(ctx`{bold hello \{in brackets\}}`,
'\u001B[1mhello {in brackets}\u001B[22m');
});
test('throw if there is an unclosed block', t => {
const ctx = m.constructor({level: 3});
try {
console.log(ctx`{bold this shouldn't appear ever\}`);
t.fail();
} catch (err) {
t.is(err.message, 'Chalk template literal is missing 1 closing bracket (`}`)');
}
try {
console.log(ctx`{bold this shouldn't {inverse appear {underline ever\} :) \}`);
t.fail();
} catch (err) {
t.is(err.message, 'Chalk template literal is missing 3 closing brackets (`}`)');
}
});
test('throw if there is an invalid style', t => {
const ctx = m.constructor({level: 3});
try {
console.log(ctx`{abadstylethatdoesntexist this shouldn't appear ever}`);
t.fail();
} catch (err) {
t.is(err.message, 'Unknown Chalk style: abadstylethatdoesntexist');
}
});
test('properly style multiline color blocks', t => {
const ctx = m.constructor({level: 3});
t.is(
ctx`{bold
Hello! This is a
${'multiline'} block!
:)
} {underline
I hope you enjoy
}`,
'\u001B[1m\u001B[22m\n' +
'\u001B[1m\t\t\tHello! This is a\u001B[22m\n' +
'\u001B[1m\t\t\tmultiline block!\u001B[22m\n' +
'\u001B[1m\t\t\t:)\u001B[22m\n' +
'\u001B[1m\t\t\u001B[22m \u001B[4m\u001B[24m\n' +
'\u001B[4m\t\t\tI hope you enjoy\u001B[24m\n' +
'\u001B[4m\t\t\u001B[24m'
);
});
test('escape interpolated values', t => {
const ctx = m.constructor({level: 0});
t.is(ctx`Hello {bold hi}`, 'Hello hi');
t.is(ctx`Hello ${'{bold hi}'}`, 'Hello {bold hi}');
});
test('allow custom colors (themes) on custom contexts', t => {
const ctx = m.constructor({level: 3});
ctx.rose = ctx.hex('#F6D9D9');
t.is(ctx`Hello, {rose Rose}.`, 'Hello, \u001B[38;2;246;217;217mRose\u001B[39m.');
});
test('correctly parse newline literals (bug #184)', t => {
const ctx = m.constructor({level: 0});
t.is(ctx`Hello
{red there}`, 'Hello\nthere');
});
test('correctly parse newline escapes (bug #177)', t => {
const ctx = m.constructor({level: 0});
t.is(ctx`Hello\nthere!`, `Hello\nthere!`);
});
test('correctly parse escape in parameters (bug #177 comment 318622809)', t => {
const ctx = m.constructor({level: 0});
const str = '\\';
t.is(ctx`{blue ${str}}`, '\\');
});
test('correctly parses unicode/hex escapes', t => {
const ctx = m.constructor({level: 0});
t.is(ctx`\u0078ylophones are fo\x78y! {magenta.inverse \u0078ylophones are fo\x78y!}`,
'xylophones are foxy! xylophones are foxy!');
});
test('correctly parses string arguments', t => {
const ctx = m.constructor({level: 3});
t.is(ctx`{keyword('black').bold can haz cheezburger}`, '\u001B[38;2;0;0;0m\u001B[1mcan haz cheezburger\u001B[22m\u001B[39m');
t.is(ctx`{keyword('blac\x6B').bold can haz cheezburger}`, '\u001B[38;2;0;0;0m\u001B[1mcan haz cheezburger\u001B[22m\u001B[39m');
t.is(ctx`{keyword('blac\u006B').bold can haz cheezburger}`, '\u001B[38;2;0;0;0m\u001B[1mcan haz cheezburger\u001B[22m\u001B[39m');
});
test('throws if a bad argument is encountered', t => {
const ctx = m.constructor({level: 3}); // Keep level at least 1 in case we optimize for disabled chalk instances
try {
console.log(ctx`{keyword(????) hi}`);
t.fail();
} catch (err) {
t.is(err.message, 'Invalid Chalk template style argument: ???? (in style \'keyword\')');
}
});
test('throws if an extra unescaped } is found', t => {
const ctx = m.constructor({level: 0});
try {
console.log(ctx`{red hi!}}`);
t.fail();
} catch (err) {
t.is(err.message, 'Found extraneous } in Chalk template literal');
}
});
test('should not parse upper-case escapes', t => {
const ctx = m.constructor({level: 0});
t.is(ctx`\N\n\T\t\X07\x07\U000A\u000A\U000a\u000a`, 'N\nT\tX07\x07U000A\u000AU000a\u000A');
});
test('should properly handle undefined template interpolated values', t => {
const ctx = m.constructor({level: 0});
t.is(ctx`hello ${undefined}`, 'hello undefined');
t.is(ctx`hello ${null}`, 'hello null');
});

View file

@ -1,47 +1,39 @@
import test from 'ava';
import chalk, {Chalk} from '../source/index.js';
// Spoof supports-color
require('./_supports-color')(__dirname);
chalk.level = 1;
const m = require('..');
test('visible: normal output when enabled', t => {
const ctx = new m.constructor({level: 3, enabled: true});
t.is(ctx.visible.red('foo'), '\u001B[31mfoo\u001B[39m');
t.is(ctx.red.visible('foo'), '\u001B[31mfoo\u001B[39m');
});
test('visible: no output when disabled', t => {
const ctx = new m.constructor({level: 3, enabled: false});
t.is(ctx.red.visible('foo'), '');
t.is(ctx.visible.red('foo'), '');
test('visible: normal output when level > 0', t => {
const instance = new Chalk({level: 3});
t.is(instance.visible.red('foo'), '\u001B[31mfoo\u001B[39m');
t.is(instance.red.visible('foo'), '\u001B[31mfoo\u001B[39m');
});
test('visible: no output when level is too low', t => {
const ctx = new m.constructor({level: 0, enabled: true});
t.is(ctx.visible.red('foo'), '');
t.is(ctx.red.visible('foo'), '');
const instance = new Chalk({level: 0});
t.is(instance.visible.red('foo'), '');
t.is(instance.red.visible('foo'), '');
});
test('test switching back and forth between enabled and disabled', t => {
const ctx = new m.constructor({level: 3, enabled: true});
t.is(ctx.red('foo'), '\u001B[31mfoo\u001B[39m');
t.is(ctx.visible.red('foo'), '\u001B[31mfoo\u001B[39m');
t.is(ctx.red.visible('foo'), '\u001B[31mfoo\u001B[39m');
t.is(ctx.visible('foo'), 'foo');
t.is(ctx.red('foo'), '\u001B[31mfoo\u001B[39m');
test('test switching back and forth between level == 0 and level > 0', t => {
const instance = new Chalk({level: 3});
t.is(instance.red('foo'), '\u001B[31mfoo\u001B[39m');
t.is(instance.visible.red('foo'), '\u001B[31mfoo\u001B[39m');
t.is(instance.red.visible('foo'), '\u001B[31mfoo\u001B[39m');
t.is(instance.visible('foo'), 'foo');
t.is(instance.red('foo'), '\u001B[31mfoo\u001B[39m');
ctx.enabled = false;
t.is(ctx.red('foo'), 'foo');
t.is(ctx.visible('foo'), '');
t.is(ctx.visible.red('foo'), '');
t.is(ctx.red.visible('foo'), '');
t.is(ctx.red('foo'), 'foo');
instance.level = 0;
t.is(instance.red('foo'), 'foo');
t.is(instance.visible('foo'), '');
t.is(instance.visible.red('foo'), '');
t.is(instance.red.visible('foo'), '');
t.is(instance.red('foo'), 'foo');
ctx.enabled = true;
t.is(ctx.red('foo'), '\u001B[31mfoo\u001B[39m');
t.is(ctx.visible.red('foo'), '\u001B[31mfoo\u001B[39m');
t.is(ctx.red.visible('foo'), '\u001B[31mfoo\u001B[39m');
t.is(ctx.visible('foo'), 'foo');
t.is(ctx.red('foo'), '\u001B[31mfoo\u001B[39m');
instance.level = 3;
t.is(instance.red('foo'), '\u001B[31mfoo\u001B[39m');
t.is(instance.visible.red('foo'), '\u001B[31mfoo\u001B[39m');
t.is(instance.red.visible('foo'), '\u001B[31mfoo\u001B[39m');
t.is(instance.visible('foo'), 'foo');
t.is(instance.red('foo'), '\u001B[31mfoo\u001B[39m');
});

View file

@ -1,63 +0,0 @@
import test from 'ava';
import importFresh from 'import-fresh';
import resolveFrom from 'resolve-from';
// Spoof supports-color
require('./_supports-color')(__dirname);
let originalEnv;
let originalPlatform;
test.before(() => {
originalEnv = process.env;
originalPlatform = process.platform;
});
test.after(() => {
process.env = originalEnv;
Object.defineProperty(process, 'platform', {value: originalPlatform});
});
test.beforeEach(() => {
process.env = {};
Object.defineProperty(process, 'platform', {value: 'win32'});
// Since chalk internally modifies `ansiStyles.blue.open`, `ansi-styles` needs
// to be removed from the require cache for `require-uncached` to work
delete require.cache[resolveFrom(__dirname, 'ansi-styles')];
});
test('detect a simple term if TERM isn\'t set', t => {
delete process.env.TERM;
const m = importFresh('..');
t.is(m.blue('foo'), '\u001B[94mfoo\u001B[39m');
});
test('replace blue foreground color in cmd.exe', t => {
process.env.TERM = 'dumb';
const m = importFresh('..');
t.is(m.blue('foo'), '\u001B[94mfoo\u001B[39m');
});
test('don\'t replace blue foreground color in xterm based terminals', t => {
process.env.TERM = 'xterm-256color';
const m = importFresh('..');
t.is(m.blue('foo'), '\u001B[34mfoo\u001B[39m');
});
test('don\'t apply dimmed styling on gray strings, see https://github.com/chalk/chalk/issues/58', t => {
process.env.TERM = 'dumb';
const m = importFresh('..');
t.is(m.gray.dim('foo'), '\u001B[90mfoo\u001B[22m\u001B[39m');
});
test('apply dimmed styling on xterm compatible terminals', t => {
process.env.TERM = 'xterm';
const m = importFresh('..');
t.is(m.gray.dim('foo'), '\u001B[90m\u001B[2mfoo\u001B[22m\u001B[39m');
});
test('apply dimmed styling on strings of other colors', t => {
process.env.TERM = 'dumb';
const m = importFresh('..');
t.is(m.blue.dim('foo'), '\u001B[94m\u001B[2mfoo\u001B[22m\u001B[39m');
});

97
types/index.d.ts vendored
View file

@ -1,97 +0,0 @@
// Type definitions for Chalk
// Definitions by: Thomas Sauer <https://github.com/t-sauer>
export const enum Level {
None = 0,
Basic = 1,
Ansi256 = 2,
TrueColor = 3
}
export interface ChalkOptions {
enabled?: boolean;
level?: Level;
}
export interface ChalkConstructor {
new (options?: ChalkOptions): Chalk;
(options?: ChalkOptions): Chalk;
}
export interface ColorSupport {
level: Level;
hasBasic: boolean;
has256: boolean;
has16m: boolean;
}
export interface Chalk {
(...text: string[]): string;
(text: TemplateStringsArray, ...placeholders: string[]): string;
constructor: ChalkConstructor;
enabled: boolean;
level: Level;
rgb(r: number, g: number, b: number): this;
hsl(h: number, s: number, l: number): this;
hsv(h: number, s: number, v: number): this;
hwb(h: number, w: number, b: number): this;
bgHex(color: string): this;
bgKeyword(color: string): this;
bgRgb(r: number, g: number, b: number): this;
bgHsl(h: number, s: number, l: number): this;
bgHsv(h: number, s: number, v: number): this;
bgHwb(h: number, w: number, b: number): this;
hex(color: string): this;
keyword(color: string): this;
readonly reset: this;
readonly bold: this;
readonly dim: this;
readonly italic: this;
readonly underline: this;
readonly inverse: this;
readonly hidden: this;
readonly strikethrough: this;
readonly visible: this;
readonly black: this;
readonly red: this;
readonly green: this;
readonly yellow: this;
readonly blue: this;
readonly magenta: this;
readonly cyan: this;
readonly white: this;
readonly gray: this;
readonly grey: this;
readonly blackBright: this;
readonly redBright: this;
readonly greenBright: this;
readonly yellowBright: this;
readonly blueBright: this;
readonly magentaBright: this;
readonly cyanBright: this;
readonly whiteBright: this;
readonly bgBlack: this;
readonly bgRed: this;
readonly bgGreen: this;
readonly bgYellow: this;
readonly bgBlue: this;
readonly bgMagenta: this;
readonly bgCyan: this;
readonly bgWhite: this;
readonly bgBlackBright: this;
readonly bgRedBright: this;
readonly bgGreenBright: this;
readonly bgYellowBright: this;
readonly bgBlueBright: this;
readonly bgMagentaBright: this;
readonly bgCyanBright: this;
readonly bgWhiteBright: this;
}
declare const chalk: Chalk & { supportsColor: ColorSupport };
export default chalk

View file

@ -1,56 +0,0 @@
import chalk, {Level} from '..';
chalk.underline('foo');
chalk.red('foo');
chalk.bgRed('foo');
const name = 'Josh';
chalk`Hello {bold.red ${name}}`;
chalk.red`foo`;
chalk.underline`foo`;
chalk`foo`;
chalk.red.bgGreen.underline('foo');
chalk.underline.red.bgGreen('foo');
chalk.grey('foo');
chalk.constructor({level: 1});
const ctx = chalk.constructor({level: Level.TrueColor });
ctx('foo');
ctx.red('foo');
ctx`foo`;
chalk.enabled = true;
chalk.level = 1;
chalk.level = Level.Ansi256;
chalk.level === Level.Ansi256;
let chalkInstance = new chalk.constructor();
chalkInstance = chalk.constructor();
chalkInstance.blue('foo');
chalkInstance`foo`;
let x = 'imastring';
x = chalk();
chalk.enabled;
chalk.level;
chalk.supportsColor.level;
chalk.supportsColor.has16m;
chalk.supportsColor.has256;
chalk.supportsColor.hasBasic;
chalk.keyword('orange').bgBlue('foo');
chalk.hex('#123456').bgBlue('foo');
chalk.rgb(1, 14, 9).bgBlue('foo');
chalk.hsl(1, 14, 9).bgBlue('foo');
chalk.hsv(1, 14, 9).bgBlue('foo');
chalk.hwb(1, 14, 9).bgBlue('foo');
chalk.visible('foo');
chalk.red.visible('foo');
chalk.visible.red('foo');

View file

@ -1,9 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"noEmit": true,
"allowJs": true
}
}