diff --git a/.editorconfig b/.editorconfig index b0d7fd9..1c6314a 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,4 +1,3 @@ -# editorconfig.org root = true [*] @@ -8,5 +7,6 @@ charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true -[*.md] -trim_trailing_whitespace = false +[*.yml] +indent_style = space +indent_size = 2 diff --git a/.gitattributes b/.gitattributes index 176a458..6313b56 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1 @@ -* text=auto +* text=auto eol=lf diff --git a/.github/funding.yml b/.github/funding.yml new file mode 100644 index 0000000..1cd069f --- /dev/null +++ b/.github/funding.yml @@ -0,0 +1,4 @@ +github: [sindresorhus, Qix-] +open_collective: sindresorhus +tidelift: npm/chalk +custom: https://sindresorhus.com/donate diff --git a/.github/security.md b/.github/security.md new file mode 100644 index 0000000..5358dc5 --- /dev/null +++ b/.github/security.md @@ -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. diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..d588995 --- /dev/null +++ b/.github/workflows/main.yml @@ -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 diff --git a/.gitignore b/.gitignore index 3c3629e..6bff314 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,4 @@ node_modules +yarn.lock +coverage +.nyc_output diff --git a/.jshintrc b/.jshintrc deleted file mode 100644 index ac35c13..0000000 --- a/.jshintrc +++ /dev/null @@ -1,20 +0,0 @@ -{ - "node": true, - "esnext": true, - "bitwise": true, - "camelcase": true, - "curly": true, - "eqeqeq": true, - "immed": true, - "indent": 4, - "latedef": true, - "newcap": true, - "noarg": true, - "quotmark": "single", - "regexp": true, - "undef": true, - "unused": true, - "strict": true, - "trailing": true, - "smarttabs": true -} diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..43c97e7 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +package-lock=false diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 2cdacaf..0000000 --- a/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - '0.10' - - '0.8' diff --git a/benchmark.js b/benchmark.js new file mode 100644 index 0000000..c5c6e27 --- /dev/null +++ b/benchmark.js @@ -0,0 +1,57 @@ +/* globals suite, bench */ +import chalk from './index.js'; + +suite('chalk', () => { + const chalkRed = chalk.red; + const chalkBgRed = chalk.bgRed; + const chalkBlueBgRed = chalk.blue.bgRed; + const chalkBlueBgRedBold = chalk.blue.bgRed.bold; + + const blueStyledString = 'the fox jumps' + chalk.blue('over the lazy dog') + '!'; + + bench('1 style', () => { + chalk.red('the fox jumps over the lazy dog'); + }); + + 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'); + }); + + bench('cached: 1 style', () => { + chalkRed('the fox jumps 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`; + }); +}); diff --git a/chalk.js b/chalk.js deleted file mode 100644 index d4887e1..0000000 --- a/chalk.js +++ /dev/null @@ -1,64 +0,0 @@ -'use strict'; -var ansi = require('ansi-styles'); -var defineProps = Object.defineProperties; - -var styles = (function () { - var ret = {}; - - Object.keys(ansi).forEach(function (key) { - var code = ansi[key]; - ret[key] = { - enumerable: true, - get: function () { - this._styles.push(code); - return this; - } - }; - }); - - return ret; -})(); - -var chalk = module.exports = defineProps({}, init()); - -function init() { - var ret = {}; - - Object.keys(styles).forEach(function (name) { - var code = styles[name]; - - ret[name] = { - enumerable: true, - get: function () { - var obj = defineProps(function self(str) { - if (!chalk.enabled) { - return str; - } - - return self._styles.reduce(function (str, code) { - return code + (str || ''); - }, str) + ansi['reset']; - }, styles); - - obj._styles = []; - - return obj[name]; - } - } - }); - - return ret; -} - -chalk.styles = ansi; - -chalk.stripColor = function (str) { - return str.replace(/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]/g, ''); -}; - -chalk.supportsColor = require('has-color'); - -// detect mode if not set manually -if (chalk.enabled === undefined) { - chalk.enabled = chalk.supportsColor; -} diff --git a/code-of-conduct.md b/code-of-conduct.md new file mode 100644 index 0000000..a7c7db8 --- /dev/null +++ b/code-of-conduct.md @@ -0,0 +1,74 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at sindresorhus@gmail.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/contributing.md b/contributing.md new file mode 100644 index 0000000..28bfd4b --- /dev/null +++ b/contributing.md @@ -0,0 +1,3 @@ +# Contributing to Chalk + +Please note that this project is released with a [Contributor Code of Conduct](code-of-conduct.md). By participating in this project you agree to abide by its terms. diff --git a/examples/rainbow.js b/examples/rainbow.js new file mode 100644 index 0000000..5b2b1d2 --- /dev/null +++ b/examples/rainbow.js @@ -0,0 +1,38 @@ +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 = /[^!-~]/g; + +function rainbow(string, offset) { + if (!string || string.length === 0) { + return string; + } + + const hueStep = 360 / string.replaceAll(ignoreChars, '').length; + + let hue = offset % 360; + const characters = []; + for (const character of string) { + if (ignoreChars.test(character)) { + characters.push(character); + } else { + characters.push(chalk.hex(convertColor.hsl.hex(hue, 100, 50))(character)); + hue = (hue + hueStep) % 360; + } + } + + return characters.join(''); +} + +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(); +await animateString('We hope you enjoy Chalk! <3'); +console.log(); diff --git a/examples/screenshot.js b/examples/screenshot.js new file mode 100644 index 0000000..9ad164b --- /dev/null +++ b/examples/screenshot.js @@ -0,0 +1,27 @@ +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 returnValue = key; + + // 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)) { + returnValue = chalk.black(returnValue); + } + + process.stdout.write(chalk[key](returnValue) + ' '); +} diff --git a/license b/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (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: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/media/logo.png b/media/logo.png new file mode 100644 index 0000000..dad5674 Binary files /dev/null and b/media/logo.png differ diff --git a/media/logo.svg b/media/logo.svg new file mode 100644 index 0000000..fcc3ea1 --- /dev/null +++ b/media/logo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/media/screenshot.png b/media/screenshot.png new file mode 100644 index 0000000..da9d89b Binary files /dev/null and b/media/screenshot.png differ diff --git a/package.json b/package.json index ff0de7d..c9e0dc5 100644 --- a/package.json +++ b/package.json @@ -1,55 +1,83 @@ { - "name": "chalk", - "version": "0.1.1", - "description": "Terminal string styling done right", - "keywords": [ - "color", - "colour", - "colors", - "terminal", - "console", - "cli", - "string", - "ansi", - "styles", - "tty", - "formatting", - "rgb", - "256", - "shell", - "xterm", - "log", - "logging", - "command-line", - "text" - ], - "homepage": "https://github.com/sindresorhus/chalk", - "bugs": "https://github.com/sindresorhus/chalk/issues", - "license": "MIT", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "http://sindresorhus.com" - }, - "files": [ - "chalk.js" - ], - "main": "chalk", - "repository": { - "type": "git", - "url": "git://github.com/sindresorhus/chalk.git" - }, - "scripts": { - "test": "mocha" - }, - "dependencies": { - "has-color": "~0.1.0", - "ansi-styles": "~0.1.0" - }, - "devDependencies": { - "mocha": "~1.12.0" - }, - "engines": { - "node": ">=0.8.0" - } + "name": "chalk", + "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": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "scripts": { + "test": "xo && c8 ava && tsd", + "bench": "matcha benchmark.js" + }, + "files": [ + "source", + "!source/index.test-d.ts" + ], + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "ansi", + "style", + "styles", + "tty", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "devDependencies": { + "@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", + "tsd": "^0.19.0", + "xo": "^0.57.0", + "yoctodelay": "^2.0.0" + }, + "xo": { + "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" + ] + } } diff --git a/readme.md b/readme.md index 35c61d0..ce1f3f3 100644 --- a/readme.md +++ b/readme.md @@ -1,125 +1,297 @@ -# chalk [![Build Status](https://secure.travis-ci.org/sindresorhus/chalk.png?branch=master)](http://travis-ci.org/sindresorhus/chalk) +

+
+
+ Chalk +
+
+
+

-> Terminal string styling done right. +> Terminal string styling done right -[colors.js](https://github.com/Marak/colors.js) is currently the most popular coloring module, but it has serious deficiencies like extending String.prototype which causes all kinds of problems. Although there are other ones, they either do too much or not enough. +[![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) -**Chalk is a clean and focused alternative.** +![](media/screenshot.png) -![screenshot](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 -## Why +## Highlights -- **Doesn't extend String.prototype** - 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 ~115,000 packages](https://www.npmjs.com/browse/depended/chalk) as of July 4, 2024 ## Install -Install with [npm](https://npmjs.org/package/chalk): `npm install --save 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) -## Example - -Chalk comes with an easy to use composable API where you just chain the styles you want. +## Usage ```js -var chalk = require('chalk'); +import chalk from 'chalk'; -// style a string console.log(chalk.blue('Hello world!')); - -// combine styled and normal strings -console.log(chalk.blue('Hello') + 'World' + chalk.red('!')); - -// compose multiple styles using the chainable API -console.log(chalk.blue.bgRed.bold('Hello world!')); ``` -You can easily define your own themes. +Chalk comes with an easy to use composable API where you just chain and nest the styles you want. ```js -var chalk = require('chalk'); -var error = chalk.bold.red; -console.log(error('Error!')); +import chalk from 'chalk'; + +const log = console.log; + +// Combine styled and normal strings +log(chalk.blue('Hello') + ' World' + chalk.red('!')); + +// Compose multiple styles using the chainable API +log(chalk.blue.bgRed.bold('Hello world!')); + +// Pass in multiple arguments +log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz')); + +// Nest styles +log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!')); + +// Nest styles of the same type even (color, underline, background) +log(chalk.green( + 'I am a green line ' + + chalk.blue.underline.bold('with a blue substring') + + ' that becomes green again!' +)); + +// ES2015 template literal +log(` +CPU: ${chalk.red('90%')} +RAM: ${chalk.green('40%')} +DISK: ${chalk.yellow('70%')} +`); + +// Use RGB colors in terminal emulators that support it. +log(chalk.rgb(123, 45, 67).underline('Underlined reddish color')); +log(chalk.hex('#DEADED').bold('Bold gray!')); ``` +Easily define your own themes: + +```js +import chalk from 'chalk'; + +const error = chalk.bold.red; +const warning = chalk.hex('#FFA500'); // Orange color + +console.log(error('Error!')); +console.log(warning('Warning!')); +``` + +Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args): + +```js +import chalk from 'chalk'; + +const name = 'Sindre'; +console.log(chalk.green('Hello %s'), name); +//=> 'Hello Sindre' +``` ## API -### chalk.\\[.\...\](*string*) +### chalk.`