[EDIT] FILE: jest-diff.tar
README.md 0000755 00000046353 15076543704 0006054 0 ustar 00 # jest-diff Display differences clearly so people can review changes confidently. The `diff` named export serializes JavaScript **values**, compares them line-by-line, and returns a string which includes comparison lines. Two named exports compare **strings** character-by-character: - `diffStringsUnified` returns a string. - `diffStringsRaw` returns an array of `Diff` objects. Three named exports compare **arrays of strings** line-by-line: - `diffLinesUnified` and `diffLinesUnified2` return a string. - `diffLinesRaw` returns an array of `Diff` objects. ## Installation To add this package as a dependency of a project, run either of the following commands: - `npm install jest-diff` - `yarn add jest-diff` ## Usage of `diff()` Given JavaScript **values**, `diff(a, b, options?)` does the following: 1. **serialize** the values as strings using the `pretty-format` package 2. **compare** the strings line-by-line using the `diff-sequences` package 3. **format** the changed or common lines using the `chalk` package To use this function, write either of the following: - `const {diff} = require('jest-diff');` in CommonJS modules - `import {diff} from 'jest-diff';` in ECMAScript modules ### Example of `diff()` ```js const a = ['delete', 'common', 'changed from']; const b = ['common', 'changed to', 'insert']; const difference = diff(a, b); ``` The returned **string** consists of: - annotation lines: describe the two change indicators with labels, and a blank line - comparison lines: similar to “unified” view on GitHub, but `Expected` lines are green, `Received` lines are red, and common lines are dim (by default, see Options) ```diff - Expected + Received Array [ - "delete", "common", - "changed from", + "changed to", + "insert", ] ``` ### Edge cases of `diff()` Here are edge cases for the return value: - `' Comparing two different types of values. …'` if the arguments have **different types** according to the `jest-get-type` package (instances of different classes have the same `'object'` type) - `'Compared values have no visual difference.'` if the arguments have either **referential identity** according to `Object.is` method or **same serialization** according to the `pretty-format` package - `null` if either argument is a so-called **asymmetric matcher** in Jasmine or Jest ## Usage of diffStringsUnified Given **strings**, `diffStringsUnified(a, b, options?)` does the following: 1. **compare** the strings character-by-character using the `diff-sequences` package 2. **clean up** small (often coincidental) common substrings, also known as chaff 3. **format** the changed or common lines using the `chalk` package Although the function is mainly for **multiline** strings, it compares any strings. Write either of the following: - `const {diffStringsUnified} = require('jest-diff');` in CommonJS modules - `import {diffStringsUnified} from 'jest-diff';` in ECMAScript modules ### Example of diffStringsUnified ```js const a = 'common\nchanged from'; const b = 'common\nchanged to'; const difference = diffStringsUnified(a, b); ``` The returned **string** consists of: - annotation lines: describe the two change indicators with labels, and a blank line - comparison lines: similar to “unified” view on GitHub, and **changed substrings** have **inverse** foreground and background colors (that is, `from` has white-on-green and `to` has white-on-red, which the following example does not show) ```diff - Expected + Received common - changed from + changed to ``` ### Performance of diffStringsUnified To get the benefit of **changed substrings** within the comparison lines, a character-by-character comparison has a higher computational cost (in time and space) than a line-by-line comparison. If the input strings can have **arbitrary length**, we recommend that the calling code set a limit, beyond which splits the strings, and then calls `diffLinesUnified` instead. For example, Jest falls back to line-by-line comparison if either string has length greater than 20K characters. ## Usage of diffLinesUnified Given **arrays of strings**, `diffLinesUnified(aLines, bLines, options?)` does the following: 1. **compare** the arrays line-by-line using the `diff-sequences` package 2. **format** the changed or common lines using the `chalk` package You might call this function when strings have been split into lines and you do not need to see changed substrings within lines. ### Example of diffLinesUnified ```js const aLines = ['delete', 'common', 'changed from']; const bLines = ['common', 'changed to', 'insert']; const difference = diffLinesUnified(aLines, bLines); ``` ```diff - Expected + Received - delete common - changed from + changed to + insert ``` ### Edge cases of diffLinesUnified or diffStringsUnified Here are edge cases for arguments and return values: - both `a` and `b` are empty strings: no comparison lines - only `a` is empty string: all comparison lines have `bColor` and `bIndicator` (see Options) - only `b` is empty string: all comparison lines have `aColor` and `aIndicator` (see Options) - `a` and `b` are equal non-empty strings: all comparison lines have `commonColor` and `commonIndicator` (see Options) ## Usage of diffLinesUnified2 Given two **pairs** of arrays of strings, `diffLinesUnified2(aLinesDisplay, bLinesDisplay, aLinesCompare, bLinesCompare, options?)` does the following: 1. **compare** the pair of `Compare` arrays line-by-line using the `diff-sequences` package 2. **format** the corresponding lines in the pair of `Display` arrays using the `chalk` package Jest calls this function to consider lines as common instead of changed if the only difference is indentation. You might call this function for case insensitive or Unicode equivalence comparison of lines. ### Example of diffLinesUnified2 ```js import {format} from 'pretty-format'; const a = { text: 'Ignore indentation in serialized object', time: '2019-09-19T12:34:56.000Z', type: 'CREATE_ITEM', }; const b = { payload: { text: 'Ignore indentation in serialized object', time: '2019-09-19T12:34:56.000Z', }, type: 'CREATE_ITEM', }; const difference = diffLinesUnified2( // serialize with indentation to display lines format(a).split('\n'), format(b).split('\n'), // serialize without indentation to compare lines format(a, {indent: 0}).split('\n'), format(b, {indent: 0}).split('\n'), ); ``` The `text` and `time` properties are common, because their only difference is indentation: ```diff - Expected + Received Object { + payload: Object { text: 'Ignore indentation in serialized object', time: '2019-09-19T12:34:56.000Z', + }, type: 'CREATE_ITEM', } ``` The preceding example illustrates why (at least for indentation) it seems more intuitive that the function returns the common line from the `bLinesDisplay` array instead of from the `aLinesDisplay` array. ## Usage of diffStringsRaw Given **strings** and a boolean option, `diffStringsRaw(a, b, cleanup)` does the following: 1. **compare** the strings character-by-character using the `diff-sequences` package 2. optionally **clean up** small (often coincidental) common substrings, also known as chaff Because `diffStringsRaw` returns the difference as **data** instead of a string, you can format it as your application requires (for example, enclosed in HTML markup for browser instead of escape sequences for console). The returned **array** describes substrings as instances of the `Diff` class, which calling code can access like array tuples: The value at index `0` is one of the following: | value | named export | description | | ----: | :------------ | :-------------------- | | `0` | `DIFF_EQUAL` | in `a` and in `b` | | `-1` | `DIFF_DELETE` | in `a` but not in `b` | | `1` | `DIFF_INSERT` | in `b` but not in `a` | The value at index `1` is a substring of `a` or `b` or both. ### Example of diffStringsRaw with cleanup ```js const diffs = diffStringsRaw('changed from', 'changed to', true); ``` | `i` | `diffs[i][0]` | `diffs[i][1]` | | --: | ------------: | :------------ | | `0` | `0` | `'changed '` | | `1` | `-1` | `'from'` | | `2` | `1` | `'to'` | ### Example of diffStringsRaw without cleanup ```js const diffs = diffStringsRaw('changed from', 'changed to', false); ``` | `i` | `diffs[i][0]` | `diffs[i][1]` | | --: | ------------: | :------------ | | `0` | `0` | `'changed '` | | `1` | `-1` | `'fr'` | | `2` | `1` | `'t'` | | `3` | `0` | `'o'` | | `4` | `-1` | `'m'` | ### Advanced import for diffStringsRaw Here are all the named imports that you might need for the `diffStringsRaw` function: - `const {DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, diffStringsRaw} = require('jest-diff');` in CommonJS modules - `import {DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, diffStringsRaw} from 'jest-diff';` in ECMAScript modules To write a **formatting** function, you might need the named constants (and `Diff` in TypeScript annotations). If you write an application-specific **cleanup** algorithm, then you might need to call the `Diff` constructor: ```js const diffCommon = new Diff(DIFF_EQUAL, 'changed '); const diffDelete = new Diff(DIFF_DELETE, 'from'); const diffInsert = new Diff(DIFF_INSERT, 'to'); ``` ## Usage of diffLinesRaw Given **arrays of strings**, `diffLinesRaw(aLines, bLines)` does the following: - **compare** the arrays line-by-line using the `diff-sequences` package Because `diffLinesRaw` returns the difference as **data** instead of a string, you can format it as your application requires. ### Example of diffLinesRaw ```js const aLines = ['delete', 'common', 'changed from']; const bLines = ['common', 'changed to', 'insert']; const diffs = diffLinesRaw(aLines, bLines); ``` | `i` | `diffs[i][0]` | `diffs[i][1]` | | --: | ------------: | :--------------- | | `0` | `-1` | `'delete'` | | `1` | `0` | `'common'` | | `2` | `-1` | `'changed from'` | | `3` | `1` | `'changed to'` | | `4` | `1` | `'insert'` | ### Edge case of diffLinesRaw If you call `string.split('\n')` for an empty string: - the result is `['']` an array which contains an empty string - instead of `[]` an empty array Depending of your application, you might call `diffLinesRaw` with either array. ### Example of split method ```js import {diffLinesRaw} from 'jest-diff'; const a = 'non-empty string'; const b = ''; const diffs = diffLinesRaw(a.split('\n'), b.split('\n')); ``` | `i` | `diffs[i][0]` | `diffs[i][1]` | | --: | ------------: | :------------------- | | `0` | `-1` | `'non-empty string'` | | `1` | `1` | `''` | Which you might format as follows: ```diff - Expected - 1 + Received + 1 - non-empty string + ``` ### Example of splitLines0 function For edge case behavior like the `diffLinesUnified` function, you might define a `splitLines0` function, which given an empty string, returns `[]` an empty array: ```js export const splitLines0 = string => string.length === 0 ? [] : string.split('\n'); ``` ```js import {diffLinesRaw} from 'jest-diff'; const a = ''; const b = 'line 1\nline 2\nline 3'; const diffs = diffLinesRaw(a.split('\n'), b.split('\n')); ``` | `i` | `diffs[i][0]` | `diffs[i][1]` | | --: | ------------: | :------------ | | `0` | `1` | `'line 1'` | | `1` | `1` | `'line 2'` | | `2` | `1` | `'line 3'` | Which you might format as follows: ```diff - Expected - 0 + Received + 3 + line 1 + line 2 + line 3 ``` In contrast to the `diffLinesRaw` function, the `diffLinesUnified` and `diffLinesUnified2` functions **automatically** convert array arguments computed by string `split` method, so callers do **not** need a `splitLine0` function. ## Options The default options are for the report when an assertion fails from the `expect` package used by Jest. For other applications, you can provide an options object as a third argument: - `diff(a, b, options)` - `diffStringsUnified(a, b, options)` - `diffLinesUnified(aLines, bLines, options)` - `diffLinesUnified2(aLinesDisplay, bLinesDisplay, aLinesCompare, bLinesCompare, options)` ### Properties of options object | name | default | | :-------------------------------- | :----------------- | | `aAnnotation` | `'Expected'` | | `aColor` | `chalk.green` | | `aIndicator` | `'-'` | | `bAnnotation` | `'Received'` | | `bColor` | `chalk.red` | | `bIndicator` | `'+'` | | `changeColor` | `chalk.inverse` | | `changeLineTrailingSpaceColor` | `string => string` | | `commonColor` | `chalk.dim` | | `commonIndicator` | `' '` | | `commonLineTrailingSpaceColor` | `string => string` | | `compareKeys` | `undefined` | | `contextLines` | `5` | | `emptyFirstOrLastLinePlaceholder` | `''` | | `expand` | `true` | | `includeChangeCounts` | `false` | | `omitAnnotationLines` | `false` | | `patchColor` | `chalk.yellow` | For more information about the options, see the following examples. ### Example of options for labels If the application is code modification, you might replace the labels: ```js const options = { aAnnotation: 'Original', bAnnotation: 'Modified', }; ``` ```diff - Original + Modified common - changed from + changed to ``` The `jest-diff` package does not assume that the 2 labels have equal length. ### Example of options for colors of changed lines For consistency with most diff tools, you might exchange the colors: ```ts import chalk = require('chalk'); const options = { aColor: chalk.red, bColor: chalk.green, }; ``` ### Example of option for color of changed substrings Although the default inverse of foreground and background colors is hard to beat for changed substrings **within lines**, especially because it highlights spaces, if you want bold font weight on yellow background color: ```ts import chalk = require('chalk'); const options = { changeColor: chalk.bold.bgYellowBright, }; ``` ### Example of option to format trailing spaces Because `diff()` does not display substring differences within lines, formatting can help you see when lines differ by the presence or absence of trailing spaces found by `/\s+$/` regular expression. - If change lines have a background color, then you can see trailing spaces. - If common lines have default dim color, then you cannot see trailing spaces. You might want yellowish background color to see them. ```js const options = { aColor: chalk.rgb(128, 0, 128).bgRgb(255, 215, 255), // magenta bColor: chalk.rgb(0, 95, 0).bgRgb(215, 255, 215), // green commonLineTrailingSpaceColor: chalk.bgYellow, }; ``` The value of a Color option is a function, which given a string, returns a string. If you want to replace trailing spaces with middle dot characters: ```js const replaceSpacesWithMiddleDot = string => '·'.repeat(string.length); const options = { changeLineTrailingSpaceColor: replaceSpacesWithMiddleDot, commonLineTrailingSpaceColor: replaceSpacesWithMiddleDot, }; ``` If you need the TypeScript type of a Color option: ```ts import {DiffOptionsColor} from 'jest-diff'; ``` ### Example of options for no colors To store the difference in a file without escape codes for colors, provide an identity function: ```js const noColor = string => string; const options = { aColor: noColor, bColor: noColor, changeColor: noColor, commonColor: noColor, patchColor: noColor, }; ``` ### Example of options for indicators For consistency with the `diff` command, you might replace the indicators: ```js const options = { aIndicator: '<', bIndicator: '>', }; ``` The `jest-diff` package assumes (but does not enforce) that the 3 indicators have equal length. ### Example of options to limit common lines By default, the output includes all common lines. To emphasize the changes, you might limit the number of common “context” lines: ```js const options = { contextLines: 1, expand: false, }; ``` A patch mark like `@@ -12,7 +12,9 @@` accounts for omitted common lines. ### Example of option for color of patch marks If you want patch marks to have the same dim color as common lines: ```ts import chalk = require('chalk'); const options = { expand: false, patchColor: chalk.dim, }; ``` ### Example of option to include change counts To display the number of changed lines at the right of annotation lines: ```js const a = ['common', 'changed from']; const b = ['common', 'changed to', 'insert']; const options = { includeChangeCounts: true, }; const difference = diff(a, b, options); ``` ```diff - Expected - 1 + Received + 2 Array [ "common", - "changed from", + "changed to", + "insert", ] ``` ### Example of option to omit annotation lines To display only the comparison lines: ```js const a = 'common\nchanged from'; const b = 'common\nchanged to'; const options = { omitAnnotationLines: true, }; const difference = diffStringsUnified(a, b, options); ``` ```diff common - changed from + changed to ``` ### Example of option for empty first or last lines If the **first** or **last** comparison line is **empty**, because the content is empty and the indicator is a space, you might not notice it. The replacement option is a string whose default value is `''` empty string. Because Jest trims the report when a matcher fails, it deletes an empty last line. Therefore, Jest uses as placeholder the downwards arrow with corner leftwards: ```js const options = { emptyFirstOrLastLinePlaceholder: '↵', // U+21B5 }; ``` If a content line is empty, then the corresponding comparison line is automatically trimmed to remove the margin space (represented as a middle dot below) for the default indicators: | Indicator | untrimmed | trimmed | | ----------------: | :-------- | :------ | | `aIndicator` | `'-·'` | `'-'` | | `bIndicator` | `'+·'` | `'+'` | | `commonIndicator` | `' ·'` | `''` | ### Example of option for sorting object keys When two objects are compared their keys are printed in alphabetical order by default. If this was not the original order of the keys the diff becomes harder to read as the keys are not in their original position. Use `compareKeys` to pass a function which will be used when sorting the object keys. ```js const a = {c: 'c', b: 'b1', a: 'a'}; const b = {c: 'c', b: 'b2', a: 'a'}; const options = { // The keys will be in their original order compareKeys: () => 0, }; const difference = diff(a, b, options); ``` ```diff - Expected + Received Object { "c": "c", - "b": "b1", + "b": "b2", "a": "a", } ``` Depending on the implementation of `compareKeys` any sort order can be used. ```js const a = {c: 'c', b: 'b1', a: 'a'}; const b = {c: 'c', b: 'b2', a: 'a'}; const options = { // The keys will be in reverse order compareKeys: (a, b) => (a > b ? -1 : 1), }; const difference = diff(a, b, options); ``` ```diff - Expected + Received Object { "a": "a", - "b": "b1", + "b": "b2", "c": "c", } ``` LICENSE 0000755 00000002076 15076543704 0005574 0 ustar 00 MIT License Copyright (c) Facebook, Inc. and its affiliates. 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. package.json 0000755 00000001500 15076543704 0007044 0 ustar 00 { "name": "jest-diff", "version": "27.5.1", "repository": { "type": "git", "url": "https://github.com/facebook/jest.git", "directory": "packages/jest-diff" }, "license": "MIT", "main": "./build/index.js", "types": "./build/index.d.ts", "exports": { ".": { "types": "./build/index.d.ts", "default": "./build/index.js" }, "./package.json": "./package.json" }, "dependencies": { "chalk": "^4.0.0", "diff-sequences": "^27.5.1", "jest-get-type": "^27.5.1", "pretty-format": "^27.5.1" }, "devDependencies": { "@jest/test-utils": "^27.5.1", "strip-ansi": "^6.0.0" }, "engines": { "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" }, "publishConfig": { "access": "public" }, "gitHead": "67c1aa20c5fec31366d733e901fee2b981cb1850" } build/types.js 0000755 00000000016 15076543704 0007360 0 ustar 00 'use strict'; build/getAlignedDiffs.d.ts 0000755 00000000660 15076543704 0011474 0 ustar 00 /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { Diff } from './cleanupSemantic'; import type { DiffOptionsColor } from './types'; declare const getAlignedDiffs: (diffs: Array<Diff>, changeColor: DiffOptionsColor) => Array<Diff>; export default getAlignedDiffs; build/constants.js 0000755 00000001226 15076543704 0010234 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.SIMILAR_MESSAGE = exports.NO_DIFF_MESSAGE = void 0; /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const NO_DIFF_MESSAGE = 'Compared values have no visual difference.'; exports.NO_DIFF_MESSAGE = NO_DIFF_MESSAGE; const SIMILAR_MESSAGE = 'Compared values serialize to the same structure.\n' + 'Printing internal object structure without calling `toJSON` instead.'; exports.SIMILAR_MESSAGE = SIMILAR_MESSAGE; build/printDiffs.d.ts 0000755 00000000764 15076543704 0010572 0 ustar 00 /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { Diff } from './cleanupSemantic'; import type { DiffOptions } from './types'; export declare const diffStringsUnified: (a: string, b: string, options?: DiffOptions | undefined) => string; export declare const diffStringsRaw: (a: string, b: string, cleanup: boolean) => Array<Diff>; build/printDiffs.js 0000755 00000005000 15076543704 0010322 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.diffStringsUnified = exports.diffStringsRaw = void 0; var _cleanupSemantic = require('./cleanupSemantic'); var _diffLines = require('./diffLines'); var _diffStrings = _interopRequireDefault(require('./diffStrings')); var _getAlignedDiffs = _interopRequireDefault(require('./getAlignedDiffs')); var _normalizeDiffOptions = require('./normalizeDiffOptions'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : {default: obj}; } /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const hasCommonDiff = (diffs, isMultiline) => { if (isMultiline) { // Important: Ignore common newline that was appended to multiline strings! const iLast = diffs.length - 1; return diffs.some( (diff, i) => diff[0] === _cleanupSemantic.DIFF_EQUAL && (i !== iLast || diff[1] !== '\n') ); } return diffs.some(diff => diff[0] === _cleanupSemantic.DIFF_EQUAL); }; // Compare two strings character-by-character. // Format as comparison lines in which changed substrings have inverse colors. const diffStringsUnified = (a, b, options) => { if (a !== b && a.length !== 0 && b.length !== 0) { const isMultiline = a.includes('\n') || b.includes('\n'); // getAlignedDiffs assumes that a newline was appended to the strings. const diffs = diffStringsRaw( isMultiline ? a + '\n' : a, isMultiline ? b + '\n' : b, true // cleanupSemantic ); if (hasCommonDiff(diffs, isMultiline)) { const optionsNormalized = (0, _normalizeDiffOptions.normalizeDiffOptions)( options ); const lines = (0, _getAlignedDiffs.default)( diffs, optionsNormalized.changeColor ); return (0, _diffLines.printDiffLines)(lines, optionsNormalized); } } // Fall back to line-by-line diff. return (0, _diffLines.diffLinesUnified)( a.split('\n'), b.split('\n'), options ); }; // Compare two strings character-by-character. // Optionally clean up small common substrings, also known as chaff. exports.diffStringsUnified = diffStringsUnified; const diffStringsRaw = (a, b, cleanup) => { const diffs = (0, _diffStrings.default)(a, b); if (cleanup) { (0, _cleanupSemantic.cleanupSemantic)(diffs); // impure function } return diffs; }; exports.diffStringsRaw = diffStringsRaw; build/diffLines.d.ts 0000755 00000001531 15076543704 0010356 0 ustar 00 /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { Diff } from './cleanupSemantic'; import type { DiffOptions, DiffOptionsNormalized } from './types'; export declare const printDiffLines: (diffs: Array<Diff>, options: DiffOptionsNormalized) => string; export declare const diffLinesUnified: (aLines: Array<string>, bLines: Array<string>, options?: DiffOptions | undefined) => string; export declare const diffLinesUnified2: (aLinesDisplay: Array<string>, bLinesDisplay: Array<string>, aLinesCompare: Array<string>, bLinesCompare: Array<string>, options?: DiffOptions | undefined) => string; export declare const diffLinesRaw: (aLines: Array<string>, bLines: Array<string>) => Array<Diff>; build/constants.d.ts 0000755 00000000525 15076543704 0010471 0 ustar 00 /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ export declare const NO_DIFF_MESSAGE = "Compared values have no visual difference."; export declare const SIMILAR_MESSAGE: string; build/diffStrings.d.ts 0000755 00000000532 15076543704 0010735 0 ustar 00 /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { Diff } from './cleanupSemantic'; declare const diffStrings: (a: string, b: string) => Array<Diff>; export default diffStrings; build/diffStrings.js 0000755 00000003554 15076543704 0010510 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.default = void 0; var _diffSequences = _interopRequireDefault(require('diff-sequences')); var _cleanupSemantic = require('./cleanupSemantic'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : {default: obj}; } /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const diffStrings = (a, b) => { const isCommon = (aIndex, bIndex) => a[aIndex] === b[bIndex]; let aIndex = 0; let bIndex = 0; const diffs = []; const foundSubsequence = (nCommon, aCommon, bCommon) => { if (aIndex !== aCommon) { diffs.push( new _cleanupSemantic.Diff( _cleanupSemantic.DIFF_DELETE, a.slice(aIndex, aCommon) ) ); } if (bIndex !== bCommon) { diffs.push( new _cleanupSemantic.Diff( _cleanupSemantic.DIFF_INSERT, b.slice(bIndex, bCommon) ) ); } aIndex = aCommon + nCommon; // number of characters compared in a bIndex = bCommon + nCommon; // number of characters compared in b diffs.push( new _cleanupSemantic.Diff( _cleanupSemantic.DIFF_EQUAL, b.slice(bCommon, bIndex) ) ); }; (0, _diffSequences.default)(a.length, b.length, isCommon, foundSubsequence); // After the last common subsequence, push remaining change items. if (aIndex !== a.length) { diffs.push( new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_DELETE, a.slice(aIndex)) ); } if (bIndex !== b.length) { diffs.push( new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_INSERT, b.slice(bIndex)) ); } return diffs; }; var _default = diffStrings; exports.default = _default; build/index.d.ts 0000755 00000001430 15076543704 0007560 0 ustar 00 /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff } from './cleanupSemantic'; import { diffLinesRaw, diffLinesUnified, diffLinesUnified2 } from './diffLines'; import { diffStringsRaw, diffStringsUnified } from './printDiffs'; import type { DiffOptions } from './types'; export type { DiffOptions, DiffOptionsColor } from './types'; export { diffLinesRaw, diffLinesUnified, diffLinesUnified2 }; export { diffStringsRaw, diffStringsUnified }; export { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff }; export declare function diff(a: any, b: any, options?: DiffOptions): string | null; build/getAlignedDiffs.js 0000755 00000016107 15076543704 0011243 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.default = void 0; var _cleanupSemantic = require('./cleanupSemantic'); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } // Given change op and array of diffs, return concatenated string: // * include common strings // * include change strings which have argument op with changeColor // * exclude change strings which have opposite op const concatenateRelevantDiffs = (op, diffs, changeColor) => diffs.reduce( (reduced, diff) => reduced + (diff[0] === _cleanupSemantic.DIFF_EQUAL ? diff[1] : diff[0] === op && diff[1].length !== 0 // empty if change is newline ? changeColor(diff[1]) : ''), '' ); // Encapsulate change lines until either a common newline or the end. class ChangeBuffer { // incomplete line // complete lines constructor(op, changeColor) { _defineProperty(this, 'op', void 0); _defineProperty(this, 'line', void 0); _defineProperty(this, 'lines', void 0); _defineProperty(this, 'changeColor', void 0); this.op = op; this.line = []; this.lines = []; this.changeColor = changeColor; } pushSubstring(substring) { this.pushDiff(new _cleanupSemantic.Diff(this.op, substring)); } pushLine() { // Assume call only if line has at least one diff, // therefore an empty line must have a diff which has an empty string. // If line has multiple diffs, then assume it has a common diff, // therefore change diffs have change color; // otherwise then it has line color only. this.lines.push( this.line.length !== 1 ? new _cleanupSemantic.Diff( this.op, concatenateRelevantDiffs(this.op, this.line, this.changeColor) ) : this.line[0][0] === this.op ? this.line[0] // can use instance : new _cleanupSemantic.Diff(this.op, this.line[0][1]) // was common diff ); this.line.length = 0; } isLineEmpty() { return this.line.length === 0; } // Minor input to buffer. pushDiff(diff) { this.line.push(diff); } // Main input to buffer. align(diff) { const string = diff[1]; if (string.includes('\n')) { const substrings = string.split('\n'); const iLast = substrings.length - 1; substrings.forEach((substring, i) => { if (i < iLast) { // The first substring completes the current change line. // A middle substring is a change line. this.pushSubstring(substring); this.pushLine(); } else if (substring.length !== 0) { // The last substring starts a change line, if it is not empty. // Important: This non-empty condition also automatically omits // the newline appended to the end of expected and received strings. this.pushSubstring(substring); } }); } else { // Append non-multiline string to current change line. this.pushDiff(diff); } } // Output from buffer. moveLinesTo(lines) { if (!this.isLineEmpty()) { this.pushLine(); } lines.push(...this.lines); this.lines.length = 0; } } // Encapsulate common and change lines. class CommonBuffer { constructor(deleteBuffer, insertBuffer) { _defineProperty(this, 'deleteBuffer', void 0); _defineProperty(this, 'insertBuffer', void 0); _defineProperty(this, 'lines', void 0); this.deleteBuffer = deleteBuffer; this.insertBuffer = insertBuffer; this.lines = []; } pushDiffCommonLine(diff) { this.lines.push(diff); } pushDiffChangeLines(diff) { const isDiffEmpty = diff[1].length === 0; // An empty diff string is redundant, unless a change line is empty. if (!isDiffEmpty || this.deleteBuffer.isLineEmpty()) { this.deleteBuffer.pushDiff(diff); } if (!isDiffEmpty || this.insertBuffer.isLineEmpty()) { this.insertBuffer.pushDiff(diff); } } flushChangeLines() { this.deleteBuffer.moveLinesTo(this.lines); this.insertBuffer.moveLinesTo(this.lines); } // Input to buffer. align(diff) { const op = diff[0]; const string = diff[1]; if (string.includes('\n')) { const substrings = string.split('\n'); const iLast = substrings.length - 1; substrings.forEach((substring, i) => { if (i === 0) { const subdiff = new _cleanupSemantic.Diff(op, substring); if ( this.deleteBuffer.isLineEmpty() && this.insertBuffer.isLineEmpty() ) { // If both current change lines are empty, // then the first substring is a common line. this.flushChangeLines(); this.pushDiffCommonLine(subdiff); } else { // If either current change line is non-empty, // then the first substring completes the change lines. this.pushDiffChangeLines(subdiff); this.flushChangeLines(); } } else if (i < iLast) { // A middle substring is a common line. this.pushDiffCommonLine(new _cleanupSemantic.Diff(op, substring)); } else if (substring.length !== 0) { // The last substring starts a change line, if it is not empty. // Important: This non-empty condition also automatically omits // the newline appended to the end of expected and received strings. this.pushDiffChangeLines(new _cleanupSemantic.Diff(op, substring)); } }); } else { // Append non-multiline string to current change lines. // Important: It cannot be at the end following empty change lines, // because newline appended to the end of expected and received strings. this.pushDiffChangeLines(diff); } } // Output from buffer. getLines() { this.flushChangeLines(); return this.lines; } } // Given diffs from expected and received strings, // return new array of diffs split or joined into lines. // // To correctly align a change line at the end, the algorithm: // * assumes that a newline was appended to the strings // * omits the last newline from the output array // // Assume the function is not called: // * if either expected or received is empty string // * if neither expected nor received is multiline string const getAlignedDiffs = (diffs, changeColor) => { const deleteBuffer = new ChangeBuffer( _cleanupSemantic.DIFF_DELETE, changeColor ); const insertBuffer = new ChangeBuffer( _cleanupSemantic.DIFF_INSERT, changeColor ); const commonBuffer = new CommonBuffer(deleteBuffer, insertBuffer); diffs.forEach(diff => { switch (diff[0]) { case _cleanupSemantic.DIFF_DELETE: deleteBuffer.align(diff); break; case _cleanupSemantic.DIFF_INSERT: insertBuffer.align(diff); break; default: commonBuffer.align(diff); } }); return commonBuffer.getLines(); }; var _default = getAlignedDiffs; exports.default = _default; build/cleanupSemantic.d.ts 0000755 00000004270 15076543704 0011571 0 ustar 00 /** * Diff Match and Patch * Copyright 2018 The diff-match-patch Authors. * https://github.com/google/diff-match-patch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Computes the difference between two texts to create a patch. * Applies the patch onto another text, allowing for errors. * @author fraser@google.com (Neil Fraser) */ /** * CHANGES by pedrottimark to diff_match_patch_uncompressed.ts file: * * 1. Delete anything not needed to use diff_cleanupSemantic method * 2. Convert from prototype properties to var declarations * 3. Convert Diff to class from constructor and prototype * 4. Add type annotations for arguments and return values * 5. Add exports */ /** * The data structure representing a diff is an array of tuples: * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] * which means: delete 'Hello', add 'Goodbye' and keep ' world.' */ declare var DIFF_DELETE: number; declare var DIFF_INSERT: number; declare var DIFF_EQUAL: number; /** * Class representing one diff tuple. * Attempts to look like a two-element array (which is what this used to be). * @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL. * @param {string} text Text to be deleted, inserted, or retained. * @constructor */ declare class Diff { 0: number; 1: string; constructor(op: number, text: string); } /** * Reduce the number of edits by eliminating semantically trivial equalities. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. */ declare var diff_cleanupSemantic: (diffs: Array<Diff>) => void; export { Diff, DIFF_EQUAL, DIFF_DELETE, DIFF_INSERT, diff_cleanupSemantic as cleanupSemantic, }; build/normalizeDiffOptions.js 0000755 00000003417 15076543704 0012371 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.normalizeDiffOptions = exports.noColor = void 0; var _chalk = _interopRequireDefault(require('chalk')); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : {default: obj}; } /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const noColor = string => string; exports.noColor = noColor; const DIFF_CONTEXT_DEFAULT = 5; const OPTIONS_DEFAULT = { aAnnotation: 'Expected', aColor: _chalk.default.green, aIndicator: '-', bAnnotation: 'Received', bColor: _chalk.default.red, bIndicator: '+', changeColor: _chalk.default.inverse, changeLineTrailingSpaceColor: noColor, commonColor: _chalk.default.dim, commonIndicator: ' ', commonLineTrailingSpaceColor: noColor, compareKeys: undefined, contextLines: DIFF_CONTEXT_DEFAULT, emptyFirstOrLastLinePlaceholder: '', expand: true, includeChangeCounts: false, omitAnnotationLines: false, patchColor: _chalk.default.yellow }; const getCompareKeys = compareKeys => compareKeys && typeof compareKeys === 'function' ? compareKeys : OPTIONS_DEFAULT.compareKeys; const getContextLines = contextLines => typeof contextLines === 'number' && Number.isSafeInteger(contextLines) && contextLines >= 0 ? contextLines : DIFF_CONTEXT_DEFAULT; // Pure function returns options with all properties. const normalizeDiffOptions = (options = {}) => ({ ...OPTIONS_DEFAULT, ...options, compareKeys: getCompareKeys(options.compareKeys), contextLines: getContextLines(options.contextLines) }); exports.normalizeDiffOptions = normalizeDiffOptions; build/cleanupSemantic.js 0000755 00000050202 15076543704 0011331 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.cleanupSemantic = exports.Diff = exports.DIFF_INSERT = exports.DIFF_EQUAL = exports.DIFF_DELETE = void 0; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } /** * Diff Match and Patch * Copyright 2018 The diff-match-patch Authors. * https://github.com/google/diff-match-patch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Computes the difference between two texts to create a patch. * Applies the patch onto another text, allowing for errors. * @author fraser@google.com (Neil Fraser) */ /** * CHANGES by pedrottimark to diff_match_patch_uncompressed.ts file: * * 1. Delete anything not needed to use diff_cleanupSemantic method * 2. Convert from prototype properties to var declarations * 3. Convert Diff to class from constructor and prototype * 4. Add type annotations for arguments and return values * 5. Add exports */ /** * The data structure representing a diff is an array of tuples: * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] * which means: delete 'Hello', add 'Goodbye' and keep ' world.' */ var DIFF_DELETE = -1; exports.DIFF_DELETE = DIFF_DELETE; var DIFF_INSERT = 1; exports.DIFF_INSERT = DIFF_INSERT; var DIFF_EQUAL = 0; /** * Class representing one diff tuple. * Attempts to look like a two-element array (which is what this used to be). * @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL. * @param {string} text Text to be deleted, inserted, or retained. * @constructor */ exports.DIFF_EQUAL = DIFF_EQUAL; class Diff { constructor(op, text) { _defineProperty(this, 0, void 0); _defineProperty(this, 1, void 0); this[0] = op; this[1] = text; } } /** * Determine the common prefix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the start of each * string. */ exports.Diff = Diff; var diff_commonPrefix = function (text1, text2) { // Quick check for common null cases. if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) { return 0; } // Binary search. // Performance analysis: https://neil.fraser.name/news/2007/10/09/ var pointermin = 0; var pointermax = Math.min(text1.length, text2.length); var pointermid = pointermax; var pointerstart = 0; while (pointermin < pointermid) { if ( text1.substring(pointerstart, pointermid) == text2.substring(pointerstart, pointermid) ) { pointermin = pointermid; pointerstart = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } return pointermid; }; /** * Determine the common suffix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the end of each string. */ var diff_commonSuffix = function (text1, text2) { // Quick check for common null cases. if ( !text1 || !text2 || text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1) ) { return 0; } // Binary search. // Performance analysis: https://neil.fraser.name/news/2007/10/09/ var pointermin = 0; var pointermax = Math.min(text1.length, text2.length); var pointermid = pointermax; var pointerend = 0; while (pointermin < pointermid) { if ( text1.substring(text1.length - pointermid, text1.length - pointerend) == text2.substring(text2.length - pointermid, text2.length - pointerend) ) { pointermin = pointermid; pointerend = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } return pointermid; }; /** * Determine if the suffix of one string is the prefix of another. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the end of the first * string and the start of the second string. * @private */ var diff_commonOverlap_ = function (text1, text2) { // Cache the text lengths to prevent multiple calls. var text1_length = text1.length; var text2_length = text2.length; // Eliminate the null case. if (text1_length == 0 || text2_length == 0) { return 0; } // Truncate the longer string. if (text1_length > text2_length) { text1 = text1.substring(text1_length - text2_length); } else if (text1_length < text2_length) { text2 = text2.substring(0, text1_length); } var text_length = Math.min(text1_length, text2_length); // Quick check for the worst case. if (text1 == text2) { return text_length; } // Start by looking for a single character match // and increase length until no match is found. // Performance analysis: https://neil.fraser.name/news/2010/11/04/ var best = 0; var length = 1; while (true) { var pattern = text1.substring(text_length - length); var found = text2.indexOf(pattern); if (found == -1) { return best; } length += found; if ( found == 0 || text1.substring(text_length - length) == text2.substring(0, length) ) { best = length; length++; } } }; /** * Reduce the number of edits by eliminating semantically trivial equalities. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. */ var diff_cleanupSemantic = function (diffs) { var changes = false; var equalities = []; // Stack of indices where equalities are found. var equalitiesLength = 0; // Keeping our own length var is faster in JS. /** @type {?string} */ var lastEquality = null; // Always equal to diffs[equalities[equalitiesLength - 1]][1] var pointer = 0; // Index of current position. // Number of characters that changed prior to the equality. var length_insertions1 = 0; var length_deletions1 = 0; // Number of characters that changed after the equality. var length_insertions2 = 0; var length_deletions2 = 0; while (pointer < diffs.length) { if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found. equalities[equalitiesLength++] = pointer; length_insertions1 = length_insertions2; length_deletions1 = length_deletions2; length_insertions2 = 0; length_deletions2 = 0; lastEquality = diffs[pointer][1]; } else { // An insertion or deletion. if (diffs[pointer][0] == DIFF_INSERT) { length_insertions2 += diffs[pointer][1].length; } else { length_deletions2 += diffs[pointer][1].length; } // Eliminate an equality that is smaller or equal to the edits on both // sides of it. if ( lastEquality && lastEquality.length <= Math.max(length_insertions1, length_deletions1) && lastEquality.length <= Math.max(length_insertions2, length_deletions2) ) { // Duplicate record. diffs.splice( equalities[equalitiesLength - 1], 0, new Diff(DIFF_DELETE, lastEquality) ); // Change second copy to insert. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; // Throw away the equality we just deleted. equalitiesLength--; // Throw away the previous equality (it needs to be reevaluated). equalitiesLength--; pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; length_insertions1 = 0; // Reset the counters. length_deletions1 = 0; length_insertions2 = 0; length_deletions2 = 0; lastEquality = null; changes = true; } } pointer++; } // Normalize the diff. if (changes) { diff_cleanupMerge(diffs); } diff_cleanupSemanticLossless(diffs); // Find any overlaps between deletions and insertions. // e.g: <del>abcxxx</del><ins>xxxdef</ins> // -> <del>abc</del>xxx<ins>def</ins> // e.g: <del>xxxabc</del><ins>defxxx</ins> // -> <ins>def</ins>xxx<del>abc</del> // Only extract an overlap if it is as big as the edit ahead or behind it. pointer = 1; while (pointer < diffs.length) { if ( diffs[pointer - 1][0] == DIFF_DELETE && diffs[pointer][0] == DIFF_INSERT ) { var deletion = diffs[pointer - 1][1]; var insertion = diffs[pointer][1]; var overlap_length1 = diff_commonOverlap_(deletion, insertion); var overlap_length2 = diff_commonOverlap_(insertion, deletion); if (overlap_length1 >= overlap_length2) { if ( overlap_length1 >= deletion.length / 2 || overlap_length1 >= insertion.length / 2 ) { // Overlap found. Insert an equality and trim the surrounding edits. diffs.splice( pointer, 0, new Diff(DIFF_EQUAL, insertion.substring(0, overlap_length1)) ); diffs[pointer - 1][1] = deletion.substring( 0, deletion.length - overlap_length1 ); diffs[pointer + 1][1] = insertion.substring(overlap_length1); pointer++; } } else { if ( overlap_length2 >= deletion.length / 2 || overlap_length2 >= insertion.length / 2 ) { // Reverse overlap found. // Insert an equality and swap and trim the surrounding edits. diffs.splice( pointer, 0, new Diff(DIFF_EQUAL, deletion.substring(0, overlap_length2)) ); diffs[pointer - 1][0] = DIFF_INSERT; diffs[pointer - 1][1] = insertion.substring( 0, insertion.length - overlap_length2 ); diffs[pointer + 1][0] = DIFF_DELETE; diffs[pointer + 1][1] = deletion.substring(overlap_length2); pointer++; } } pointer++; } pointer++; } }; /** * Look for single edits surrounded on both sides by equalities * which can be shifted sideways to align the edit to a word boundary. * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. */ exports.cleanupSemantic = diff_cleanupSemantic; var diff_cleanupSemanticLossless = function (diffs) { /** * Given two strings, compute a score representing whether the internal * boundary falls on logical boundaries. * Scores range from 6 (best) to 0 (worst). * Closure, but does not reference any external variables. * @param {string} one First string. * @param {string} two Second string. * @return {number} The score. * @private */ function diff_cleanupSemanticScore_(one, two) { if (!one || !two) { // Edges are the best. return 6; } // Each port of this function behaves slightly differently due to // subtle differences in each language's definition of things like // 'whitespace'. Since this function's purpose is largely cosmetic, // the choice has been made to use each language's native features // rather than force total conformity. var char1 = one.charAt(one.length - 1); var char2 = two.charAt(0); var nonAlphaNumeric1 = char1.match(nonAlphaNumericRegex_); var nonAlphaNumeric2 = char2.match(nonAlphaNumericRegex_); var whitespace1 = nonAlphaNumeric1 && char1.match(whitespaceRegex_); var whitespace2 = nonAlphaNumeric2 && char2.match(whitespaceRegex_); var lineBreak1 = whitespace1 && char1.match(linebreakRegex_); var lineBreak2 = whitespace2 && char2.match(linebreakRegex_); var blankLine1 = lineBreak1 && one.match(blanklineEndRegex_); var blankLine2 = lineBreak2 && two.match(blanklineStartRegex_); if (blankLine1 || blankLine2) { // Five points for blank lines. return 5; } else if (lineBreak1 || lineBreak2) { // Four points for line breaks. return 4; } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { // Three points for end of sentences. return 3; } else if (whitespace1 || whitespace2) { // Two points for whitespace. return 2; } else if (nonAlphaNumeric1 || nonAlphaNumeric2) { // One point for non-alphanumeric. return 1; } return 0; } var pointer = 1; // Intentionally ignore the first and last element (don't need checking). while (pointer < diffs.length - 1) { if ( diffs[pointer - 1][0] == DIFF_EQUAL && diffs[pointer + 1][0] == DIFF_EQUAL ) { // This is a single edit surrounded by equalities. var equality1 = diffs[pointer - 1][1]; var edit = diffs[pointer][1]; var equality2 = diffs[pointer + 1][1]; // First, shift the edit as far left as possible. var commonOffset = diff_commonSuffix(equality1, edit); if (commonOffset) { var commonString = edit.substring(edit.length - commonOffset); equality1 = equality1.substring(0, equality1.length - commonOffset); edit = commonString + edit.substring(0, edit.length - commonOffset); equality2 = commonString + equality2; } // Second, step character by character right, looking for the best fit. var bestEquality1 = equality1; var bestEdit = edit; var bestEquality2 = equality2; var bestScore = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); while (edit.charAt(0) === equality2.charAt(0)) { equality1 += edit.charAt(0); edit = edit.substring(1) + equality2.charAt(0); equality2 = equality2.substring(1); var score = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); // The >= encourages trailing rather than leading whitespace on edits. if (score >= bestScore) { bestScore = score; bestEquality1 = equality1; bestEdit = edit; bestEquality2 = equality2; } } if (diffs[pointer - 1][1] != bestEquality1) { // We have an improvement, save it back to the diff. if (bestEquality1) { diffs[pointer - 1][1] = bestEquality1; } else { diffs.splice(pointer - 1, 1); pointer--; } diffs[pointer][1] = bestEdit; if (bestEquality2) { diffs[pointer + 1][1] = bestEquality2; } else { diffs.splice(pointer + 1, 1); pointer--; } } } pointer++; } }; // Define some regex patterns for matching boundaries. var nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/; var whitespaceRegex_ = /\s/; var linebreakRegex_ = /[\r\n]/; var blanklineEndRegex_ = /\n\r?\n$/; var blanklineStartRegex_ = /^\r?\n\r?\n/; /** * Reorder and merge like edit sections. Merge equalities. * Any edit section can move as long as it doesn't cross an equality. * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. */ var diff_cleanupMerge = function (diffs) { // Add a dummy entry at the end. diffs.push(new Diff(DIFF_EQUAL, '')); var pointer = 0; var count_delete = 0; var count_insert = 0; var text_delete = ''; var text_insert = ''; var commonlength; while (pointer < diffs.length) { switch (diffs[pointer][0]) { case DIFF_INSERT: count_insert++; text_insert += diffs[pointer][1]; pointer++; break; case DIFF_DELETE: count_delete++; text_delete += diffs[pointer][1]; pointer++; break; case DIFF_EQUAL: // Upon reaching an equality, check for prior redundancies. if (count_delete + count_insert > 1) { if (count_delete !== 0 && count_insert !== 0) { // Factor out any common prefixies. commonlength = diff_commonPrefix(text_insert, text_delete); if (commonlength !== 0) { if ( pointer - count_delete - count_insert > 0 && diffs[pointer - count_delete - count_insert - 1][0] == DIFF_EQUAL ) { diffs[pointer - count_delete - count_insert - 1][1] += text_insert.substring(0, commonlength); } else { diffs.splice( 0, 0, new Diff(DIFF_EQUAL, text_insert.substring(0, commonlength)) ); pointer++; } text_insert = text_insert.substring(commonlength); text_delete = text_delete.substring(commonlength); } // Factor out any common suffixies. commonlength = diff_commonSuffix(text_insert, text_delete); if (commonlength !== 0) { diffs[pointer][1] = text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1]; text_insert = text_insert.substring( 0, text_insert.length - commonlength ); text_delete = text_delete.substring( 0, text_delete.length - commonlength ); } } // Delete the offending records and add the merged ones. pointer -= count_delete + count_insert; diffs.splice(pointer, count_delete + count_insert); if (text_delete.length) { diffs.splice(pointer, 0, new Diff(DIFF_DELETE, text_delete)); pointer++; } if (text_insert.length) { diffs.splice(pointer, 0, new Diff(DIFF_INSERT, text_insert)); pointer++; } pointer++; } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) { // Merge this equality with the previous one. diffs[pointer - 1][1] += diffs[pointer][1]; diffs.splice(pointer, 1); } else { pointer++; } count_insert = 0; count_delete = 0; text_delete = ''; text_insert = ''; break; } } if (diffs[diffs.length - 1][1] === '') { diffs.pop(); // Remove the dummy entry at the end. } // Second pass: look for single edits surrounded on both sides by equalities // which can be shifted sideways to eliminate an equality. // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC var changes = false; pointer = 1; // Intentionally ignore the first and last element (don't need checking). while (pointer < diffs.length - 1) { if ( diffs[pointer - 1][0] == DIFF_EQUAL && diffs[pointer + 1][0] == DIFF_EQUAL ) { // This is a single edit surrounded by equalities. if ( diffs[pointer][1].substring( diffs[pointer][1].length - diffs[pointer - 1][1].length ) == diffs[pointer - 1][1] ) { // Shift the edit over the previous equality. diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring( 0, diffs[pointer][1].length - diffs[pointer - 1][1].length ); diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; diffs.splice(pointer - 1, 1); changes = true; } else if ( diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) == diffs[pointer + 1][1] ) { // Shift the edit over the next equality. diffs[pointer - 1][1] += diffs[pointer + 1][1]; diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1]; diffs.splice(pointer + 1, 1); changes = true; } } pointer++; } // If shifts were made, the diff needs reordering and another shift sweep. if (changes) { diff_cleanupMerge(diffs); } }; build/diffLines.js 0000755 00000013364 15076543704 0010131 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.printDiffLines = exports.diffLinesUnified2 = exports.diffLinesUnified = exports.diffLinesRaw = void 0; var _diffSequences = _interopRequireDefault(require('diff-sequences')); var _cleanupSemantic = require('./cleanupSemantic'); var _joinAlignedDiffs = require('./joinAlignedDiffs'); var _normalizeDiffOptions = require('./normalizeDiffOptions'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : {default: obj}; } /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const isEmptyString = lines => lines.length === 1 && lines[0].length === 0; const countChanges = diffs => { let a = 0; let b = 0; diffs.forEach(diff => { switch (diff[0]) { case _cleanupSemantic.DIFF_DELETE: a += 1; break; case _cleanupSemantic.DIFF_INSERT: b += 1; break; } }); return { a, b }; }; const printAnnotation = ( { aAnnotation, aColor, aIndicator, bAnnotation, bColor, bIndicator, includeChangeCounts, omitAnnotationLines }, changeCounts ) => { if (omitAnnotationLines) { return ''; } let aRest = ''; let bRest = ''; if (includeChangeCounts) { const aCount = String(changeCounts.a); const bCount = String(changeCounts.b); // Padding right aligns the ends of the annotations. const baAnnotationLengthDiff = bAnnotation.length - aAnnotation.length; const aAnnotationPadding = ' '.repeat(Math.max(0, baAnnotationLengthDiff)); const bAnnotationPadding = ' '.repeat(Math.max(0, -baAnnotationLengthDiff)); // Padding left aligns the ends of the counts. const baCountLengthDiff = bCount.length - aCount.length; const aCountPadding = ' '.repeat(Math.max(0, baCountLengthDiff)); const bCountPadding = ' '.repeat(Math.max(0, -baCountLengthDiff)); aRest = aAnnotationPadding + ' ' + aIndicator + ' ' + aCountPadding + aCount; bRest = bAnnotationPadding + ' ' + bIndicator + ' ' + bCountPadding + bCount; } return ( aColor(aIndicator + ' ' + aAnnotation + aRest) + '\n' + bColor(bIndicator + ' ' + bAnnotation + bRest) + '\n\n' ); }; const printDiffLines = (diffs, options) => printAnnotation(options, countChanges(diffs)) + (options.expand ? (0, _joinAlignedDiffs.joinAlignedDiffsExpand)(diffs, options) : (0, _joinAlignedDiffs.joinAlignedDiffsNoExpand)(diffs, options)); // Compare two arrays of strings line-by-line. Format as comparison lines. exports.printDiffLines = printDiffLines; const diffLinesUnified = (aLines, bLines, options) => printDiffLines( diffLinesRaw( isEmptyString(aLines) ? [] : aLines, isEmptyString(bLines) ? [] : bLines ), (0, _normalizeDiffOptions.normalizeDiffOptions)(options) ); // Given two pairs of arrays of strings: // Compare the pair of comparison arrays line-by-line. // Format the corresponding lines in the pair of displayable arrays. exports.diffLinesUnified = diffLinesUnified; const diffLinesUnified2 = ( aLinesDisplay, bLinesDisplay, aLinesCompare, bLinesCompare, options ) => { if (isEmptyString(aLinesDisplay) && isEmptyString(aLinesCompare)) { aLinesDisplay = []; aLinesCompare = []; } if (isEmptyString(bLinesDisplay) && isEmptyString(bLinesCompare)) { bLinesDisplay = []; bLinesCompare = []; } if ( aLinesDisplay.length !== aLinesCompare.length || bLinesDisplay.length !== bLinesCompare.length ) { // Fall back to diff of display lines. return diffLinesUnified(aLinesDisplay, bLinesDisplay, options); } const diffs = diffLinesRaw(aLinesCompare, bLinesCompare); // Replace comparison lines with displayable lines. let aIndex = 0; let bIndex = 0; diffs.forEach(diff => { switch (diff[0]) { case _cleanupSemantic.DIFF_DELETE: diff[1] = aLinesDisplay[aIndex]; aIndex += 1; break; case _cleanupSemantic.DIFF_INSERT: diff[1] = bLinesDisplay[bIndex]; bIndex += 1; break; default: diff[1] = bLinesDisplay[bIndex]; aIndex += 1; bIndex += 1; } }); return printDiffLines( diffs, (0, _normalizeDiffOptions.normalizeDiffOptions)(options) ); }; // Compare two arrays of strings line-by-line. exports.diffLinesUnified2 = diffLinesUnified2; const diffLinesRaw = (aLines, bLines) => { const aLength = aLines.length; const bLength = bLines.length; const isCommon = (aIndex, bIndex) => aLines[aIndex] === bLines[bIndex]; const diffs = []; let aIndex = 0; let bIndex = 0; const foundSubsequence = (nCommon, aCommon, bCommon) => { for (; aIndex !== aCommon; aIndex += 1) { diffs.push( new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_DELETE, aLines[aIndex]) ); } for (; bIndex !== bCommon; bIndex += 1) { diffs.push( new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_INSERT, bLines[bIndex]) ); } for (; nCommon !== 0; nCommon -= 1, aIndex += 1, bIndex += 1) { diffs.push( new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_EQUAL, bLines[bIndex]) ); } }; (0, _diffSequences.default)(aLength, bLength, isCommon, foundSubsequence); // After the last common subsequence, push remaining change items. for (; aIndex !== aLength; aIndex += 1) { diffs.push( new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_DELETE, aLines[aIndex]) ); } for (; bIndex !== bLength; bIndex += 1) { diffs.push( new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_INSERT, bLines[bIndex]) ); } return diffs; }; exports.diffLinesRaw = diffLinesRaw; build/joinAlignedDiffs.d.ts 0000755 00000001016 15076543704 0011650 0 ustar 00 /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { Diff } from './cleanupSemantic'; import type { DiffOptionsNormalized } from './types'; export declare const joinAlignedDiffsNoExpand: (diffs: Array<Diff>, options: DiffOptionsNormalized) => string; export declare const joinAlignedDiffsExpand: (diffs: Array<Diff>, options: DiffOptionsNormalized) => string; build/joinAlignedDiffs.js 0000755 00000017227 15076543704 0011427 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.joinAlignedDiffsNoExpand = exports.joinAlignedDiffsExpand = void 0; var _cleanupSemantic = require('./cleanupSemantic'); /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const formatTrailingSpaces = (line, trailingSpaceFormatter) => line.replace(/\s+$/, match => trailingSpaceFormatter(match)); const printDiffLine = ( line, isFirstOrLast, color, indicator, trailingSpaceFormatter, emptyFirstOrLastLinePlaceholder ) => line.length !== 0 ? color( indicator + ' ' + formatTrailingSpaces(line, trailingSpaceFormatter) ) : indicator !== ' ' ? color(indicator) : isFirstOrLast && emptyFirstOrLastLinePlaceholder.length !== 0 ? color(indicator + ' ' + emptyFirstOrLastLinePlaceholder) : ''; const printDeleteLine = ( line, isFirstOrLast, { aColor, aIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder } ) => printDiffLine( line, isFirstOrLast, aColor, aIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder ); const printInsertLine = ( line, isFirstOrLast, { bColor, bIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder } ) => printDiffLine( line, isFirstOrLast, bColor, bIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder ); const printCommonLine = ( line, isFirstOrLast, { commonColor, commonIndicator, commonLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder } ) => printDiffLine( line, isFirstOrLast, commonColor, commonIndicator, commonLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder ); // In GNU diff format, indexes are one-based instead of zero-based. const createPatchMark = (aStart, aEnd, bStart, bEnd, {patchColor}) => patchColor( `@@ -${aStart + 1},${aEnd - aStart} +${bStart + 1},${bEnd - bStart} @@` ); // jest --no-expand // // Given array of aligned strings with inverse highlight formatting, // return joined lines with diff formatting (and patch marks, if needed). const joinAlignedDiffsNoExpand = (diffs, options) => { const iLength = diffs.length; const nContextLines = options.contextLines; const nContextLines2 = nContextLines + nContextLines; // First pass: count output lines and see if it has patches. let jLength = iLength; let hasExcessAtStartOrEnd = false; let nExcessesBetweenChanges = 0; let i = 0; while (i !== iLength) { const iStart = i; while (i !== iLength && diffs[i][0] === _cleanupSemantic.DIFF_EQUAL) { i += 1; } if (iStart !== i) { if (iStart === 0) { // at start if (i > nContextLines) { jLength -= i - nContextLines; // subtract excess common lines hasExcessAtStartOrEnd = true; } } else if (i === iLength) { // at end const n = i - iStart; if (n > nContextLines) { jLength -= n - nContextLines; // subtract excess common lines hasExcessAtStartOrEnd = true; } } else { // between changes const n = i - iStart; if (n > nContextLines2) { jLength -= n - nContextLines2; // subtract excess common lines nExcessesBetweenChanges += 1; } } } while (i !== iLength && diffs[i][0] !== _cleanupSemantic.DIFF_EQUAL) { i += 1; } } const hasPatch = nExcessesBetweenChanges !== 0 || hasExcessAtStartOrEnd; if (nExcessesBetweenChanges !== 0) { jLength += nExcessesBetweenChanges + 1; // add patch lines } else if (hasExcessAtStartOrEnd) { jLength += 1; // add patch line } const jLast = jLength - 1; const lines = []; let jPatchMark = 0; // index of placeholder line for current patch mark if (hasPatch) { lines.push(''); // placeholder line for first patch mark } // Indexes of expected or received lines in current patch: let aStart = 0; let bStart = 0; let aEnd = 0; let bEnd = 0; const pushCommonLine = line => { const j = lines.length; lines.push(printCommonLine(line, j === 0 || j === jLast, options)); aEnd += 1; bEnd += 1; }; const pushDeleteLine = line => { const j = lines.length; lines.push(printDeleteLine(line, j === 0 || j === jLast, options)); aEnd += 1; }; const pushInsertLine = line => { const j = lines.length; lines.push(printInsertLine(line, j === 0 || j === jLast, options)); bEnd += 1; }; // Second pass: push lines with diff formatting (and patch marks, if needed). i = 0; while (i !== iLength) { let iStart = i; while (i !== iLength && diffs[i][0] === _cleanupSemantic.DIFF_EQUAL) { i += 1; } if (iStart !== i) { if (iStart === 0) { // at beginning if (i > nContextLines) { iStart = i - nContextLines; aStart = iStart; bStart = iStart; aEnd = aStart; bEnd = bStart; } for (let iCommon = iStart; iCommon !== i; iCommon += 1) { pushCommonLine(diffs[iCommon][1]); } } else if (i === iLength) { // at end const iEnd = i - iStart > nContextLines ? iStart + nContextLines : i; for (let iCommon = iStart; iCommon !== iEnd; iCommon += 1) { pushCommonLine(diffs[iCommon][1]); } } else { // between changes const nCommon = i - iStart; if (nCommon > nContextLines2) { const iEnd = iStart + nContextLines; for (let iCommon = iStart; iCommon !== iEnd; iCommon += 1) { pushCommonLine(diffs[iCommon][1]); } lines[jPatchMark] = createPatchMark( aStart, aEnd, bStart, bEnd, options ); jPatchMark = lines.length; lines.push(''); // placeholder line for next patch mark const nOmit = nCommon - nContextLines2; aStart = aEnd + nOmit; bStart = bEnd + nOmit; aEnd = aStart; bEnd = bStart; for (let iCommon = i - nContextLines; iCommon !== i; iCommon += 1) { pushCommonLine(diffs[iCommon][1]); } } else { for (let iCommon = iStart; iCommon !== i; iCommon += 1) { pushCommonLine(diffs[iCommon][1]); } } } } while (i !== iLength && diffs[i][0] === _cleanupSemantic.DIFF_DELETE) { pushDeleteLine(diffs[i][1]); i += 1; } while (i !== iLength && diffs[i][0] === _cleanupSemantic.DIFF_INSERT) { pushInsertLine(diffs[i][1]); i += 1; } } if (hasPatch) { lines[jPatchMark] = createPatchMark(aStart, aEnd, bStart, bEnd, options); } return lines.join('\n'); }; // jest --expand // // Given array of aligned strings with inverse highlight formatting, // return joined lines with diff formatting. exports.joinAlignedDiffsNoExpand = joinAlignedDiffsNoExpand; const joinAlignedDiffsExpand = (diffs, options) => diffs .map((diff, i, diffs) => { const line = diff[1]; const isFirstOrLast = i === 0 || i === diffs.length - 1; switch (diff[0]) { case _cleanupSemantic.DIFF_DELETE: return printDeleteLine(line, isFirstOrLast, options); case _cleanupSemantic.DIFF_INSERT: return printInsertLine(line, isFirstOrLast, options); default: return printCommonLine(line, isFirstOrLast, options); } }) .join('\n'); exports.joinAlignedDiffsExpand = joinAlignedDiffsExpand; build/normalizeDiffOptions.d.ts 0000755 00000000654 15076543704 0012625 0 ustar 00 /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import type { DiffOptions, DiffOptionsNormalized } from './types'; export declare const noColor: (string: string) => string; export declare const normalizeDiffOptions: (options?: DiffOptions) => DiffOptionsNormalized; build/types.d.ts 0000755 00000003100 15076543704 0007611 0 ustar 00 /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import type { CompareKeys } from 'pretty-format'; export declare type DiffOptionsColor = (arg: string) => string; export declare type DiffOptions = { aAnnotation?: string; aColor?: DiffOptionsColor; aIndicator?: string; bAnnotation?: string; bColor?: DiffOptionsColor; bIndicator?: string; changeColor?: DiffOptionsColor; changeLineTrailingSpaceColor?: DiffOptionsColor; commonColor?: DiffOptionsColor; commonIndicator?: string; commonLineTrailingSpaceColor?: DiffOptionsColor; contextLines?: number; emptyFirstOrLastLinePlaceholder?: string; expand?: boolean; includeChangeCounts?: boolean; omitAnnotationLines?: boolean; patchColor?: DiffOptionsColor; compareKeys?: CompareKeys; }; export declare type DiffOptionsNormalized = { aAnnotation: string; aColor: DiffOptionsColor; aIndicator: string; bAnnotation: string; bColor: DiffOptionsColor; bIndicator: string; changeColor: DiffOptionsColor; changeLineTrailingSpaceColor: DiffOptionsColor; commonColor: DiffOptionsColor; commonIndicator: string; commonLineTrailingSpaceColor: DiffOptionsColor; compareKeys: CompareKeys; contextLines: number; emptyFirstOrLastLinePlaceholder: string; expand: boolean; includeChangeCounts: boolean; omitAnnotationLines: boolean; patchColor: DiffOptionsColor; }; build/index.js 0000755 00000015533 15076543704 0007335 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); Object.defineProperty(exports, 'DIFF_DELETE', { enumerable: true, get: function () { return _cleanupSemantic.DIFF_DELETE; } }); Object.defineProperty(exports, 'DIFF_EQUAL', { enumerable: true, get: function () { return _cleanupSemantic.DIFF_EQUAL; } }); Object.defineProperty(exports, 'DIFF_INSERT', { enumerable: true, get: function () { return _cleanupSemantic.DIFF_INSERT; } }); Object.defineProperty(exports, 'Diff', { enumerable: true, get: function () { return _cleanupSemantic.Diff; } }); exports.diff = diff; Object.defineProperty(exports, 'diffLinesRaw', { enumerable: true, get: function () { return _diffLines.diffLinesRaw; } }); Object.defineProperty(exports, 'diffLinesUnified', { enumerable: true, get: function () { return _diffLines.diffLinesUnified; } }); Object.defineProperty(exports, 'diffLinesUnified2', { enumerable: true, get: function () { return _diffLines.diffLinesUnified2; } }); Object.defineProperty(exports, 'diffStringsRaw', { enumerable: true, get: function () { return _printDiffs.diffStringsRaw; } }); Object.defineProperty(exports, 'diffStringsUnified', { enumerable: true, get: function () { return _printDiffs.diffStringsUnified; } }); var _chalk = _interopRequireDefault(require('chalk')); var _jestGetType = require('jest-get-type'); var _prettyFormat = require('pretty-format'); var _cleanupSemantic = require('./cleanupSemantic'); var _constants = require('./constants'); var _diffLines = require('./diffLines'); var _normalizeDiffOptions = require('./normalizeDiffOptions'); var _printDiffs = require('./printDiffs'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : {default: obj}; } var global = (function () { if (typeof globalThis !== 'undefined') { return globalThis; } else if (typeof global !== 'undefined') { return global; } else if (typeof self !== 'undefined') { return self; } else if (typeof window !== 'undefined') { return window; } else { return Function('return this')(); } })(); var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol; const getCommonMessage = (message, options) => { const {commonColor} = (0, _normalizeDiffOptions.normalizeDiffOptions)( options ); return commonColor(message); }; const { AsymmetricMatcher, DOMCollection, DOMElement, Immutable, ReactElement, ReactTestComponent } = _prettyFormat.plugins; const PLUGINS = [ ReactTestComponent, ReactElement, DOMElement, DOMCollection, Immutable, AsymmetricMatcher ]; const FORMAT_OPTIONS = { plugins: PLUGINS }; const FALLBACK_FORMAT_OPTIONS = { callToJSON: false, maxDepth: 10, plugins: PLUGINS }; // Generate a string that will highlight the difference between two values // with green and red. (similar to how github does code diffing) // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types function diff(a, b, options) { if (Object.is(a, b)) { return getCommonMessage(_constants.NO_DIFF_MESSAGE, options); } const aType = (0, _jestGetType.getType)(a); let expectedType = aType; let omitDifference = false; if (aType === 'object' && typeof a.asymmetricMatch === 'function') { if (a.$$typeof !== Symbol.for('jest.asymmetricMatcher')) { // Do not know expected type of user-defined asymmetric matcher. return null; } if (typeof a.getExpectedType !== 'function') { // For example, expect.anything() matches either null or undefined return null; } expectedType = a.getExpectedType(); // Primitive types boolean and number omit difference below. // For example, omit difference for expect.stringMatching(regexp) omitDifference = expectedType === 'string'; } if (expectedType !== (0, _jestGetType.getType)(b)) { return ( ' Comparing two different types of values.' + ` Expected ${_chalk.default.green(expectedType)} but ` + `received ${_chalk.default.red((0, _jestGetType.getType)(b))}.` ); } if (omitDifference) { return null; } switch (aType) { case 'string': return (0, _diffLines.diffLinesUnified)( a.split('\n'), b.split('\n'), options ); case 'boolean': case 'number': return comparePrimitive(a, b, options); case 'map': return compareObjects(sortMap(a), sortMap(b), options); case 'set': return compareObjects(sortSet(a), sortSet(b), options); default: return compareObjects(a, b, options); } } function comparePrimitive(a, b, options) { const aFormat = (0, _prettyFormat.format)(a, FORMAT_OPTIONS); const bFormat = (0, _prettyFormat.format)(b, FORMAT_OPTIONS); return aFormat === bFormat ? getCommonMessage(_constants.NO_DIFF_MESSAGE, options) : (0, _diffLines.diffLinesUnified)( aFormat.split('\n'), bFormat.split('\n'), options ); } function sortMap(map) { return new Map(Array.from(map.entries()).sort()); } function sortSet(set) { return new Set(Array.from(set.values()).sort()); } function compareObjects(a, b, options) { let difference; let hasThrown = false; try { const formatOptions = getFormatOptions(FORMAT_OPTIONS, options); difference = getObjectsDifference(a, b, formatOptions, options); } catch { hasThrown = true; } const noDiffMessage = getCommonMessage(_constants.NO_DIFF_MESSAGE, options); // If the comparison yields no results, compare again but this time // without calling `toJSON`. It's also possible that toJSON might throw. if (difference === undefined || difference === noDiffMessage) { const formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options); difference = getObjectsDifference(a, b, formatOptions, options); if (difference !== noDiffMessage && !hasThrown) { difference = getCommonMessage(_constants.SIMILAR_MESSAGE, options) + '\n\n' + difference; } } return difference; } function getFormatOptions(formatOptions, options) { const {compareKeys} = (0, _normalizeDiffOptions.normalizeDiffOptions)( options ); return {...formatOptions, compareKeys}; } function getObjectsDifference(a, b, formatOptions, options) { const formatOptionsZeroIndent = {...formatOptions, indent: 0}; const aCompare = (0, _prettyFormat.format)(a, formatOptionsZeroIndent); const bCompare = (0, _prettyFormat.format)(b, formatOptionsZeroIndent); if (aCompare === bCompare) { return getCommonMessage(_constants.NO_DIFF_MESSAGE, options); } else { const aDisplay = (0, _prettyFormat.format)(a, formatOptions); const bDisplay = (0, _prettyFormat.format)(b, formatOptions); return (0, _diffLines.diffLinesUnified2)( aDisplay.split('\n'), bDisplay.split('\n'), aCompare.split('\n'), bCompare.split('\n'), options ); } } node_modules/pretty-format/README.md 0000755 00000033723 15077334362 0013342 0 ustar 00 # pretty-format Stringify any JavaScript value. - Serialize built-in JavaScript types. - Serialize application-specific data types with built-in or user-defined plugins. ## Installation ```sh $ yarn add pretty-format ``` ## Usage ```js const {format: prettyFormat} = require('pretty-format'); // CommonJS ``` ```js import {format as prettyFormat} from 'pretty-format'; // ES2015 modules ``` ```js const val = {object: {}}; val.circularReference = val; val[Symbol('foo')] = 'foo'; val.map = new Map([['prop', 'value']]); val.array = [-0, Infinity, NaN]; console.log(prettyFormat(val)); /* Object { "array": Array [ -0, Infinity, NaN, ], "circularReference": [Circular], "map": Map { "prop" => "value", }, "object": Object {}, Symbol(foo): "foo", } */ ``` ## Usage with options ```js function onClick() {} console.log(prettyFormat(onClick)); /* [Function onClick] */ const options = { printFunctionName: false, }; console.log(prettyFormat(onClick, options)); /* [Function] */ ``` <!-- prettier-ignore --> | key | type | default | description | | :-------------------- | :--------------- | :---------- | :-------------------------------------------------------------------------------------- | | `callToJSON` | `boolean` | `true` | call `toJSON` method (if it exists) on objects | | `compareKeys` | `function\|null` | `undefined` | compare function used when sorting object keys, `null` can be used to skip over sorting | | `escapeRegex` | `boolean` | `false` | escape special characters in regular expressions | | `escapeString` | `boolean` | `true` | escape special characters in strings | | `highlight` | `boolean` | `false` | highlight syntax with colors in terminal (some plugins) | | `indent` | `number` | `2` | spaces in each level of indentation | | `maxDepth` | `number` | `Infinity` | levels to print in arrays, objects, elements, and so on | | `maxWidth` | `number` | `Infinity` | number of elements to print in arrays, sets, and so on | | `min` | `boolean` | `false` | minimize added space: no indentation nor line breaks | | `plugins` | `array` | `[]` | plugins to serialize application-specific data types | | `printBasicPrototype` | `boolean` | `false` | print the prototype for plain objects and arrays | | `printFunctionName` | `boolean` | `true` | include or omit the name of a function | | `theme` | `object` | | colors to highlight syntax in terminal | Property values of `theme` are from [ansi-styles colors](https://github.com/chalk/ansi-styles#colors) ```js const DEFAULT_THEME = { comment: 'gray', content: 'reset', prop: 'yellow', tag: 'cyan', value: 'green', }; ``` ## Usage with plugins The `pretty-format` package provides some built-in plugins, including: - `ReactElement` for elements from `react` - `ReactTestComponent` for test objects from `react-test-renderer` ```js // CommonJS const React = require('react'); const renderer = require('react-test-renderer'); const {format: prettyFormat, plugins} = require('pretty-format'); const {ReactElement, ReactTestComponent} = plugins; ``` ```js // ES2015 modules and destructuring assignment import React from 'react'; import renderer from 'react-test-renderer'; import {plugins, format as prettyFormat} from 'pretty-format'; const {ReactElement, ReactTestComponent} = plugins; ``` ```js const onClick = () => {}; const element = React.createElement('button', {onClick}, 'Hello World'); const formatted1 = prettyFormat(element, { plugins: [ReactElement], printFunctionName: false, }); const formatted2 = prettyFormat(renderer.create(element).toJSON(), { plugins: [ReactTestComponent], printFunctionName: false, }); /* <button onClick=[Function] > Hello World </button> */ ``` ## Usage in Jest For snapshot tests, Jest uses `pretty-format` with options that include some of its built-in plugins. For this purpose, plugins are also known as **snapshot serializers**. To serialize application-specific data types, you can add modules to `devDependencies` of a project, and then: In an **individual** test file, you can add a module as follows. It precedes any modules from Jest configuration. ```js import serializer from 'my-serializer-module'; expect.addSnapshotSerializer(serializer); // tests which have `expect(value).toMatchSnapshot()` assertions ``` For **all** test files, you can specify modules in Jest configuration. They precede built-in plugins for React, HTML, and Immutable.js data types. For example, in a `package.json` file: ```json { "jest": { "snapshotSerializers": ["my-serializer-module"] } } ``` ## Writing plugins A plugin is a JavaScript object. If `options` has a `plugins` array: for the first plugin whose `test(val)` method returns a truthy value, then `prettyFormat(val, options)` returns the result from either: - `serialize(val, …)` method of the **improved** interface (available in **version 21** or later) - `print(val, …)` method of the **original** interface (if plugin does not have `serialize` method) ### test Write `test` so it can receive `val` argument of any type. To serialize **objects** which have certain properties, then a guarded expression like `val != null && …` or more concise `val && …` prevents the following errors: - `TypeError: Cannot read property 'whatever' of null` - `TypeError: Cannot read property 'whatever' of undefined` For example, `test` method of built-in `ReactElement` plugin: ```js const elementSymbol = Symbol.for('react.element'); const test = val => val && val.$$typeof === elementSymbol; ``` Pay attention to efficiency in `test` because `pretty-format` calls it often. ### serialize The **improved** interface is available in **version 21** or later. Write `serialize` to return a string, given the arguments: - `val` which “passed the test” - unchanging `config` object: derived from `options` - current `indentation` string: concatenate to `indent` from `config` - current `depth` number: compare to `maxDepth` from `config` - current `refs` array: find circular references in objects - `printer` callback function: serialize children ### config <!-- prettier-ignore --> | key | type | description | | :------------------ | :--------------- | :-------------------------------------------------------------------------------------- | | `callToJSON` | `boolean` | call `toJSON` method (if it exists) on objects | | `compareKeys` | `function\|null` | compare function used when sorting object keys, `null` can be used to skip over sorting | | `colors` | `Object` | escape codes for colors to highlight syntax | | `escapeRegex` | `boolean` | escape special characters in regular expressions | | `escapeString` | `boolean` | escape special characters in strings | | `indent` | `string` | spaces in each level of indentation | | `maxDepth` | `number` | levels to print in arrays, objects, elements, and so on | | `min` | `boolean` | minimize added space: no indentation nor line breaks | | `plugins` | `array` | plugins to serialize application-specific data types | | `printFunctionName` | `boolean` | include or omit the name of a function | | `spacingInner` | `string` | spacing to separate items in a list | | `spacingOuter` | `string` | spacing to enclose a list of items | Each property of `colors` in `config` corresponds to a property of `theme` in `options`: - the key is the same (for example, `tag`) - the value in `colors` is a object with `open` and `close` properties whose values are escape codes from [ansi-styles](https://github.com/chalk/ansi-styles) for the color value in `theme` (for example, `'cyan'`) Some properties in `config` are derived from `min` in `options`: - `spacingInner` and `spacingOuter` are **newline** if `min` is `false` - `spacingInner` is **space** and `spacingOuter` is **empty string** if `min` is `true` ### Example of serialize and test This plugin is a pattern you can apply to serialize composite data types. Side note: `pretty-format` does not need a plugin to serialize arrays. ```js // We reused more code when we factored out a function for child items // that is independent of depth, name, and enclosing punctuation (see below). const SEPARATOR = ','; function serializeItems(items, config, indentation, depth, refs, printer) { if (items.length === 0) { return ''; } const indentationItems = indentation + config.indent; return ( config.spacingOuter + items .map( item => indentationItems + printer(item, config, indentationItems, depth, refs), // callback ) .join(SEPARATOR + config.spacingInner) + (config.min ? '' : SEPARATOR) + // following the last item config.spacingOuter + indentation ); } const plugin = { test(val) { return Array.isArray(val); }, serialize(array, config, indentation, depth, refs, printer) { const name = array.constructor.name; return ++depth > config.maxDepth ? `[${name}]` : `${config.min ? '' : `${name} `}[${serializeItems( array, config, indentation, depth, refs, printer, )}]`; }, }; ``` ```js const val = { filter: 'completed', items: [ { text: 'Write test', completed: true, }, { text: 'Write serialize', completed: true, }, ], }; ``` ```js console.log( prettyFormat(val, { plugins: [plugin], }), ); /* Object { "filter": "completed", "items": Array [ Object { "completed": true, "text": "Write test", }, Object { "completed": true, "text": "Write serialize", }, ], } */ ``` ```js console.log( prettyFormat(val, { indent: 4, plugins: [plugin], }), ); /* Object { "filter": "completed", "items": Array [ Object { "completed": true, "text": "Write test", }, Object { "completed": true, "text": "Write serialize", }, ], } */ ``` ```js console.log( prettyFormat(val, { maxDepth: 1, plugins: [plugin], }), ); /* Object { "filter": "completed", "items": [Array], } */ ``` ```js console.log( prettyFormat(val, { min: true, plugins: [plugin], }), ); /* {"filter": "completed", "items": [{"completed": true, "text": "Write test"}, {"completed": true, "text": "Write serialize"}]} */ ``` ### print The **original** interface is adequate for plugins: - that **do not** depend on options other than `highlight` or `min` - that **do not** depend on `depth` or `refs` in recursive traversal, and - if values either - do **not** require indentation, or - do **not** occur as children of JavaScript data structures (for example, array) Write `print` to return a string, given the arguments: - `val` which “passed the test” - current `printer(valChild)` callback function: serialize children - current `indenter(lines)` callback function: indent lines at the next level - unchanging `config` object: derived from `options` - unchanging `colors` object: derived from `options` The 3 properties of `config` are `min` in `options` and: - `spacing` and `edgeSpacing` are **newline** if `min` is `false` - `spacing` is **space** and `edgeSpacing` is **empty string** if `min` is `true` Each property of `colors` corresponds to a property of `theme` in `options`: - the key is the same (for example, `tag`) - the value in `colors` is a object with `open` and `close` properties whose values are escape codes from [ansi-styles](https://github.com/chalk/ansi-styles) for the color value in `theme` (for example, `'cyan'`) ### Example of print and test This plugin prints functions with the **number of named arguments** excluding rest argument. ```js const plugin = { print(val) { return `[Function ${val.name || 'anonymous'} ${val.length}]`; }, test(val) { return typeof val === 'function'; }, }; ``` ```js const val = { onClick(event) {}, render() {}, }; prettyFormat(val, { plugins: [plugin], }); /* Object { "onClick": [Function onClick 1], "render": [Function render 0], } */ prettyFormat(val); /* Object { "onClick": [Function onClick], "render": [Function render], } */ ``` This plugin **ignores** the `printFunctionName` option. That limitation of the original `print` interface is a reason to use the improved `serialize` interface, described above. ```js prettyFormat(val, { plugins: [pluginOld], printFunctionName: false, }); /* Object { "onClick": [Function onClick 1], "render": [Function render 0], } */ prettyFormat(val, { printFunctionName: false, }); /* Object { "onClick": [Function], "render": [Function], } */ ``` node_modules/pretty-format/LICENSE 0000755 00000002100 15077334362 0013051 0 ustar 00 MIT License Copyright (c) Meta Platforms, Inc. and affiliates. 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. node_modules/pretty-format/package.json 0000755 00000002073 15077334362 0014343 0 ustar 00 { "name": "pretty-format", "version": "29.7.0", "repository": { "type": "git", "url": "https://github.com/jestjs/jest.git", "directory": "packages/pretty-format" }, "license": "MIT", "description": "Stringify any JavaScript value.", "main": "./build/index.js", "types": "./build/index.d.ts", "exports": { ".": { "types": "./build/index.d.ts", "default": "./build/index.js" }, "./package.json": "./package.json" }, "author": "James Kyle <me@thejameskyle.com>", "dependencies": { "@jest/schemas": "^29.6.3", "ansi-styles": "^5.0.0", "react-is": "^18.0.0" }, "devDependencies": { "@types/react": "^17.0.3", "@types/react-is": "^18.0.0", "@types/react-test-renderer": "17.0.2", "immutable": "^4.0.0", "jest-util": "^29.7.0", "react": "17.0.2", "react-dom": "^17.0.1", "react-test-renderer": "17.0.2" }, "engines": { "node": "^14.15.0 || ^16.10.0 || >=18.0.0" }, "publishConfig": { "access": "public" }, "gitHead": "4e56991693da7cd4c3730dc3579a1dd1403ee630" } node_modules/pretty-format/node_modules/ansi-styles/license 0000755 00000002125 15077334362 0020350 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/pretty-format/node_modules/ansi-styles/readme.md 0000755 00000007641 15077334362 0020572 0 ustar 00 # ansi-styles > [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings. <img src="screenshot.svg" width="900"> ## Install ``` $ npm install ansi-styles ``` ## Usage ```js const style = require('ansi-styles'); console.log(`${style.green.open}Hello world!${style.green.close}`); // Color conversion between 256/truecolor // NOTE: When converting from truecolor to 256 colors, the original color // may be degraded to fit the new color palette. This means terminals // that do not support 16 million colors will best-match the // original color. console.log(`${style.color.ansi256(style.rgbToAnsi256(199, 20, 250))}Hello World${style.color.close}`) console.log(`${style.color.ansi16m(...style.hexToRgb('#abcdef'))}Hello World${style.color.close}`) ``` ## API Each style has an `open` and `close` property. ## Styles ### Modifiers - `reset` - `bold` - `dim` - `italic` *(Not widely supported)* - `underline` - `overline` *Supported on VTE-based terminals, the GNOME terminal, mintty, and Git Bash.* - `inverse` - `hidden` - `strikethrough` *(Not widely supported)* ### Colors - `black` - `red` - `green` - `yellow` - `blue` - `magenta` - `cyan` - `white` - `blackBright` (alias: `gray`, `grey`) - `redBright` - `greenBright` - `yellowBright` - `blueBright` - `magentaBright` - `cyanBright` - `whiteBright` ### Background colors - `bgBlack` - `bgRed` - `bgGreen` - `bgYellow` - `bgBlue` - `bgMagenta` - `bgCyan` - `bgWhite` - `bgBlackBright` (alias: `bgGray`, `bgGrey`) - `bgRedBright` - `bgGreenBright` - `bgYellowBright` - `bgBlueBright` - `bgMagentaBright` - `bgCyanBright` - `bgWhiteBright` ## Advanced usage By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. - `style.modifier` - `style.color` - `style.bgColor` ###### Example ```js console.log(style.color.green.open); ``` Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `style.codes`, which returns a `Map` with the open codes as keys and close codes as values. ###### Example ```js console.log(style.codes.get(36)); //=> 39 ``` ## [256 / 16 million (TrueColor) support](https://gist.github.com/XVilka/8346728) `ansi-styles` allows converting between various color formats and ANSI escapes, with support for 256 and 16 million colors. The following color spaces from `color-convert` are supported: - `rgb` - `hex` - `ansi256` To use these, call the associated conversion function with the intended output, for example: ```js style.color.ansi256(style.rgbToAnsi256(100, 200, 15)); // RGB to 256 color ansi foreground code style.bgColor.ansi256(style.hexToAnsi256('#C0FFEE')); // HEX to 256 color ansi foreground code style.color.ansi16m(100, 200, 15); // RGB to 16 million color foreground code style.bgColor.ansi16m(...style.hexToRgb('#C0FFEE')); // Hex (RGB) to 16 million color foreground code ``` ## Related - [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal ## Maintainers - [Sindre Sorhus](https://github.com/sindresorhus) - [Josh Junon](https://github.com/qix-) ## For enterprise Available as part of the Tidelift Subscription. The maintainers of `ansi-styles` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-ansi-styles?utm_source=npm-ansi-styles&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) node_modules/pretty-format/node_modules/ansi-styles/index.d.ts 0000755 00000007033 15077334362 0020707 0 ustar 00 declare namespace ansiStyles { interface CSPair { /** The ANSI terminal control sequence for starting this style. */ readonly open: string; /** The ANSI terminal control sequence for ending this style. */ readonly close: string; } interface ColorBase { /** The ANSI terminal control sequence for ending this color. */ readonly close: string; ansi256(code: number): string; ansi16m(red: number, green: number, blue: number): string; } 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; } 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; } 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; } 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; } } declare const ansiStyles: { readonly modifier: ansiStyles.Modifier; readonly color: ansiStyles.ForegroundColor & ansiStyles.ColorBase; readonly bgColor: ansiStyles.BackgroundColor & ansiStyles.ColorBase; readonly codes: ReadonlyMap<number, number>; } & ansiStyles.BackgroundColor & ansiStyles.ForegroundColor & ansiStyles.Modifier & ansiStyles.ConvertColor; export = ansiStyles; node_modules/pretty-format/node_modules/ansi-styles/package.json 0000755 00000001720 15077334362 0021271 0 ustar 00 { "name": "ansi-styles", "version": "5.2.0", "description": "ANSI escape codes for styling strings in the terminal", "license": "MIT", "repository": "chalk/ansi-styles", "funding": "https://github.com/chalk/ansi-styles?sponsor=1", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "engines": { "node": ">=10" }, "scripts": { "test": "xo && ava && tsd", "screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "devDependencies": { "ava": "^2.4.0", "svg-term-cli": "^2.1.1", "tsd": "^0.14.0", "xo": "^0.37.1" } } node_modules/pretty-format/node_modules/ansi-styles/index.js 0000755 00000007473 15077334362 0020463 0 ustar 00 'use strict'; const ANSI_BACKGROUND_OFFSET = 10; 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`; function assembleStyles() { const codes = new Map(); 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], 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], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; // Alias bright black as gray (and grey) styles.color.gray = styles.color.blackBright; styles.bgColor.bgGray = styles.bgColor.bgBlackBright; styles.color.grey = styles.color.blackBright; styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; 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.ansi256 = wrapAnsi256(); styles.color.ansi16m = wrapAnsi16m(); 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 = /(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(hex.toString(16)); if (!matches) { return [0, 0, 0]; } let {colorString} = matches.groups; if (colorString.length === 3) { colorString = colorString.split('').map(character => character + character).join(''); } const integer = Number.parseInt(colorString, 16); return [ (integer >> 16) & 0xFF, (integer >> 8) & 0xFF, integer & 0xFF ]; }, enumerable: false }, hexToAnsi256: { value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), enumerable: false } }); return styles; } // Make the export immutable Object.defineProperty(module, 'exports', { enumerable: true, get: assembleStyles }); node_modules/pretty-format/build/plugins/DOMElement.js 0000755 00000005356 15077334362 0017133 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.test = exports.serialize = exports.default = void 0; var _markup = require('./lib/markup'); /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const ELEMENT_NODE = 1; const TEXT_NODE = 3; const COMMENT_NODE = 8; const FRAGMENT_NODE = 11; const ELEMENT_REGEXP = /^((HTML|SVG)\w*)?Element$/; const testHasAttribute = val => { try { return typeof val.hasAttribute === 'function' && val.hasAttribute('is'); } catch { return false; } }; const testNode = val => { const constructorName = val.constructor.name; const {nodeType, tagName} = val; const isCustomElement = (typeof tagName === 'string' && tagName.includes('-')) || testHasAttribute(val); return ( (nodeType === ELEMENT_NODE && (ELEMENT_REGEXP.test(constructorName) || isCustomElement)) || (nodeType === TEXT_NODE && constructorName === 'Text') || (nodeType === COMMENT_NODE && constructorName === 'Comment') || (nodeType === FRAGMENT_NODE && constructorName === 'DocumentFragment') ); }; const test = val => val?.constructor?.name && testNode(val); exports.test = test; function nodeIsText(node) { return node.nodeType === TEXT_NODE; } function nodeIsComment(node) { return node.nodeType === COMMENT_NODE; } function nodeIsFragment(node) { return node.nodeType === FRAGMENT_NODE; } const serialize = (node, config, indentation, depth, refs, printer) => { if (nodeIsText(node)) { return (0, _markup.printText)(node.data, config); } if (nodeIsComment(node)) { return (0, _markup.printComment)(node.data, config); } const type = nodeIsFragment(node) ? 'DocumentFragment' : node.tagName.toLowerCase(); if (++depth > config.maxDepth) { return (0, _markup.printElementAsLeaf)(type, config); } return (0, _markup.printElement)( type, (0, _markup.printProps)( nodeIsFragment(node) ? [] : Array.from(node.attributes, attr => attr.name).sort(), nodeIsFragment(node) ? {} : Array.from(node.attributes).reduce((props, attribute) => { props[attribute.name] = attribute.value; return props; }, {}), config, indentation + config.indent, depth, refs, printer ), (0, _markup.printChildren)( Array.prototype.slice.call(node.childNodes || node.children), config, indentation + config.indent, depth, refs, printer ), config, indentation ); }; exports.serialize = serialize; const plugin = { serialize, test }; var _default = plugin; exports.default = _default; node_modules/pretty-format/build/plugins/AsymmetricMatcher.js 0000755 00000004364 15077334362 0020621 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.test = exports.serialize = exports.default = void 0; var _collections = require('../collections'); var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const asymmetricMatcher = typeof Symbol === 'function' && Symbol.for ? Symbol.for('jest.asymmetricMatcher') : 0x1357a5; const SPACE = ' '; const serialize = (val, config, indentation, depth, refs, printer) => { const stringedValue = val.toString(); if ( stringedValue === 'ArrayContaining' || stringedValue === 'ArrayNotContaining' ) { if (++depth > config.maxDepth) { return `[${stringedValue}]`; } return `${stringedValue + SPACE}[${(0, _collections.printListItems)( val.sample, config, indentation, depth, refs, printer )}]`; } if ( stringedValue === 'ObjectContaining' || stringedValue === 'ObjectNotContaining' ) { if (++depth > config.maxDepth) { return `[${stringedValue}]`; } return `${stringedValue + SPACE}{${(0, _collections.printObjectProperties)( val.sample, config, indentation, depth, refs, printer )}}`; } if ( stringedValue === 'StringMatching' || stringedValue === 'StringNotMatching' ) { return ( stringedValue + SPACE + printer(val.sample, config, indentation, depth, refs) ); } if ( stringedValue === 'StringContaining' || stringedValue === 'StringNotContaining' ) { return ( stringedValue + SPACE + printer(val.sample, config, indentation, depth, refs) ); } if (typeof val.toAsymmetricMatcher !== 'function') { throw new Error( `Asymmetric matcher ${val.constructor.name} does not implement toAsymmetricMatcher()` ); } return val.toAsymmetricMatcher(); }; exports.serialize = serialize; const test = val => val && val.$$typeof === asymmetricMatcher; exports.test = test; const plugin = { serialize, test }; var _default = plugin; exports.default = _default; node_modules/pretty-format/build/plugins/DOMCollection.js 0000755 00000003462 15077334362 0017631 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.test = exports.serialize = exports.default = void 0; var _collections = require('../collections'); /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const SPACE = ' '; const OBJECT_NAMES = ['DOMStringMap', 'NamedNodeMap']; const ARRAY_REGEXP = /^(HTML\w*Collection|NodeList)$/; const testName = name => OBJECT_NAMES.indexOf(name) !== -1 || ARRAY_REGEXP.test(name); const test = val => val && val.constructor && !!val.constructor.name && testName(val.constructor.name); exports.test = test; const isNamedNodeMap = collection => collection.constructor.name === 'NamedNodeMap'; const serialize = (collection, config, indentation, depth, refs, printer) => { const name = collection.constructor.name; if (++depth > config.maxDepth) { return `[${name}]`; } return ( (config.min ? '' : name + SPACE) + (OBJECT_NAMES.indexOf(name) !== -1 ? `{${(0, _collections.printObjectProperties)( isNamedNodeMap(collection) ? Array.from(collection).reduce((props, attribute) => { props[attribute.name] = attribute.value; return props; }, {}) : { ...collection }, config, indentation, depth, refs, printer )}}` : `[${(0, _collections.printListItems)( Array.from(collection), config, indentation, depth, refs, printer )}]`) ); }; exports.serialize = serialize; const plugin = { serialize, test }; var _default = plugin; exports.default = _default; node_modules/pretty-format/build/plugins/ReactTestComponent.js 0000755 00000003407 15077334362 0020756 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.test = exports.serialize = exports.default = void 0; var _markup = require('./lib/markup'); var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // Child can be `number` in Stack renderer but not in Fiber renderer. const testSymbol = typeof Symbol === 'function' && Symbol.for ? Symbol.for('react.test.json') : 0xea71357; const getPropKeys = object => { const {props} = object; return props ? Object.keys(props) .filter(key => props[key] !== undefined) .sort() : []; }; const serialize = (object, config, indentation, depth, refs, printer) => ++depth > config.maxDepth ? (0, _markup.printElementAsLeaf)(object.type, config) : (0, _markup.printElement)( object.type, object.props ? (0, _markup.printProps)( getPropKeys(object), object.props, config, indentation + config.indent, depth, refs, printer ) : '', object.children ? (0, _markup.printChildren)( object.children, config, indentation + config.indent, depth, refs, printer ) : '', config, indentation ); exports.serialize = serialize; const test = val => val && val.$$typeof === testSymbol; exports.test = test; const plugin = { serialize, test }; var _default = plugin; exports.default = _default; node_modules/pretty-format/build/plugins/Immutable.js 0000755 00000012502 15077334362 0017110 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.test = exports.serialize = exports.default = void 0; var _collections = require('../collections'); /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // SENTINEL constants are from https://github.com/facebook/immutable-js const IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; const IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@'; const IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; const IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@'; const IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; const IS_RECORD_SENTINEL = '@@__IMMUTABLE_RECORD__@@'; // immutable v4 const IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@'; const IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@'; const IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@'; const getImmutableName = name => `Immutable.${name}`; const printAsLeaf = name => `[${name}]`; const SPACE = ' '; const LAZY = '…'; // Seq is lazy if it calls a method like filter const printImmutableEntries = ( val, config, indentation, depth, refs, printer, type ) => ++depth > config.maxDepth ? printAsLeaf(getImmutableName(type)) : `${getImmutableName(type) + SPACE}{${(0, _collections.printIteratorEntries)( val.entries(), config, indentation, depth, refs, printer )}}`; // Record has an entries method because it is a collection in immutable v3. // Return an iterator for Immutable Record from version v3 or v4. function getRecordEntries(val) { let i = 0; return { next() { if (i < val._keys.length) { const key = val._keys[i++]; return { done: false, value: [key, val.get(key)] }; } return { done: true, value: undefined }; } }; } const printImmutableRecord = ( val, config, indentation, depth, refs, printer ) => { // _name property is defined only for an Immutable Record instance // which was constructed with a second optional descriptive name arg const name = getImmutableName(val._name || 'Record'); return ++depth > config.maxDepth ? printAsLeaf(name) : `${name + SPACE}{${(0, _collections.printIteratorEntries)( getRecordEntries(val), config, indentation, depth, refs, printer )}}`; }; const printImmutableSeq = (val, config, indentation, depth, refs, printer) => { const name = getImmutableName('Seq'); if (++depth > config.maxDepth) { return printAsLeaf(name); } if (val[IS_KEYED_SENTINEL]) { return `${name + SPACE}{${ // from Immutable collection of entries or from ECMAScript object val._iter || val._object ? (0, _collections.printIteratorEntries)( val.entries(), config, indentation, depth, refs, printer ) : LAZY }}`; } return `${name + SPACE}[${ val._iter || // from Immutable collection of values val._array || // from ECMAScript array val._collection || // from ECMAScript collection in immutable v4 val._iterable // from ECMAScript collection in immutable v3 ? (0, _collections.printIteratorValues)( val.values(), config, indentation, depth, refs, printer ) : LAZY }]`; }; const printImmutableValues = ( val, config, indentation, depth, refs, printer, type ) => ++depth > config.maxDepth ? printAsLeaf(getImmutableName(type)) : `${getImmutableName(type) + SPACE}[${(0, _collections.printIteratorValues)( val.values(), config, indentation, depth, refs, printer )}]`; const serialize = (val, config, indentation, depth, refs, printer) => { if (val[IS_MAP_SENTINEL]) { return printImmutableEntries( val, config, indentation, depth, refs, printer, val[IS_ORDERED_SENTINEL] ? 'OrderedMap' : 'Map' ); } if (val[IS_LIST_SENTINEL]) { return printImmutableValues( val, config, indentation, depth, refs, printer, 'List' ); } if (val[IS_SET_SENTINEL]) { return printImmutableValues( val, config, indentation, depth, refs, printer, val[IS_ORDERED_SENTINEL] ? 'OrderedSet' : 'Set' ); } if (val[IS_STACK_SENTINEL]) { return printImmutableValues( val, config, indentation, depth, refs, printer, 'Stack' ); } if (val[IS_SEQ_SENTINEL]) { return printImmutableSeq(val, config, indentation, depth, refs, printer); } // For compatibility with immutable v3 and v4, let record be the default. return printImmutableRecord(val, config, indentation, depth, refs, printer); }; // Explicitly comparing sentinel properties to true avoids false positive // when mock identity-obj-proxy returns the key as the value for any key. exports.serialize = serialize; const test = val => val && (val[IS_ITERABLE_SENTINEL] === true || val[IS_RECORD_SENTINEL] === true); exports.test = test; const plugin = { serialize, test }; var _default = plugin; exports.default = _default; node_modules/pretty-format/build/plugins/ReactElement.js 0000755 00000010107 15077334362 0017540 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.test = exports.serialize = exports.default = void 0; var ReactIs = _interopRequireWildcard(require('react-is')); var _markup = require('./lib/markup'); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== 'function') return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { return {default: obj}; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // Given element.props.children, or subtree during recursive traversal, // return flattened array of children. const getChildren = (arg, children = []) => { if (Array.isArray(arg)) { arg.forEach(item => { getChildren(item, children); }); } else if (arg != null && arg !== false) { children.push(arg); } return children; }; const getType = element => { const type = element.type; if (typeof type === 'string') { return type; } if (typeof type === 'function') { return type.displayName || type.name || 'Unknown'; } if (ReactIs.isFragment(element)) { return 'React.Fragment'; } if (ReactIs.isSuspense(element)) { return 'React.Suspense'; } if (typeof type === 'object' && type !== null) { if (ReactIs.isContextProvider(element)) { return 'Context.Provider'; } if (ReactIs.isContextConsumer(element)) { return 'Context.Consumer'; } if (ReactIs.isForwardRef(element)) { if (type.displayName) { return type.displayName; } const functionName = type.render.displayName || type.render.name || ''; return functionName !== '' ? `ForwardRef(${functionName})` : 'ForwardRef'; } if (ReactIs.isMemo(element)) { const functionName = type.displayName || type.type.displayName || type.type.name || ''; return functionName !== '' ? `Memo(${functionName})` : 'Memo'; } } return 'UNDEFINED'; }; const getPropKeys = element => { const {props} = element; return Object.keys(props) .filter(key => key !== 'children' && props[key] !== undefined) .sort(); }; const serialize = (element, config, indentation, depth, refs, printer) => ++depth > config.maxDepth ? (0, _markup.printElementAsLeaf)(getType(element), config) : (0, _markup.printElement)( getType(element), (0, _markup.printProps)( getPropKeys(element), element.props, config, indentation + config.indent, depth, refs, printer ), (0, _markup.printChildren)( getChildren(element.props.children), config, indentation + config.indent, depth, refs, printer ), config, indentation ); exports.serialize = serialize; const test = val => val != null && ReactIs.isElement(val); exports.test = test; const plugin = { serialize, test }; var _default = plugin; exports.default = _default; node_modules/pretty-format/build/plugins/lib/escapeHTML.js 0000755 00000000605 15077334362 0017665 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.default = escapeHTML; /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ function escapeHTML(str) { return str.replace(/</g, '<').replace(/>/g, '>'); } node_modules/pretty-format/build/plugins/lib/markup.js 0000755 00000006505 15077334362 0017244 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.printText = exports.printProps = exports.printElementAsLeaf = exports.printElement = exports.printComment = exports.printChildren = void 0; var _escapeHTML = _interopRequireDefault(require('./escapeHTML')); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : {default: obj}; } /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // Return empty string if keys is empty. const printProps = (keys, props, config, indentation, depth, refs, printer) => { const indentationNext = indentation + config.indent; const colors = config.colors; return keys .map(key => { const value = props[key]; let printed = printer(value, config, indentationNext, depth, refs); if (typeof value !== 'string') { if (printed.indexOf('\n') !== -1) { printed = config.spacingOuter + indentationNext + printed + config.spacingOuter + indentation; } printed = `{${printed}}`; } return `${ config.spacingInner + indentation + colors.prop.open + key + colors.prop.close }=${colors.value.open}${printed}${colors.value.close}`; }) .join(''); }; // Return empty string if children is empty. exports.printProps = printProps; const printChildren = (children, config, indentation, depth, refs, printer) => children .map( child => config.spacingOuter + indentation + (typeof child === 'string' ? printText(child, config) : printer(child, config, indentation, depth, refs)) ) .join(''); exports.printChildren = printChildren; const printText = (text, config) => { const contentColor = config.colors.content; return ( contentColor.open + (0, _escapeHTML.default)(text) + contentColor.close ); }; exports.printText = printText; const printComment = (comment, config) => { const commentColor = config.colors.comment; return `${commentColor.open}<!--${(0, _escapeHTML.default)(comment)}-->${ commentColor.close }`; }; // Separate the functions to format props, children, and element, // so a plugin could override a particular function, if needed. // Too bad, so sad: the traditional (but unnecessary) space // in a self-closing tagColor requires a second test of printedProps. exports.printComment = printComment; const printElement = ( type, printedProps, printedChildren, config, indentation ) => { const tagColor = config.colors.tag; return `${tagColor.open}<${type}${ printedProps && tagColor.close + printedProps + config.spacingOuter + indentation + tagColor.open }${ printedChildren ? `>${tagColor.close}${printedChildren}${config.spacingOuter}${indentation}${tagColor.open}</${type}` : `${printedProps && !config.min ? '' : ' '}/` }>${tagColor.close}`; }; exports.printElement = printElement; const printElementAsLeaf = (type, config) => { const tagColor = config.colors.tag; return `${tagColor.open}<${type}${tagColor.close} …${tagColor.open} />${tagColor.close}`; }; exports.printElementAsLeaf = printElementAsLeaf; node_modules/pretty-format/build/types.js 0000755 00000000016 15077334362 0014651 0 ustar 00 'use strict'; node_modules/pretty-format/build/index.d.ts 0000755 00000006556 15077334362 0015067 0 ustar 00 /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import type {SnapshotFormat} from '@jest/schemas'; export declare type Colors = { comment: { close: string; open: string; }; content: { close: string; open: string; }; prop: { close: string; open: string; }; tag: { close: string; open: string; }; value: { close: string; open: string; }; }; export declare type CompareKeys = | ((a: string, b: string) => number) | null | undefined; export declare type Config = { callToJSON: boolean; compareKeys: CompareKeys; colors: Colors; escapeRegex: boolean; escapeString: boolean; indent: string; maxDepth: number; maxWidth: number; min: boolean; plugins: Plugins; printBasicPrototype: boolean; printFunctionName: boolean; spacingInner: string; spacingOuter: string; }; export declare const DEFAULT_OPTIONS: { callToJSON: true; compareKeys: undefined; escapeRegex: false; escapeString: true; highlight: false; indent: number; maxDepth: number; maxWidth: number; min: false; plugins: never[]; printBasicPrototype: true; printFunctionName: true; theme: Required<{ readonly comment?: string | undefined; readonly content?: string | undefined; readonly prop?: string | undefined; readonly tag?: string | undefined; readonly value?: string | undefined; }>; }; /** * Returns a presentation string of your `val` object * @param val any potential JavaScript object * @param options Custom settings */ declare function format(val: unknown, options?: OptionsReceived): string; export default format; export {format}; declare type Indent = (arg0: string) => string; export declare type NewPlugin = { serialize: ( val: any, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, ) => string; test: Test; }; export declare type OldPlugin = { print: ( val: unknown, print: Print, indent: Indent, options: PluginOptions, colors: Colors, ) => string; test: Test; }; export declare interface Options extends Omit<RequiredOptions, 'compareKeys' | 'theme'> { compareKeys: CompareKeys; theme: Required<RequiredOptions['theme']>; } export declare type OptionsReceived = PrettyFormatOptions; declare type Plugin_2 = NewPlugin | OldPlugin; export {Plugin_2 as Plugin}; declare type PluginOptions = { edgeSpacing: string; min: boolean; spacing: string; }; export declare type Plugins = Array<Plugin_2>; export declare const plugins: { AsymmetricMatcher: NewPlugin; DOMCollection: NewPlugin; DOMElement: NewPlugin; Immutable: NewPlugin; ReactElement: NewPlugin; ReactTestComponent: NewPlugin; }; export declare interface PrettyFormatOptions extends Omit<SnapshotFormat, 'compareKeys'> { compareKeys?: CompareKeys; plugins?: Plugins; } declare type Print = (arg0: unknown) => string; export declare type Printer = ( val: unknown, config: Config, indentation: string, depth: number, refs: Refs, hasCalledToJSON?: boolean, ) => string; export declare type Refs = Array<unknown>; declare type RequiredOptions = Required<PrettyFormatOptions>; declare type Test = (arg0: any) => boolean; export declare type Theme = Options['theme']; export {}; node_modules/pretty-format/build/collections.js 0000755 00000011467 15077334362 0016037 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.printIteratorEntries = printIteratorEntries; exports.printIteratorValues = printIteratorValues; exports.printListItems = printListItems; exports.printObjectProperties = printObjectProperties; /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ const getKeysOfEnumerableProperties = (object, compareKeys) => { const rawKeys = Object.keys(object); const keys = compareKeys !== null ? rawKeys.sort(compareKeys) : rawKeys; if (Object.getOwnPropertySymbols) { Object.getOwnPropertySymbols(object).forEach(symbol => { if (Object.getOwnPropertyDescriptor(object, symbol).enumerable) { keys.push(symbol); } }); } return keys; }; /** * Return entries (for example, of a map) * with spacing, indentation, and comma * without surrounding punctuation (for example, braces) */ function printIteratorEntries( iterator, config, indentation, depth, refs, printer, // Too bad, so sad that separator for ECMAScript Map has been ' => ' // What a distracting diff if you change a data structure to/from // ECMAScript Object or Immutable.Map/OrderedMap which use the default. separator = ': ' ) { let result = ''; let width = 0; let current = iterator.next(); if (!current.done) { result += config.spacingOuter; const indentationNext = indentation + config.indent; while (!current.done) { result += indentationNext; if (width++ === config.maxWidth) { result += '…'; break; } const name = printer( current.value[0], config, indentationNext, depth, refs ); const value = printer( current.value[1], config, indentationNext, depth, refs ); result += name + separator + value; current = iterator.next(); if (!current.done) { result += `,${config.spacingInner}`; } else if (!config.min) { result += ','; } } result += config.spacingOuter + indentation; } return result; } /** * Return values (for example, of a set) * with spacing, indentation, and comma * without surrounding punctuation (braces or brackets) */ function printIteratorValues( iterator, config, indentation, depth, refs, printer ) { let result = ''; let width = 0; let current = iterator.next(); if (!current.done) { result += config.spacingOuter; const indentationNext = indentation + config.indent; while (!current.done) { result += indentationNext; if (width++ === config.maxWidth) { result += '…'; break; } result += printer(current.value, config, indentationNext, depth, refs); current = iterator.next(); if (!current.done) { result += `,${config.spacingInner}`; } else if (!config.min) { result += ','; } } result += config.spacingOuter + indentation; } return result; } /** * Return items (for example, of an array) * with spacing, indentation, and comma * without surrounding punctuation (for example, brackets) **/ function printListItems(list, config, indentation, depth, refs, printer) { let result = ''; if (list.length) { result += config.spacingOuter; const indentationNext = indentation + config.indent; for (let i = 0; i < list.length; i++) { result += indentationNext; if (i === config.maxWidth) { result += '…'; break; } if (i in list) { result += printer(list[i], config, indentationNext, depth, refs); } if (i < list.length - 1) { result += `,${config.spacingInner}`; } else if (!config.min) { result += ','; } } result += config.spacingOuter + indentation; } return result; } /** * Return properties of an object * with spacing, indentation, and comma * without surrounding punctuation (for example, braces) */ function printObjectProperties(val, config, indentation, depth, refs, printer) { let result = ''; const keys = getKeysOfEnumerableProperties(val, config.compareKeys); if (keys.length) { result += config.spacingOuter; const indentationNext = indentation + config.indent; for (let i = 0; i < keys.length; i++) { const key = keys[i]; const name = printer(key, config, indentationNext, depth, refs); const value = printer(val[key], config, indentationNext, depth, refs); result += `${indentationNext + name}: ${value}`; if (i < keys.length - 1) { result += `,${config.spacingInner}`; } else if (!config.min) { result += ','; } } result += config.spacingOuter + indentation; } return result; } node_modules/pretty-format/build/index.js 0000755 00000032657 15077334362 0014634 0 ustar 00 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.default = exports.DEFAULT_OPTIONS = void 0; exports.format = format; exports.plugins = void 0; var _ansiStyles = _interopRequireDefault(require('ansi-styles')); var _collections = require('./collections'); var _AsymmetricMatcher = _interopRequireDefault( require('./plugins/AsymmetricMatcher') ); var _DOMCollection = _interopRequireDefault(require('./plugins/DOMCollection')); var _DOMElement = _interopRequireDefault(require('./plugins/DOMElement')); var _Immutable = _interopRequireDefault(require('./plugins/Immutable')); var _ReactElement = _interopRequireDefault(require('./plugins/ReactElement')); var _ReactTestComponent = _interopRequireDefault( require('./plugins/ReactTestComponent') ); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : {default: obj}; } /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* eslint-disable local/ban-types-eventually */ const toString = Object.prototype.toString; const toISOString = Date.prototype.toISOString; const errorToString = Error.prototype.toString; const regExpToString = RegExp.prototype.toString; /** * Explicitly comparing typeof constructor to function avoids undefined as name * when mock identity-obj-proxy returns the key as the value for any key. */ const getConstructorName = val => (typeof val.constructor === 'function' && val.constructor.name) || 'Object'; /* global window */ /** Is val is equal to global window object? Works even if it does not exist :) */ const isWindow = val => typeof window !== 'undefined' && val === window; const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/; const NEWLINE_REGEXP = /\n/gi; class PrettyFormatPluginError extends Error { constructor(message, stack) { super(message); this.stack = stack; this.name = this.constructor.name; } } function isToStringedArrayType(toStringed) { return ( toStringed === '[object Array]' || toStringed === '[object ArrayBuffer]' || toStringed === '[object DataView]' || toStringed === '[object Float32Array]' || toStringed === '[object Float64Array]' || toStringed === '[object Int8Array]' || toStringed === '[object Int16Array]' || toStringed === '[object Int32Array]' || toStringed === '[object Uint8Array]' || toStringed === '[object Uint8ClampedArray]' || toStringed === '[object Uint16Array]' || toStringed === '[object Uint32Array]' ); } function printNumber(val) { return Object.is(val, -0) ? '-0' : String(val); } function printBigInt(val) { return String(`${val}n`); } function printFunction(val, printFunctionName) { if (!printFunctionName) { return '[Function]'; } return `[Function ${val.name || 'anonymous'}]`; } function printSymbol(val) { return String(val).replace(SYMBOL_REGEXP, 'Symbol($1)'); } function printError(val) { return `[${errorToString.call(val)}]`; } /** * The first port of call for printing an object, handles most of the * data-types in JS. */ function printBasicValue(val, printFunctionName, escapeRegex, escapeString) { if (val === true || val === false) { return `${val}`; } if (val === undefined) { return 'undefined'; } if (val === null) { return 'null'; } const typeOf = typeof val; if (typeOf === 'number') { return printNumber(val); } if (typeOf === 'bigint') { return printBigInt(val); } if (typeOf === 'string') { if (escapeString) { return `"${val.replace(/"|\\/g, '\\$&')}"`; } return `"${val}"`; } if (typeOf === 'function') { return printFunction(val, printFunctionName); } if (typeOf === 'symbol') { return printSymbol(val); } const toStringed = toString.call(val); if (toStringed === '[object WeakMap]') { return 'WeakMap {}'; } if (toStringed === '[object WeakSet]') { return 'WeakSet {}'; } if ( toStringed === '[object Function]' || toStringed === '[object GeneratorFunction]' ) { return printFunction(val, printFunctionName); } if (toStringed === '[object Symbol]') { return printSymbol(val); } if (toStringed === '[object Date]') { return isNaN(+val) ? 'Date { NaN }' : toISOString.call(val); } if (toStringed === '[object Error]') { return printError(val); } if (toStringed === '[object RegExp]') { if (escapeRegex) { // https://github.com/benjamingr/RegExp.escape/blob/main/polyfill.js return regExpToString.call(val).replace(/[\\^$*+?.()|[\]{}]/g, '\\$&'); } return regExpToString.call(val); } if (val instanceof Error) { return printError(val); } return null; } /** * Handles more complex objects ( such as objects with circular references. * maps and sets etc ) */ function printComplexValue( val, config, indentation, depth, refs, hasCalledToJSON ) { if (refs.indexOf(val) !== -1) { return '[Circular]'; } refs = refs.slice(); refs.push(val); const hitMaxDepth = ++depth > config.maxDepth; const min = config.min; if ( config.callToJSON && !hitMaxDepth && val.toJSON && typeof val.toJSON === 'function' && !hasCalledToJSON ) { return printer(val.toJSON(), config, indentation, depth, refs, true); } const toStringed = toString.call(val); if (toStringed === '[object Arguments]') { return hitMaxDepth ? '[Arguments]' : `${min ? '' : 'Arguments '}[${(0, _collections.printListItems)( val, config, indentation, depth, refs, printer )}]`; } if (isToStringedArrayType(toStringed)) { return hitMaxDepth ? `[${val.constructor.name}]` : `${ min ? '' : !config.printBasicPrototype && val.constructor.name === 'Array' ? '' : `${val.constructor.name} ` }[${(0, _collections.printListItems)( val, config, indentation, depth, refs, printer )}]`; } if (toStringed === '[object Map]') { return hitMaxDepth ? '[Map]' : `Map {${(0, _collections.printIteratorEntries)( val.entries(), config, indentation, depth, refs, printer, ' => ' )}}`; } if (toStringed === '[object Set]') { return hitMaxDepth ? '[Set]' : `Set {${(0, _collections.printIteratorValues)( val.values(), config, indentation, depth, refs, printer )}}`; } // Avoid failure to serialize global window object in jsdom test environment. // For example, not even relevant if window is prop of React element. return hitMaxDepth || isWindow(val) ? `[${getConstructorName(val)}]` : `${ min ? '' : !config.printBasicPrototype && getConstructorName(val) === 'Object' ? '' : `${getConstructorName(val)} ` }{${(0, _collections.printObjectProperties)( val, config, indentation, depth, refs, printer )}}`; } function isNewPlugin(plugin) { return plugin.serialize != null; } function printPlugin(plugin, val, config, indentation, depth, refs) { let printed; try { printed = isNewPlugin(plugin) ? plugin.serialize(val, config, indentation, depth, refs, printer) : plugin.print( val, valChild => printer(valChild, config, indentation, depth, refs), str => { const indentationNext = indentation + config.indent; return ( indentationNext + str.replace(NEWLINE_REGEXP, `\n${indentationNext}`) ); }, { edgeSpacing: config.spacingOuter, min: config.min, spacing: config.spacingInner }, config.colors ); } catch (error) { throw new PrettyFormatPluginError(error.message, error.stack); } if (typeof printed !== 'string') { throw new Error( `pretty-format: Plugin must return type "string" but instead returned "${typeof printed}".` ); } return printed; } function findPlugin(plugins, val) { for (let p = 0; p < plugins.length; p++) { try { if (plugins[p].test(val)) { return plugins[p]; } } catch (error) { throw new PrettyFormatPluginError(error.message, error.stack); } } return null; } function printer(val, config, indentation, depth, refs, hasCalledToJSON) { const plugin = findPlugin(config.plugins, val); if (plugin !== null) { return printPlugin(plugin, val, config, indentation, depth, refs); } const basicResult = printBasicValue( val, config.printFunctionName, config.escapeRegex, config.escapeString ); if (basicResult !== null) { return basicResult; } return printComplexValue( val, config, indentation, depth, refs, hasCalledToJSON ); } const DEFAULT_THEME = { comment: 'gray', content: 'reset', prop: 'yellow', tag: 'cyan', value: 'green' }; const DEFAULT_THEME_KEYS = Object.keys(DEFAULT_THEME); // could be replaced by `satisfies` operator in the future: https://github.com/microsoft/TypeScript/issues/47920 const toOptionsSubtype = options => options; const DEFAULT_OPTIONS = toOptionsSubtype({ callToJSON: true, compareKeys: undefined, escapeRegex: false, escapeString: true, highlight: false, indent: 2, maxDepth: Infinity, maxWidth: Infinity, min: false, plugins: [], printBasicPrototype: true, printFunctionName: true, theme: DEFAULT_THEME }); exports.DEFAULT_OPTIONS = DEFAULT_OPTIONS; function validateOptions(options) { Object.keys(options).forEach(key => { if (!Object.prototype.hasOwnProperty.call(DEFAULT_OPTIONS, key)) { throw new Error(`pretty-format: Unknown option "${key}".`); } }); if (options.min && options.indent !== undefined && options.indent !== 0) { throw new Error( 'pretty-format: Options "min" and "indent" cannot be used together.' ); } if (options.theme !== undefined) { if (options.theme === null) { throw new Error('pretty-format: Option "theme" must not be null.'); } if (typeof options.theme !== 'object') { throw new Error( `pretty-format: Option "theme" must be of type "object" but instead received "${typeof options.theme}".` ); } } } const getColorsHighlight = options => DEFAULT_THEME_KEYS.reduce((colors, key) => { const value = options.theme && options.theme[key] !== undefined ? options.theme[key] : DEFAULT_THEME[key]; const color = value && _ansiStyles.default[value]; if ( color && typeof color.close === 'string' && typeof color.open === 'string' ) { colors[key] = color; } else { throw new Error( `pretty-format: Option "theme" has a key "${key}" whose value "${value}" is undefined in ansi-styles.` ); } return colors; }, Object.create(null)); const getColorsEmpty = () => DEFAULT_THEME_KEYS.reduce((colors, key) => { colors[key] = { close: '', open: '' }; return colors; }, Object.create(null)); const getPrintFunctionName = options => options?.printFunctionName ?? DEFAULT_OPTIONS.printFunctionName; const getEscapeRegex = options => options?.escapeRegex ?? DEFAULT_OPTIONS.escapeRegex; const getEscapeString = options => options?.escapeString ?? DEFAULT_OPTIONS.escapeString; const getConfig = options => ({ callToJSON: options?.callToJSON ?? DEFAULT_OPTIONS.callToJSON, colors: options?.highlight ? getColorsHighlight(options) : getColorsEmpty(), compareKeys: typeof options?.compareKeys === 'function' || options?.compareKeys === null ? options.compareKeys : DEFAULT_OPTIONS.compareKeys, escapeRegex: getEscapeRegex(options), escapeString: getEscapeString(options), indent: options?.min ? '' : createIndent(options?.indent ?? DEFAULT_OPTIONS.indent), maxDepth: options?.maxDepth ?? DEFAULT_OPTIONS.maxDepth, maxWidth: options?.maxWidth ?? DEFAULT_OPTIONS.maxWidth, min: options?.min ?? DEFAULT_OPTIONS.min, plugins: options?.plugins ?? DEFAULT_OPTIONS.plugins, printBasicPrototype: options?.printBasicPrototype ?? true, printFunctionName: getPrintFunctionName(options), spacingInner: options?.min ? ' ' : '\n', spacingOuter: options?.min ? '' : '\n' }); function createIndent(indent) { return new Array(indent + 1).join(' '); } /** * Returns a presentation string of your `val` object * @param val any potential JavaScript object * @param options Custom settings */ function format(val, options) { if (options) { validateOptions(options); if (options.plugins) { const plugin = findPlugin(options.plugins, val); if (plugin !== null) { return printPlugin(plugin, val, getConfig(options), '', 0, []); } } } const basicResult = printBasicValue( val, getPrintFunctionName(options), getEscapeRegex(options), getEscapeString(options) ); if (basicResult !== null) { return basicResult; } return printComplexValue(val, getConfig(options), '', 0, []); } const plugins = { AsymmetricMatcher: _AsymmetricMatcher.default, DOMCollection: _DOMCollection.default, DOMElement: _DOMElement.default, Immutable: _Immutable.default, ReactElement: _ReactElement.default, ReactTestComponent: _ReactTestComponent.default }; exports.plugins = plugins; var _default = format; exports.default = _default; node_modules/color-convert/README.md 0000755 00000005445 15077334362 0013321 0 ustar 00 # color-convert [](https://travis-ci.org/Qix-/color-convert) Color-convert is a color conversion library for JavaScript and node. It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest): ```js var convert = require('color-convert'); convert.rgb.hsl(140, 200, 100); // [96, 48, 59] convert.keyword.rgb('blue'); // [0, 0, 255] var rgbChannels = convert.rgb.channels; // 3 var cmykChannels = convert.cmyk.channels; // 4 var ansiChannels = convert.ansi16.channels; // 1 ``` # Install ```console $ npm install color-convert ``` # API Simply get the property of the _from_ and _to_ conversion that you're looking for. All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function. All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha). ```js var convert = require('color-convert'); // Hex to LAB convert.hex.lab('DEADBF'); // [ 76, 21, -2 ] convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ] // RGB to CMYK convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ] convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ] ``` ### Arrays All functions that accept multiple arguments also support passing an array. Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.) ```js var convert = require('color-convert'); convert.rgb.hex(123, 45, 67); // '7B2D43' convert.rgb.hex([123, 45, 67]); // '7B2D43' ``` ## Routing Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex). Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js). # Contribute If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request. # License Copyright © 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE). node_modules/color-convert/route.js 0000755 00000004321 15077334362 0013526 0 ustar 00 const conversions = require('./conversions'); /* This function routes a model to all other models. all functions that are routed have a property `.conversion` attached to the returned synthetic function. This property is an array of strings, each with the steps in between the 'from' and 'to' color models (inclusive). conversions that are not possible simply are not included. */ function buildGraph() { const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 const models = Object.keys(conversions); for (let len = models.length, i = 0; i < len; i++) { graph[models[i]] = { // http://jsperf.com/1-vs-infinity // micro-opt, but this is simple. distance: -1, parent: null }; } return graph; } // https://en.wikipedia.org/wiki/Breadth-first_search function deriveBFS(fromModel) { const graph = buildGraph(); const queue = [fromModel]; // Unshift -> queue -> pop graph[fromModel].distance = 0; while (queue.length) { const current = queue.pop(); const adjacents = Object.keys(conversions[current]); for (let len = adjacents.length, i = 0; i < len; i++) { const adjacent = adjacents[i]; const node = graph[adjacent]; if (node.distance === -1) { node.distance = graph[current].distance + 1; node.parent = current; queue.unshift(adjacent); } } } return graph; } function link(from, to) { return function (args) { return to(from(args)); }; } function wrapConversion(toModel, graph) { const path = [graph[toModel].parent, toModel]; let fn = conversions[graph[toModel].parent][toModel]; let cur = graph[toModel].parent; while (graph[cur].parent) { path.unshift(graph[cur].parent); fn = link(conversions[graph[cur].parent][cur], fn); cur = graph[cur].parent; } fn.conversion = path; return fn; } module.exports = function (fromModel) { const graph = deriveBFS(fromModel); const conversion = {}; const models = Object.keys(graph); for (let len = models.length, i = 0; i < len; i++) { const toModel = models[i]; const node = graph[toModel]; if (node.parent === null) { // No possible conversion, or this node is the source model. continue; } conversion[toModel] = wrapConversion(toModel, graph); } return conversion; }; node_modules/color-convert/LICENSE 0000755 00000002077 15077334362 0013045 0 ustar 00 Copyright (c) 2011-2016 Heather Arthur <fayearthur@gmail.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. node_modules/color-convert/CHANGELOG.md 0000755 00000002611 15077334362 0013643 0 ustar 00 # 1.0.0 - 2016-01-07 - Removed: unused speed test - Added: Automatic routing between previously unsupported conversions ([#27](https://github.com/Qix-/color-convert/pull/27)) - Removed: `xxx2xxx()` and `xxx2xxxRaw()` functions ([#27](https://github.com/Qix-/color-convert/pull/27)) - Removed: `convert()` class ([#27](https://github.com/Qix-/color-convert/pull/27)) - Changed: all functions to lookup dictionary ([#27](https://github.com/Qix-/color-convert/pull/27)) - Changed: `ansi` to `ansi256` ([#27](https://github.com/Qix-/color-convert/pull/27)) - Fixed: argument grouping for functions requiring only one argument ([#27](https://github.com/Qix-/color-convert/pull/27)) # 0.6.0 - 2015-07-23 - Added: methods to handle [ANSI](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) 16/256 colors: - rgb2ansi16 - rgb2ansi - hsl2ansi16 - hsl2ansi - hsv2ansi16 - hsv2ansi - hwb2ansi16 - hwb2ansi - cmyk2ansi16 - cmyk2ansi - keyword2ansi16 - keyword2ansi - ansi162rgb - ansi162hsl - ansi162hsv - ansi162hwb - ansi162cmyk - ansi162keyword - ansi2rgb - ansi2hsl - ansi2hsv - ansi2hwb - ansi2cmyk - ansi2keyword ([#18](https://github.com/harthur/color-convert/pull/18)) # 0.5.3 - 2015-06-02 - Fixed: hsl2hsv does not return `NaN` anymore when using `[0,0,0]` ([#15](https://github.com/harthur/color-convert/issues/15)) --- Check out commit logs for older releases node_modules/color-convert/package.json 0000755 00000001473 15077334362 0014325 0 ustar 00 { "name": "color-convert", "description": "Plain color conversion functions", "version": "2.0.1", "author": "Heather Arthur <fayearthur@gmail.com>", "license": "MIT", "repository": "Qix-/color-convert", "scripts": { "pretest": "xo", "test": "node test/basic.js" }, "engines": { "node": ">=7.0.0" }, "keywords": [ "color", "colour", "convert", "converter", "conversion", "rgb", "hsl", "hsv", "hwb", "cmyk", "ansi", "ansi16" ], "files": [ "index.js", "conversions.js", "route.js" ], "xo": { "rules": { "default-case": 0, "no-inline-comments": 0, "operator-linebreak": 0 } }, "devDependencies": { "chalk": "^2.4.2", "xo": "^0.24.0" }, "dependencies": { "color-name": "~1.1.4" } } node_modules/color-convert/conversions.js 0000755 00000041220 15077334362 0014737 0 ustar 00 /* MIT license */ /* eslint-disable no-mixed-operators */ const cssKeywords = require('color-name'); // NOTE: conversions should only return primitive values (i.e. arrays, or // values that give correct `typeof` results). // do not use box values types (i.e. Number(), String(), etc.) const reverseKeywords = {}; for (const key of Object.keys(cssKeywords)) { reverseKeywords[cssKeywords[key]] = key; } const convert = { rgb: {channels: 3, labels: 'rgb'}, hsl: {channels: 3, labels: 'hsl'}, hsv: {channels: 3, labels: 'hsv'}, hwb: {channels: 3, labels: 'hwb'}, cmyk: {channels: 4, labels: 'cmyk'}, xyz: {channels: 3, labels: 'xyz'}, lab: {channels: 3, labels: 'lab'}, lch: {channels: 3, labels: 'lch'}, hex: {channels: 1, labels: ['hex']}, keyword: {channels: 1, labels: ['keyword']}, ansi16: {channels: 1, labels: ['ansi16']}, ansi256: {channels: 1, labels: ['ansi256']}, hcg: {channels: 3, labels: ['h', 'c', 'g']}, apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, gray: {channels: 1, labels: ['gray']} }; module.exports = convert; // Hide .channels and .labels properties for (const model of Object.keys(convert)) { if (!('channels' in convert[model])) { throw new Error('missing channels property: ' + model); } if (!('labels' in convert[model])) { throw new Error('missing channel labels property: ' + model); } if (convert[model].labels.length !== convert[model].channels) { throw new Error('channel and label counts mismatch: ' + model); } const {channels, labels} = convert[model]; delete convert[model].channels; delete convert[model].labels; Object.defineProperty(convert[model], 'channels', {value: channels}); Object.defineProperty(convert[model], 'labels', {value: labels}); } convert.rgb.hsl = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const min = Math.min(r, g, b); const max = Math.max(r, g, b); const delta = max - min; let h; let s; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } const l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; convert.rgb.hsv = function (rgb) { let rdif; let gdif; let bdif; let h; let s; const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const v = Math.max(r, g, b); const diff = v - Math.min(r, g, b); const diffc = function (c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff === 0) { h = 0; s = 0; } else { s = diff / v; rdif = diffc(r); gdif = diffc(g); bdif = diffc(b); if (r === v) { h = bdif - gdif; } else if (g === v) { h = (1 / 3) + rdif - bdif; } else if (b === v) { h = (2 / 3) + gdif - rdif; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return [ h * 360, s * 100, v * 100 ]; }; convert.rgb.hwb = function (rgb) { const r = rgb[0]; const g = rgb[1]; let b = rgb[2]; const h = convert.rgb.hsl(rgb)[0]; const w = 1 / 255 * Math.min(r, Math.min(g, b)); b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); return [h, w * 100, b * 100]; }; convert.rgb.cmyk = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const k = Math.min(1 - r, 1 - g, 1 - b); const c = (1 - r - k) / (1 - k) || 0; const m = (1 - g - k) / (1 - k) || 0; const y = (1 - b - k) / (1 - k) || 0; return [c * 100, m * 100, y * 100, k * 100]; }; function comparativeDistance(x, y) { /* See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance */ return ( ((x[0] - y[0]) ** 2) + ((x[1] - y[1]) ** 2) + ((x[2] - y[2]) ** 2) ); } convert.rgb.keyword = function (rgb) { const reversed = reverseKeywords[rgb]; if (reversed) { return reversed; } let currentClosestDistance = Infinity; let currentClosestKeyword; for (const keyword of Object.keys(cssKeywords)) { const value = cssKeywords[keyword]; // Compute comparative distance const distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest if (distance < currentClosestDistance) { currentClosestDistance = distance; currentClosestKeyword = keyword; } } return currentClosestKeyword; }; convert.keyword.rgb = function (keyword) { return cssKeywords[keyword]; }; convert.rgb.xyz = function (rgb) { let r = rgb[0] / 255; let g = rgb[1] / 255; let b = rgb[2] / 255; // Assume sRGB r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); return [x * 100, y * 100, z * 100]; }; convert.rgb.lab = function (rgb) { const xyz = convert.rgb.xyz(rgb); let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); const l = (116 * y) - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert.hsl.rgb = function (hsl) { const h = hsl[0] / 360; const s = hsl[1] / 100; const l = hsl[2] / 100; let t2; let t3; let val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } const t1 = 2 * l - t2; const rgb = [0, 0, 0]; for (let i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; }; convert.hsl.hsv = function (hsl) { const h = hsl[0]; let s = hsl[1] / 100; let l = hsl[2] / 100; let smin = s; const lmin = Math.max(l, 0.01); l *= 2; s *= (l <= 1) ? l : 2 - l; smin *= lmin <= 1 ? lmin : 2 - lmin; const v = (l + s) / 2; const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); return [h, sv * 100, v * 100]; }; convert.hsv.rgb = function (hsv) { const h = hsv[0] / 60; const s = hsv[1] / 100; let v = hsv[2] / 100; const hi = Math.floor(h) % 6; const f = h - Math.floor(h); const p = 255 * v * (1 - s); const q = 255 * v * (1 - (s * f)); const t = 255 * v * (1 - (s * (1 - f))); v *= 255; switch (hi) { case 0: return [v, t, p]; case 1: return [q, v, p]; case 2: return [p, v, t]; case 3: return [p, q, v]; case 4: return [t, p, v]; case 5: return [v, p, q]; } }; convert.hsv.hsl = function (hsv) { const h = hsv[0]; const s = hsv[1] / 100; const v = hsv[2] / 100; const vmin = Math.max(v, 0.01); let sl; let l; l = (2 - s) * v; const lmin = (2 - s) * vmin; sl = s * vmin; sl /= (lmin <= 1) ? lmin : 2 - lmin; sl = sl || 0; l /= 2; return [h, sl * 100, l * 100]; }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb convert.hwb.rgb = function (hwb) { const h = hwb[0] / 360; let wh = hwb[1] / 100; let bl = hwb[2] / 100; const ratio = wh + bl; let f; // Wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } const i = Math.floor(6 * h); const v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } const n = wh + f * (v - wh); // Linear interpolation let r; let g; let b; /* eslint-disable max-statements-per-line,no-multi-spaces */ switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } /* eslint-enable max-statements-per-line,no-multi-spaces */ return [r * 255, g * 255, b * 255]; }; convert.cmyk.rgb = function (cmyk) { const c = cmyk[0] / 100; const m = cmyk[1] / 100; const y = cmyk[2] / 100; const k = cmyk[3] / 100; const r = 1 - Math.min(1, c * (1 - k) + k); const g = 1 - Math.min(1, m * (1 - k) + k); const b = 1 - Math.min(1, y * (1 - k) + k); return [r * 255, g * 255, b * 255]; }; convert.xyz.rgb = function (xyz) { const x = xyz[0] / 100; const y = xyz[1] / 100; const z = xyz[2] / 100; let r; let g; let b; r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); // Assume sRGB r = r > 0.0031308 ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) : r * 12.92; g = g > 0.0031308 ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) : g * 12.92; b = b > 0.0031308 ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) : b * 12.92; r = Math.min(Math.max(0, r), 1); g = Math.min(Math.max(0, g), 1); b = Math.min(Math.max(0, b), 1); return [r * 255, g * 255, b * 255]; }; convert.xyz.lab = function (xyz) { let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); const l = (116 * y) - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert.lab.xyz = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let x; let y; let z; y = (l + 16) / 116; x = a / 500 + y; z = y - b / 200; const y2 = y ** 3; const x2 = x ** 3; const z2 = z ** 3; y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; x *= 95.047; y *= 100; z *= 108.883; return [x, y, z]; }; convert.lab.lch = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let h; const hr = Math.atan2(b, a); h = hr * 360 / 2 / Math.PI; if (h < 0) { h += 360; } const c = Math.sqrt(a * a + b * b); return [l, c, h]; }; convert.lch.lab = function (lch) { const l = lch[0]; const c = lch[1]; const h = lch[2]; const hr = h / 360 * 2 * Math.PI; const a = c * Math.cos(hr); const b = c * Math.sin(hr); return [l, a, b]; }; convert.rgb.ansi16 = function (args, saturation = null) { const [r, g, b] = args; let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization value = Math.round(value / 50); if (value === 0) { return 30; } let ansi = 30 + ((Math.round(b / 255) << 2) | (Math.round(g / 255) << 1) | Math.round(r / 255)); if (value === 2) { ansi += 60; } return ansi; }; convert.hsv.ansi16 = function (args) { // Optimization here; we already know the value and don't need to get // it converted for us. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); }; convert.rgb.ansi256 = function (args) { const r = args[0]; const g = args[1]; const b = args[2]; // We use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (r === g && g === b) { if (r < 8) { return 16; } if (r > 248) { return 231; } return Math.round(((r - 8) / 247) * 24) + 232; } const ansi = 16 + (36 * Math.round(r / 255 * 5)) + (6 * Math.round(g / 255 * 5)) + Math.round(b / 255 * 5); return ansi; }; convert.ansi16.rgb = function (args) { let color = args % 10; // Handle greyscale if (color === 0 || color === 7) { if (args > 50) { color += 3.5; } color = color / 10.5 * 255; return [color, color, color]; } const mult = (~~(args > 50) + 1) * 0.5; const r = ((color & 1) * mult) * 255; const g = (((color >> 1) & 1) * mult) * 255; const b = (((color >> 2) & 1) * mult) * 255; return [r, g, b]; }; convert.ansi256.rgb = function (args) { // Handle greyscale if (args >= 232) { const c = (args - 232) * 10 + 8; return [c, c, c]; } args -= 16; let rem; const r = Math.floor(args / 36) / 5 * 255; const g = Math.floor((rem = args % 36) / 6) / 5 * 255; const b = (rem % 6) / 5 * 255; return [r, g, b]; }; convert.rgb.hex = function (args) { const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.hex.rgb = function (args) { const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); if (!match) { return [0, 0, 0]; } let colorString = match[0]; if (match[0].length === 3) { colorString = colorString.split('').map(char => { return char + char; }).join(''); } const integer = parseInt(colorString, 16); const r = (integer >> 16) & 0xFF; const g = (integer >> 8) & 0xFF; const b = integer & 0xFF; return [r, g, b]; }; convert.rgb.hcg = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const max = Math.max(Math.max(r, g), b); const min = Math.min(Math.min(r, g), b); const chroma = (max - min); let grayscale; let hue; if (chroma < 1) { grayscale = min / (1 - chroma); } else { grayscale = 0; } if (chroma <= 0) { hue = 0; } else if (max === r) { hue = ((g - b) / chroma) % 6; } else if (max === g) { hue = 2 + (b - r) / chroma; } else { hue = 4 + (r - g) / chroma; } hue /= 6; hue %= 1; return [hue * 360, chroma * 100, grayscale * 100]; }; convert.hsl.hcg = function (hsl) { const s = hsl[1] / 100; const l = hsl[2] / 100; const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); let f = 0; if (c < 1.0) { f = (l - 0.5 * c) / (1.0 - c); } return [hsl[0], c * 100, f * 100]; }; convert.hsv.hcg = function (hsv) { const s = hsv[1] / 100; const v = hsv[2] / 100; const c = s * v; let f = 0; if (c < 1.0) { f = (v - c) / (1 - c); } return [hsv[0], c * 100, f * 100]; }; convert.hcg.rgb = function (hcg) { const h = hcg[0] / 360; const c = hcg[1] / 100; const g = hcg[2] / 100; if (c === 0.0) { return [g * 255, g * 255, g * 255]; } const pure = [0, 0, 0]; const hi = (h % 1) * 6; const v = hi % 1; const w = 1 - v; let mg = 0; /* eslint-disable max-statements-per-line */ switch (Math.floor(hi)) { case 0: pure[0] = 1; pure[1] = v; pure[2] = 0; break; case 1: pure[0] = w; pure[1] = 1; pure[2] = 0; break; case 2: pure[0] = 0; pure[1] = 1; pure[2] = v; break; case 3: pure[0] = 0; pure[1] = w; pure[2] = 1; break; case 4: pure[0] = v; pure[1] = 0; pure[2] = 1; break; default: pure[0] = 1; pure[1] = 0; pure[2] = w; } /* eslint-enable max-statements-per-line */ mg = (1.0 - c) * g; return [ (c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255 ]; }; convert.hcg.hsv = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); let f = 0; if (v > 0.0) { f = c / v; } return [hcg[0], f * 100, v * 100]; }; convert.hcg.hsl = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const l = g * (1.0 - c) + 0.5 * c; let s = 0; if (l > 0.0 && l < 0.5) { s = c / (2 * l); } else if (l >= 0.5 && l < 1.0) { s = c / (2 * (1 - l)); } return [hcg[0], s * 100, l * 100]; }; convert.hcg.hwb = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); return [hcg[0], (v - c) * 100, (1 - v) * 100]; }; convert.hwb.hcg = function (hwb) { const w = hwb[1] / 100; const b = hwb[2] / 100; const v = 1 - b; const c = v - w; let g = 0; if (c < 1) { g = (v - c) / (1 - c); } return [hwb[0], c * 100, g * 100]; }; convert.apple.rgb = function (apple) { return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; }; convert.rgb.apple = function (rgb) { return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; }; convert.gray.rgb = function (args) { return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; }; convert.gray.hsl = function (args) { return [0, 0, args[0]]; }; convert.gray.hsv = convert.gray.hsl; convert.gray.hwb = function (gray) { return [0, 100, gray[0]]; }; convert.gray.cmyk = function (gray) { return [0, 0, 0, gray[0]]; }; convert.gray.lab = function (gray) { return [gray[0], 0, 0]; }; convert.gray.hex = function (gray) { const val = Math.round(gray[0] / 100 * 255) & 0xFF; const integer = (val << 16) + (val << 8) + val; const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.rgb.gray = function (rgb) { const val = (rgb[0] + rgb[1] + rgb[2]) / 3; return [val / 255 * 100]; }; node_modules/color-convert/index.js 0000755 00000003254 15077334362 0013503 0 ustar 00 const conversions = require('./conversions'); const route = require('./route'); const convert = {}; const models = Object.keys(conversions); function wrapRaw(fn) { const wrappedFn = function (...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } return fn(args); }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } function wrapRounded(fn) { const wrappedFn = function (...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } const result = fn(args); // We're assuming the result is an array here. // see notice in conversions.js; don't use box types // in conversion functions. if (typeof result === 'object') { for (let len = result.length, i = 0; i < len; i++) { result[i] = Math.round(result[i]); } } return result; }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } models.forEach(fromModel => { convert[fromModel] = {}; Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); const routes = route(fromModel); const routeModels = Object.keys(routes); routeModels.forEach(toModel => { const fn = routes[toModel]; convert[fromModel][toModel] = wrapRounded(fn); convert[fromModel][toModel].raw = wrapRaw(fn); }); }); module.exports = convert; node_modules/color-name/README.md 0000755 00000000600 15077334362 0012545 0 ustar 00 A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. [](https://nodei.co/npm/color-name/) ```js var colors = require('color-name'); colors.red //[255,0,0] ``` <a href="LICENSE"><img src="https://upload.wikimedia.org/wikipedia/commons/0/0c/MIT_logo.svg" width="120"/></a> node_modules/color-name/LICENSE 0000755 00000002075 15077334362 0012303 0 ustar 00 The MIT License (MIT) Copyright (c) 2015 Dmitry Ivanov 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. node_modules/color-name/package.json 0000755 00000001137 15077334362 0013562 0 ustar 00 { "name": "color-name", "version": "1.1.4", "description": "A list of color names and its values", "main": "index.js", "files": [ "index.js" ], "scripts": { "test": "node test.js" }, "repository": { "type": "git", "url": "git@github.com:colorjs/color-name.git" }, "keywords": [ "color-name", "color", "color-keyword", "keyword" ], "author": "DY <dfcreative@gmail.com>", "license": "MIT", "bugs": { "url": "https://github.com/colorjs/color-name/issues" }, "homepage": "https://github.com/colorjs/color-name" } node_modules/color-name/index.js 0000755 00000011011 15077334362 0012731 0 ustar 00 'use strict' module.exports = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; node_modules/supports-color/license 0000755 00000002125 15077334362 0013616 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/supports-color/readme.md 0000755 00000004366 15077334362 0014041 0 ustar 00 # supports-color [](https://travis-ci.org/chalk/supports-color) > Detect whether a terminal supports color ## Install ``` $ npm install supports-color ``` ## Usage ```js const supportsColor = require('supports-color'); if (supportsColor.stdout) { console.log('Terminal stdout supports color'); } if (supportsColor.stdout.has256) { console.log('Terminal stdout supports 256 colors'); } if (supportsColor.stderr.has16m) { console.log('Terminal stderr supports 16 million colors (truecolor)'); } ``` ## API Returns an `Object` with a `stdout` and `stderr` property for testing either streams. Each property is an `Object`, or `false` if color is not supported. The `stdout`/`stderr` objects specifies a level of support for color through a `.level` property and a corresponding flag: - `.level = 1` and `.hasBasic = true`: Basic color support (16 colors) - `.level = 2` and `.has256 = true`: 256 color support - `.level = 3` and `.has16m = true`: Truecolor support (16 million colors) ## Info It obeys the `--color` and `--no-color` CLI flags. 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. ## Related - [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module - [chalk](https://github.com/chalk/chalk) - Terminal string styling done right ## Maintainers - [Sindre Sorhus](https://github.com/sindresorhus) - [Josh Junon](https://github.com/qix-) --- <div align="center"> <b> <a href="https://tidelift.com/subscription/pkg/npm-supports-color?utm_source=npm-supports-color&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a> </b> <br> <sub> Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies. </sub> </div> --- node_modules/supports-color/package.json 0000755 00000001461 15077334362 0014541 0 ustar 00 { "name": "supports-color", "version": "7.2.0", "description": "Detect whether a terminal supports color", "license": "MIT", "repository": "chalk/supports-color", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "engines": { "node": ">=8" }, "scripts": { "test": "xo && ava" }, "files": [ "index.js", "browser.js" ], "keywords": [ "color", "colour", "colors", "terminal", "console", "cli", "ansi", "styles", "tty", "rgb", "256", "shell", "xterm", "command-line", "support", "supports", "capability", "detect", "truecolor", "16m" ], "dependencies": { "has-flag": "^4.0.0" }, "devDependencies": { "ava": "^1.4.1", "import-fresh": "^3.0.0", "xo": "^0.24.0" }, "browser": "browser.js" } node_modules/supports-color/browser.js 0000755 00000000103 15077334362 0014264 0 ustar 00 'use strict'; module.exports = { stdout: false, stderr: false }; node_modules/supports-color/index.js 0000755 00000005274 15077334362 0013726 0 ustar 00 'use strict'; const os = require('os'); const tty = require('tty'); const hasFlag = require('has-flag'); const {env} = process; let forceColor; if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never')) { forceColor = 0; } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { forceColor = 1; } if ('FORCE_COLOR' in env) { if (env.FORCE_COLOR === 'true') { forceColor = 1; } else if (env.FORCE_COLOR === 'false') { forceColor = 0; } else { forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(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) { if (forceColor === 0) { return 0; } if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } 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]) >= 10586 ) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].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 ('TERM_PROGRAM' in env) { const version = 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; } function getSupportLevel(stream) { const level = supportsColor(stream, stream && stream.isTTY); return translateLevel(level); } module.exports = { supportsColor: getSupportLevel, stdout: translateLevel(supportsColor(true, tty.isatty(1))), stderr: translateLevel(supportsColor(true, tty.isatty(2))) }; node_modules/chalk/license 0000755 00000002125 15077334362 0011665 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/chalk/readme.md 0000755 00000032065 15077334362 0012105 0 ustar 00 <h1 align="center"> <br> <br> <img width="320" src="media/logo.svg" alt="Chalk"> <br> <br> <br> </h1> > Terminal string styling done right [](https://travis-ci.org/chalk/chalk) [](https://coveralls.io/github/chalk/chalk?branch=master) [](https://www.npmjs.com/package/chalk?activeTab=dependents) [](https://www.npmjs.com/package/chalk) [](https://www.youtube.com/watch?v=9auOCbH5Ns4) [](https://github.com/xojs/xo)  [](https://repl.it/github/chalk/chalk) <img src="https://cdn.jsdelivr.net/gh/chalk/ansi-styles@8261697c95bf34b6c7767e2cbe9941a851d59385/screenshot.svg" width="900"> <br> --- <div align="center"> <p> <p> <sup> Sindre Sorhus' open source work is supported by the community on <a href="https://github.com/sponsors/sindresorhus">GitHub Sponsors</a> and <a href="https://stakes.social/0x44d871aebF0126Bf646753E2C976Aa7e68A66c15">Dev</a> </sup> </p> <sup>Special thanks to:</sup> <br> <br> <a href="https://standardresume.co/tech"> <img src="https://sindresorhus.com/assets/thanks/standard-resume-logo.svg" width="160"/> </a> <br> <br> <a href="https://retool.com/?utm_campaign=sindresorhus"> <img src="https://sindresorhus.com/assets/thanks/retool-logo.svg" width="230"/> </a> <br> <br> <a href="https://doppler.com/?utm_campaign=github_repo&utm_medium=referral&utm_content=chalk&utm_source=github"> <div> <img src="https://dashboard.doppler.com/imgs/logo-long.svg" width="240" alt="Doppler"> </div> <b>All your environment variables, in one place</b> <div> <span>Stop struggling with scattered API keys, hacking together home-brewed tools,</span> <br> <span>and avoiding access controls. Keep your team and servers in sync with Doppler.</span> </div> </a> <br> <a href="https://uibakery.io/?utm_source=chalk&utm_medium=sponsor&utm_campaign=github"> <div> <img src="https://sindresorhus.com/assets/thanks/uibakery-logo.jpg" width="270" alt="UI Bakery"> </div> </a> </p> </div> --- <br> ## Highlights - Expressive API - Highly performant - Ability to nest styles - [256/Truecolor color support](#256-and-truecolor-color-support) - Auto-detects color support - Doesn't extend `String.prototype` - Clean and focused - Actively maintained - [Used by ~50,000 packages](https://www.npmjs.com/browse/depended/chalk) as of January 1, 2020 ## Install ```console $ npm install chalk ``` ## Usage ```js const chalk = require('chalk'); console.log(chalk.blue('Hello world!')); ``` Chalk comes with an easy to use composable API where you just chain and nest the styles you want. ```js const chalk = require('chalk'); const log = console.log; // Combine styled and normal strings log(chalk.blue('Hello') + ' World' + chalk.red('!')); // Compose multiple styles using the chainable API log(chalk.blue.bgRed.bold('Hello world!')); // Pass in multiple arguments log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz')); // Nest styles log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!')); // Nest styles of the same type even (color, underline, background) log(chalk.green( 'I am a green line ' + chalk.blue.underline.bold('with a blue substring') + ' that becomes green again!' )); // ES2015 template literal log(` CPU: ${chalk.red('90%')} RAM: ${chalk.green('40%')} DISK: ${chalk.yellow('70%')} `); // ES2015 tagged template literal log(chalk` CPU: {red ${cpu.totalPercent}%} RAM: {green ${ram.used / ram.total * 100}%} DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%} `); // Use RGB colors in terminal emulators that support it. log(chalk.keyword('orange')('Yay for orange colored text!')); log(chalk.rgb(123, 45, 67).underline('Underlined reddish color')); log(chalk.hex('#DEADED').bold('Bold gray!')); ``` Easily define your own themes: ```js const chalk = require('chalk'); const error = chalk.bold.red; const warning = chalk.keyword('orange'); console.log(error('Error!')); console.log(warning('Warning!')); ``` Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args): ```js const name = 'Sindre'; console.log(chalk.green('Hello %s'), name); //=> 'Hello Sindre' ``` ## API ### chalk.`<style>[.<style>...](string, [string...])` Example: `chalk.red.bold.underline('Hello', 'world');` Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`. Multiple arguments will be separated by space. ### chalk.level Specifies the level of color support. Color support is automatically detected, but you can override it by setting the `level` property. You should however only do this in your own code as it applies globally to all Chalk consumers. If you need to change this in a reusable module, create a new instance: ```js const ctx = new chalk.Instance({level: 0}); ``` | Level | Description | | :---: | :--- | | `0` | All colors disabled | | `1` | Basic color support (16 colors) | | `2` | 256 color support | | `3` | Truecolor support (16 million colors) | ### chalk.supportsColor Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience. Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks. Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively. ### chalk.stderr and chalk.stderr.supportsColor `chalk.stderr` contains a separate instance configured with color support detected for `stderr` stream instead of `stdout`. Override rules from `chalk.supportsColor` apply to this too. `chalk.stderr.supportsColor` is exposed for convenience. ## Styles ### Modifiers - `reset` - Resets the current color chain. - `bold` - Make text bold. - `dim` - Emitting only a small amount of light. - `italic` - Make text italic. *(Not widely supported)* - `underline` - Make text underline. *(Not widely supported)* - `inverse`- Inverse background and foreground colors. - `hidden` - Prints the text, but makes it invisible. - `strikethrough` - Puts a horizontal line through the center of the text. *(Not widely supported)* - `visible`- Prints the text only when Chalk has a color level > 0. Can be useful for things that are purely cosmetic. ### Colors - `black` - `red` - `green` - `yellow` - `blue` - `magenta` - `cyan` - `white` - `blackBright` (alias: `gray`, `grey`) - `redBright` - `greenBright` - `yellowBright` - `blueBright` - `magentaBright` - `cyanBright` - `whiteBright` ### Background colors - `bgBlack` - `bgRed` - `bgGreen` - `bgYellow` - `bgBlue` - `bgMagenta` - `bgCyan` - `bgWhite` - `bgBlackBright` (alias: `bgGray`, `bgGrey`) - `bgRedBright` - `bgGreenBright` - `bgYellowBright` - `bgBlueBright` - `bgMagentaBright` - `bgCyanBright` - `bgWhiteBright` ## Tagged template literal Chalk can be used as a [tagged template literal](https://exploringjs.com/es6/ch_template-literals.html#_tagged-template-literals). ```js const chalk = require('chalk'); const miles = 18; const calculateFeet = miles => miles * 5280; console.log(chalk` There are {bold 5280 feet} in a mile. In {bold ${miles} miles}, there are {green.bold ${calculateFeet(miles)} feet}. `); ``` Blocks are delimited by an opening curly brace (`{`), a style, some content, and a closing curly brace (`}`). Template styles are chained exactly like normal Chalk styles. The following three statements are equivalent: ```js console.log(chalk.bold.rgb(10, 100, 200)('Hello!')); console.log(chalk.bold.rgb(10, 100, 200)`Hello!`); console.log(chalk`{bold.rgb(10,100,200) Hello!}`); ``` Note that function styles (`rgb()`, `hsl()`, `keyword()`, etc.) may not contain spaces between parameters. All interpolated values (`` chalk`${foo}` ``) are converted to strings via the `.toString()` method. All curly braces (`{` and `}`) in interpolated value strings are escaped. ## 256 and Truecolor color support Chalk supports 256 colors and [Truecolor](https://gist.github.com/XVilka/8346728) (16 million colors) on supported terminal apps. Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying `{level: n}` as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red). Examples: - `chalk.hex('#DEADED').underline('Hello, world!')` - `chalk.keyword('orange')('Some orange text')` - `chalk.rgb(15, 100, 204).inverse('Hello!')` Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `keyword` for foreground colors and `bgKeyword` for background colors). - `chalk.bgHex('#DEADED').underline('Hello, world!')` - `chalk.bgKeyword('orange')('Some orange text')` - `chalk.bgRgb(15, 100, 204).inverse('Hello!')` The following color models can be used: - [`rgb`](https://en.wikipedia.org/wiki/RGB_color_model) - Example: `chalk.rgb(255, 136, 0).bold('Orange!')` - [`hex`](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) - Example: `chalk.hex('#FF8800').bold('Orange!')` - [`keyword`](https://www.w3.org/wiki/CSS/Properties/color/keywords) (CSS keywords) - Example: `chalk.keyword('orange').bold('Orange!')` - [`hsl`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 100, 50).bold('Orange!')` - [`hsv`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsv(32, 100, 100).bold('Orange!')` - [`hwb`](https://en.wikipedia.org/wiki/HWB_color_model) - Example: `chalk.hwb(32, 0, 50).bold('Orange!')` - [`ansi`](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) - Example: `chalk.ansi(31).bgAnsi(93)('red on yellowBright')` - [`ansi256`](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) - Example: `chalk.bgAnsi256(194)('Honeydew, more or less')` ## Windows If you're on Windows, do yourself a favor and use [Windows Terminal](https://github.com/microsoft/terminal) instead of `cmd.exe`. ## Origin story [colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68) and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative. ## chalk for enterprise Available as part of the Tidelift Subscription. The maintainers of chalk and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-chalk?utm_source=npm-chalk&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) ## Related - [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module - [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal - [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color - [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes - [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Strip ANSI escape codes from a stream - [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes - [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes - [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes - [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes - [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models - [chalk-animation](https://github.com/bokub/chalk-animation) - Animate strings in the terminal - [gradient-string](https://github.com/bokub/gradient-string) - Apply color gradients to strings - [chalk-pipe](https://github.com/LitoMore/chalk-pipe) - Create chalk style schemes with simpler style strings - [terminal-link](https://github.com/sindresorhus/terminal-link) - Create clickable links in the terminal ## Maintainers - [Sindre Sorhus](https://github.com/sindresorhus) - [Josh Junon](https://github.com/qix-) node_modules/chalk/index.d.ts 0000755 00000021303 15077334362 0012220 0 ustar 00 /** Basic foreground colors. [More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) */ declare type ForegroundColor = | 'black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white' | 'gray' | 'grey' | 'blackBright' | 'redBright' | 'greenBright' | 'yellowBright' | 'blueBright' | 'magentaBright' | 'cyanBright' | 'whiteBright'; /** Basic background colors. [More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) */ declare type BackgroundColor = | 'bgBlack' | 'bgRed' | 'bgGreen' | 'bgYellow' | 'bgBlue' | 'bgMagenta' | 'bgCyan' | 'bgWhite' | 'bgGray' | 'bgGrey' | 'bgBlackBright' | 'bgRedBright' | 'bgGreenBright' | 'bgYellowBright' | 'bgBlueBright' | 'bgMagentaBright' | 'bgCyanBright' | 'bgWhiteBright'; /** Basic colors. [More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) */ declare type Color = ForegroundColor | BackgroundColor; declare type Modifiers = | 'reset' | 'bold' | 'dim' | 'italic' | 'underline' | 'inverse' | 'hidden' | 'strikethrough' | 'visible'; declare namespace chalk { /** Levels: - `0` - All colors disabled. - `1` - Basic 16 colors support. - `2` - ANSI 256 colors support. - `3` - Truecolor 16 million colors support. */ type Level = 0 | 1 | 2 | 3; interface Options { /** Specify the color support for Chalk. By default, color support is automatically detected based on the environment. Levels: - `0` - All colors disabled. - `1` - Basic 16 colors support. - `2` - ANSI 256 colors support. - `3` - Truecolor 16 million colors support. */ level?: Level; } /** Return a new Chalk instance. */ type Instance = new (options?: Options) => Chalk; /** Detect whether the terminal supports color. */ interface ColorSupport { /** The color level used by Chalk. */ level: Level; /** Return whether Chalk supports basic 16 colors. */ hasBasic: boolean; /** Return whether Chalk supports ANSI 256 colors. */ has256: boolean; /** Return whether Chalk supports Truecolor 16 million colors. */ has16m: boolean; } interface ChalkFunction { /** Use a template string. @remarks Template literals are unsupported for nested calls (see [issue #341](https://github.com/chalk/chalk/issues/341)) @example ``` import chalk = require('chalk'); log(chalk` CPU: {red ${cpu.totalPercent}%} RAM: {green ${ram.used / ram.total * 100}%} DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%} `); ``` @example ``` import chalk = require('chalk'); log(chalk.red.bgBlack`2 + 3 = {bold ${2 + 3}}`) ``` */ (text: TemplateStringsArray, ...placeholders: unknown[]): string; (...text: unknown[]): string; } interface Chalk extends ChalkFunction { /** Return a new Chalk instance. */ Instance: Instance; /** The color support for Chalk. By default, color support is automatically detected based on the environment. Levels: - `0` - All colors disabled. - `1` - Basic 16 colors support. - `2` - ANSI 256 colors support. - `3` - Truecolor 16 million colors support. */ level: Level; /** Use HEX value to set text color. @param color - Hexadecimal value representing the desired color. @example ``` import chalk = require('chalk'); chalk.hex('#DEADED'); ``` */ hex(color: string): Chalk; /** Use keyword color value to set text color. @param color - Keyword value representing the desired color. @example ``` import chalk = require('chalk'); chalk.keyword('orange'); ``` */ keyword(color: string): Chalk; /** Use RGB values to set text color. */ rgb(red: number, green: number, blue: number): Chalk; /** Use HSL values to set text color. */ hsl(hue: number, saturation: number, lightness: number): Chalk; /** Use HSV values to set text color. */ hsv(hue: number, saturation: number, value: number): Chalk; /** Use HWB values to set text color. */ hwb(hue: number, whiteness: number, blackness: number): Chalk; /** Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set text color. 30 <= code && code < 38 || 90 <= code && code < 98 For example, 31 for red, 91 for redBright. */ ansi(code: number): Chalk; /** Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color. */ ansi256(index: number): Chalk; /** Use HEX value to set background color. @param color - Hexadecimal value representing the desired color. @example ``` import chalk = require('chalk'); chalk.bgHex('#DEADED'); ``` */ bgHex(color: string): Chalk; /** Use keyword color value to set background color. @param color - Keyword value representing the desired color. @example ``` import chalk = require('chalk'); chalk.bgKeyword('orange'); ``` */ bgKeyword(color: string): Chalk; /** Use RGB values to set background color. */ bgRgb(red: number, green: number, blue: number): Chalk; /** Use HSL values to set background color. */ bgHsl(hue: number, saturation: number, lightness: number): Chalk; /** Use HSV values to set background color. */ bgHsv(hue: number, saturation: number, value: number): Chalk; /** Use HWB values to set background color. */ bgHwb(hue: number, whiteness: number, blackness: number): Chalk; /** Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set background color. 30 <= code && code < 38 || 90 <= code && code < 98 For example, 31 for red, 91 for redBright. Use the foreground code, not the background code (for example, not 41, nor 101). */ bgAnsi(code: number): Chalk; /** Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color. */ bgAnsi256(index: number): Chalk; /** Modifier: Resets the current color chain. */ readonly reset: Chalk; /** Modifier: Make text bold. */ readonly bold: Chalk; /** Modifier: Emitting only a small amount of light. */ readonly dim: Chalk; /** Modifier: Make text italic. (Not widely supported) */ readonly italic: Chalk; /** Modifier: Make text underline. (Not widely supported) */ readonly underline: Chalk; /** Modifier: Inverse background and foreground colors. */ readonly inverse: Chalk; /** Modifier: Prints the text, but makes it invisible. */ readonly hidden: Chalk; /** Modifier: Puts a horizontal line through the center of the text. (Not widely supported) */ readonly strikethrough: Chalk; /** Modifier: Prints the text only when Chalk has a color support level > 0. Can be useful for things that are purely cosmetic. */ readonly visible: Chalk; readonly black: Chalk; readonly red: Chalk; readonly green: Chalk; readonly yellow: Chalk; readonly blue: Chalk; readonly magenta: Chalk; readonly cyan: Chalk; readonly white: Chalk; /* Alias for `blackBright`. */ readonly gray: Chalk; /* Alias for `blackBright`. */ readonly grey: Chalk; readonly blackBright: Chalk; readonly redBright: Chalk; readonly greenBright: Chalk; readonly yellowBright: Chalk; readonly blueBright: Chalk; readonly magentaBright: Chalk; readonly cyanBright: Chalk; readonly whiteBright: Chalk; readonly bgBlack: Chalk; readonly bgRed: Chalk; readonly bgGreen: Chalk; readonly bgYellow: Chalk; readonly bgBlue: Chalk; readonly bgMagenta: Chalk; readonly bgCyan: Chalk; readonly bgWhite: Chalk; /* Alias for `bgBlackBright`. */ readonly bgGray: Chalk; /* Alias for `bgBlackBright`. */ readonly bgGrey: Chalk; readonly bgBlackBright: Chalk; readonly bgRedBright: Chalk; readonly bgGreenBright: Chalk; readonly bgYellowBright: Chalk; readonly bgBlueBright: Chalk; readonly bgMagentaBright: Chalk; readonly bgCyanBright: Chalk; readonly bgWhiteBright: Chalk; } } /** Main Chalk object that allows to chain styles together. Call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`. */ declare const chalk: chalk.Chalk & chalk.ChalkFunction & { supportsColor: chalk.ColorSupport | false; Level: chalk.Level; Color: Color; ForegroundColor: ForegroundColor; BackgroundColor: BackgroundColor; Modifiers: Modifiers; stderr: chalk.Chalk & {supportsColor: chalk.ColorSupport | false}; }; export = chalk; node_modules/chalk/package.json 0000755 00000002255 15077334362 0012612 0 ustar 00 { "name": "chalk", "version": "4.1.2", "description": "Terminal string styling done right", "license": "MIT", "repository": "chalk/chalk", "funding": "https://github.com/chalk/chalk?sponsor=1", "main": "source", "engines": { "node": ">=10" }, "scripts": { "test": "xo && nyc ava && tsd", "bench": "matcha benchmark.js" }, "files": [ "source", "index.d.ts" ], "keywords": [ "color", "colour", "colors", "terminal", "console", "cli", "string", "str", "ansi", "style", "styles", "tty", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" }, "devDependencies": { "ava": "^2.4.0", "coveralls": "^3.0.7", "execa": "^4.0.0", "import-fresh": "^3.1.0", "matcha": "^0.7.0", "nyc": "^15.0.0", "resolve-from": "^5.0.0", "tsd": "^0.7.4", "xo": "^0.28.2" }, "xo": { "rules": { "unicorn/prefer-string-slice": "off", "unicorn/prefer-includes": "off", "@typescript-eslint/member-ordering": "off", "no-redeclare": "off", "unicorn/string-content": "off", "unicorn/better-regex": "off" } } } node_modules/chalk/source/templates.js 0000755 00000006447 15077334362 0014167 0 ustar 00 'use strict'; const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; const ESCAPES = new Map([ ['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007'] ]); function unescape(c) { const u = c[0] === 'u'; const bracket = c[1] === '{'; if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { return String.fromCharCode(parseInt(c.slice(1), 16)); } if (u && bracket) { return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); } return ESCAPES.get(c) || c; } function parseArguments(name, arguments_) { const results = []; const chunks = arguments_.trim().split(/\s*,\s*/g); let matches; for (const chunk of chunks) { const number = Number(chunk); if (!Number.isNaN(number)) { results.push(number); } else if ((matches = chunk.match(STRING_REGEX))) { results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character)); } else { throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); } } return results; } function parseStyle(style) { STYLE_REGEX.lastIndex = 0; const results = []; let matches; while ((matches = STYLE_REGEX.exec(style)) !== null) { const name = matches[1]; if (matches[2]) { const args = parseArguments(name, matches[2]); results.push([name].concat(args)); } else { results.push([name]); } } return results; } function buildStyle(chalk, styles) { const enabled = {}; for (const layer of styles) { for (const style of layer.styles) { enabled[style[0]] = layer.inverse ? null : style.slice(1); } } let current = chalk; for (const [styleName, styles] of Object.entries(enabled)) { if (!Array.isArray(styles)) { continue; } if (!(styleName in current)) { throw new Error(`Unknown Chalk style: ${styleName}`); } current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; } return current; } module.exports = (chalk, temporary) => { const styles = []; const chunks = []; let chunk = []; // eslint-disable-next-line max-params temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => { if (escapeCharacter) { chunk.push(unescape(escapeCharacter)); } else if (style) { const string = chunk.join(''); chunk = []; chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string)); styles.push({inverse, styles: parseStyle(style)}); } else if (close) { if (styles.length === 0) { throw new Error('Found extraneous } in Chalk template literal'); } chunks.push(buildStyle(chalk, styles)(chunk.join(''))); chunk = []; styles.pop(); } else { chunk.push(character); } }); chunks.push(chunk.join('')); if (styles.length > 0) { const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; throw new Error(errMessage); } return chunks.join(''); }; node_modules/chalk/source/util.js 0000755 00000002013 15077334362 0013127 0 ustar 00 'use strict'; const stringReplaceAll = (string, substring, replacer) => { let index = string.indexOf(substring); if (index === -1) { return string; } const substringLength = substring.length; let endIndex = 0; let returnValue = ''; do { returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; endIndex = index + substringLength; index = string.indexOf(substring, endIndex); } while (index !== -1); returnValue += string.substr(endIndex); return returnValue; }; const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { let endIndex = 0; let returnValue = ''; do { const gotCR = string[index - 1] === '\r'; returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; endIndex = index + 1; index = string.indexOf('\n', endIndex); } while (index !== -1); returnValue += string.substr(endIndex); return returnValue; }; module.exports = { stringReplaceAll, stringEncaseCRLFWithFirstIndex }; node_modules/chalk/source/index.js 0000755 00000013673 15077334362 0013277 0 ustar 00 'use strict'; const ansiStyles = require('ansi-styles'); const {stdout: stdoutColor, stderr: stderrColor} = require('supports-color'); const { stringReplaceAll, stringEncaseCRLFWithFirstIndex } = require('./util'); const {isArray} = Array; // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = [ 'ansi', 'ansi', 'ansi256', 'ansi16m' ]; const styles = Object.create(null); const applyOptions = (object, options = {}) => { if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { throw new Error('The `level` option should be an integer from 0 to 3'); } // Detect level if not set manually const colorLevel = stdoutColor ? stdoutColor.level : 0; object.level = options.level === undefined ? colorLevel : options.level; }; class ChalkClass { constructor(options) { // eslint-disable-next-line no-constructor-return return chalkFactory(options); } } const chalkFactory = options => { const chalk = {}; applyOptions(chalk, options); chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); Object.setPrototypeOf(chalk, Chalk.prototype); Object.setPrototypeOf(chalk.template, chalk); chalk.template.constructor = () => { throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); }; chalk.template.Instance = ChalkClass; return chalk.template; }; function Chalk(options) { return chalkFactory(options); } for (const [styleName, style] of Object.entries(ansiStyles)) { styles[styleName] = { get() { const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); Object.defineProperty(this, styleName, {value: builder}); return builder; } }; } styles.visible = { get() { const builder = createBuilder(this, this._styler, true); Object.defineProperty(this, 'visible', {value: builder}); return builder; } }; const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; for (const model of usedModels) { styles[model] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler); return createBuilder(this, styler, this._isEmpty); }; } }; } for (const model of usedModels) { const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler); return createBuilder(this, styler, this._isEmpty); }; } }; } const proto = Object.defineProperties(() => {}, { ...styles, level: { enumerable: true, get() { return this._generator.level; }, set(level) { this._generator.level = level; } } }); const createStyler = (open, close, parent) => { let openAll; let closeAll; if (parent === undefined) { openAll = open; closeAll = close; } else { openAll = parent.openAll + open; closeAll = close + parent.closeAll; } return { open, close, openAll, closeAll, parent }; }; const createBuilder = (self, _styler, _isEmpty) => { const builder = (...arguments_) => { if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) { // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` return applyStyle(builder, chalkTag(builder, ...arguments_)); } // Single argument is hot path, implicit coercion is faster than anything // eslint-disable-next-line no-implicit-coercion return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); }; // We alter the prototype because we must return a function, but there is // no way to create a function with a different prototype Object.setPrototypeOf(builder, proto); builder._generator = self; builder._styler = _styler; builder._isEmpty = _isEmpty; return builder; }; const applyStyle = (self, string) => { if (self.level <= 0 || !string) { return self._isEmpty ? '' : string; } let styler = self._styler; if (styler === undefined) { return string; } const {openAll, closeAll} = styler; if (string.indexOf('\u001B') !== -1) { while (styler !== undefined) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. string = stringReplaceAll(string, styler.close, styler.open); styler = styler.parent; } } // We can move both next actions out of loop, because remaining actions in loop won't have // any/visible effect on parts we add here. Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 const lfIndex = string.indexOf('\n'); if (lfIndex !== -1) { string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); } return openAll + string + closeAll; }; let template; const chalkTag = (chalk, ...strings) => { const [firstString] = strings; if (!isArray(firstString) || !isArray(firstString.raw)) { // If chalk() was called by itself or with a string, // return the string itself as a string. return strings.join(' '); } const arguments_ = strings.slice(1); const parts = [firstString.raw[0]]; for (let i = 1; i < firstString.length; i++) { parts.push( String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i]) ); } if (template === undefined) { template = require('./templates'); } return template(chalk, parts.join('')); }; Object.defineProperties(Chalk.prototype, styles); const chalk = Chalk(); // eslint-disable-line new-cap chalk.supportsColor = stdoutColor; chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap chalk.stderr.supportsColor = stderrColor; module.exports = chalk; node_modules/ansi-styles/license 0000755 00000002125 15077334362 0013056 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/ansi-styles/readme.md 0000755 00000010347 15077334362 0013275 0 ustar 00 # ansi-styles [](https://travis-ci.org/chalk/ansi-styles) > [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings. <img src="screenshot.svg" width="900"> ## Install ``` $ npm install ansi-styles ``` ## Usage ```js const style = require('ansi-styles'); console.log(`${style.green.open}Hello world!${style.green.close}`); // Color conversion between 16/256/truecolor // NOTE: If conversion goes to 16 colors or 256 colors, the original color // may be degraded to fit that color palette. This means terminals // that do not support 16 million colors will best-match the // original color. console.log(style.bgColor.ansi.hsl(120, 80, 72) + 'Hello world!' + style.bgColor.close); console.log(style.color.ansi256.rgb(199, 20, 250) + 'Hello world!' + style.color.close); console.log(style.color.ansi16m.hex('#abcdef') + 'Hello world!' + style.color.close); ``` ## API Each style has an `open` and `close` property. ## Styles ### Modifiers - `reset` - `bold` - `dim` - `italic` *(Not widely supported)* - `underline` - `inverse` - `hidden` - `strikethrough` *(Not widely supported)* ### Colors - `black` - `red` - `green` - `yellow` - `blue` - `magenta` - `cyan` - `white` - `blackBright` (alias: `gray`, `grey`) - `redBright` - `greenBright` - `yellowBright` - `blueBright` - `magentaBright` - `cyanBright` - `whiteBright` ### Background colors - `bgBlack` - `bgRed` - `bgGreen` - `bgYellow` - `bgBlue` - `bgMagenta` - `bgCyan` - `bgWhite` - `bgBlackBright` (alias: `bgGray`, `bgGrey`) - `bgRedBright` - `bgGreenBright` - `bgYellowBright` - `bgBlueBright` - `bgMagentaBright` - `bgCyanBright` - `bgWhiteBright` ## Advanced usage By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. - `style.modifier` - `style.color` - `style.bgColor` ###### Example ```js console.log(style.color.green.open); ``` Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `style.codes`, which returns a `Map` with the open codes as keys and close codes as values. ###### Example ```js console.log(style.codes.get(36)); //=> 39 ``` ## [256 / 16 million (TrueColor) support](https://gist.github.com/XVilka/8346728) `ansi-styles` uses the [`color-convert`](https://github.com/Qix-/color-convert) package to allow for converting between various colors and ANSI escapes, with support for 256 and 16 million colors. The following color spaces from `color-convert` are supported: - `rgb` - `hex` - `keyword` - `hsl` - `hsv` - `hwb` - `ansi` - `ansi256` To use these, call the associated conversion function with the intended output, for example: ```js style.color.ansi.rgb(100, 200, 15); // RGB to 16 color ansi foreground code style.bgColor.ansi.rgb(100, 200, 15); // RGB to 16 color ansi background code style.color.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code style.bgColor.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code style.color.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color foreground code style.bgColor.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color background code ``` ## Related - [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal ## Maintainers - [Sindre Sorhus](https://github.com/sindresorhus) - [Josh Junon](https://github.com/qix-) ## For enterprise Available as part of the Tidelift Subscription. The maintainers of `ansi-styles` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-ansi-styles?utm_source=npm-ansi-styles&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) node_modules/ansi-styles/index.d.ts 0000755 00000014315 15077334362 0013416 0 ustar 00 declare type CSSColor = | 'aliceblue' | 'antiquewhite' | 'aqua' | 'aquamarine' | 'azure' | 'beige' | 'bisque' | 'black' | 'blanchedalmond' | 'blue' | 'blueviolet' | 'brown' | 'burlywood' | 'cadetblue' | 'chartreuse' | 'chocolate' | 'coral' | 'cornflowerblue' | 'cornsilk' | 'crimson' | 'cyan' | 'darkblue' | 'darkcyan' | 'darkgoldenrod' | 'darkgray' | 'darkgreen' | 'darkgrey' | 'darkkhaki' | 'darkmagenta' | 'darkolivegreen' | 'darkorange' | 'darkorchid' | 'darkred' | 'darksalmon' | 'darkseagreen' | 'darkslateblue' | 'darkslategray' | 'darkslategrey' | 'darkturquoise' | 'darkviolet' | 'deeppink' | 'deepskyblue' | 'dimgray' | 'dimgrey' | 'dodgerblue' | 'firebrick' | 'floralwhite' | 'forestgreen' | 'fuchsia' | 'gainsboro' | 'ghostwhite' | 'gold' | 'goldenrod' | 'gray' | 'green' | 'greenyellow' | 'grey' | 'honeydew' | 'hotpink' | 'indianred' | 'indigo' | 'ivory' | 'khaki' | 'lavender' | 'lavenderblush' | 'lawngreen' | 'lemonchiffon' | 'lightblue' | 'lightcoral' | 'lightcyan' | 'lightgoldenrodyellow' | 'lightgray' | 'lightgreen' | 'lightgrey' | 'lightpink' | 'lightsalmon' | 'lightseagreen' | 'lightskyblue' | 'lightslategray' | 'lightslategrey' | 'lightsteelblue' | 'lightyellow' | 'lime' | 'limegreen' | 'linen' | 'magenta' | 'maroon' | 'mediumaquamarine' | 'mediumblue' | 'mediumorchid' | 'mediumpurple' | 'mediumseagreen' | 'mediumslateblue' | 'mediumspringgreen' | 'mediumturquoise' | 'mediumvioletred' | 'midnightblue' | 'mintcream' | 'mistyrose' | 'moccasin' | 'navajowhite' | 'navy' | 'oldlace' | 'olive' | 'olivedrab' | 'orange' | 'orangered' | 'orchid' | 'palegoldenrod' | 'palegreen' | 'paleturquoise' | 'palevioletred' | 'papayawhip' | 'peachpuff' | 'peru' | 'pink' | 'plum' | 'powderblue' | 'purple' | 'rebeccapurple' | 'red' | 'rosybrown' | 'royalblue' | 'saddlebrown' | 'salmon' | 'sandybrown' | 'seagreen' | 'seashell' | 'sienna' | 'silver' | 'skyblue' | 'slateblue' | 'slategray' | 'slategrey' | 'snow' | 'springgreen' | 'steelblue' | 'tan' | 'teal' | 'thistle' | 'tomato' | 'turquoise' | 'violet' | 'wheat' | 'white' | 'whitesmoke' | 'yellow' | 'yellowgreen'; declare namespace ansiStyles { interface ColorConvert { /** The RGB color space. @param red - (`0`-`255`) @param green - (`0`-`255`) @param blue - (`0`-`255`) */ rgb(red: number, green: number, blue: number): string; /** The RGB HEX color space. @param hex - A hexadecimal string containing RGB data. */ hex(hex: string): string; /** @param keyword - A CSS color name. */ keyword(keyword: CSSColor): string; /** The HSL color space. @param hue - (`0`-`360`) @param saturation - (`0`-`100`) @param lightness - (`0`-`100`) */ hsl(hue: number, saturation: number, lightness: number): string; /** The HSV color space. @param hue - (`0`-`360`) @param saturation - (`0`-`100`) @param value - (`0`-`100`) */ hsv(hue: number, saturation: number, value: number): string; /** The HSV color space. @param hue - (`0`-`360`) @param whiteness - (`0`-`100`) @param blackness - (`0`-`100`) */ hwb(hue: number, whiteness: number, blackness: number): string; /** Use a [4-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4-bit) to set text color. */ ansi(ansi: number): string; /** Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color. */ ansi256(ansi: number): string; } interface CSPair { /** The ANSI terminal control sequence for starting this style. */ readonly open: string; /** The ANSI terminal control sequence for ending this style. */ readonly close: string; } interface ColorBase { readonly ansi: ColorConvert; readonly ansi256: ColorConvert; readonly ansi16m: ColorConvert; /** The ANSI terminal control sequence for ending this color. */ readonly close: string; } 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; /** 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; } 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; } 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; } } declare const ansiStyles: { readonly modifier: ansiStyles.Modifier; readonly color: ansiStyles.ForegroundColor & ansiStyles.ColorBase; readonly bgColor: ansiStyles.BackgroundColor & ansiStyles.ColorBase; readonly codes: ReadonlyMap<number, number>; } & ansiStyles.BackgroundColor & ansiStyles.ForegroundColor & ansiStyles.Modifier; export = ansiStyles; node_modules/ansi-styles/package.json 0000755 00000002036 15077334362 0014000 0 ustar 00 { "name": "ansi-styles", "version": "4.3.0", "description": "ANSI escape codes for styling strings in the terminal", "license": "MIT", "repository": "chalk/ansi-styles", "funding": "https://github.com/chalk/ansi-styles?sponsor=1", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "engines": { "node": ">=8" }, "scripts": { "test": "xo && ava && tsd", "screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "dependencies": { "color-convert": "^2.0.1" }, "devDependencies": { "@types/color-convert": "^1.9.0", "ava": "^2.3.0", "svg-term-cli": "^2.1.1", "tsd": "^0.11.0", "xo": "^0.25.3" } } node_modules/ansi-styles/index.js 0000755 00000010053 15077334362 0013155 0 ustar 00 'use strict'; const wrapAnsi16 = (fn, offset) => (...args) => { const code = fn(...args); return `\u001B[${code + offset}m`; }; const wrapAnsi256 = (fn, offset) => (...args) => { const code = fn(...args); return `\u001B[${38 + offset};5;${code}m`; }; const wrapAnsi16m = (fn, offset) => (...args) => { const rgb = fn(...args); return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; }; const ansi2ansi = n => n; const rgb2rgb = (r, g, b) => [r, g, b]; const setLazyProperty = (object, property, get) => { Object.defineProperty(object, property, { get: () => { const value = get(); Object.defineProperty(object, property, { value, enumerable: true, configurable: true }); return value; }, enumerable: true, configurable: true }); }; /** @type {typeof import('color-convert')} */ let colorConvert; const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { if (colorConvert === undefined) { colorConvert = require('color-convert'); } const offset = isBackground ? 10 : 0; const styles = {}; for (const [sourceSpace, suite] of Object.entries(colorConvert)) { const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; if (sourceSpace === targetSpace) { styles[name] = wrap(identity, offset); } else if (typeof suite === 'object') { styles[name] = wrap(suite[targetSpace], offset); } } return styles; }; function assembleStyles() { const codes = new Map(); 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], 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], 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], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; // Alias bright black as gray (and grey) styles.color.gray = styles.color.blackBright; styles.bgColor.bgGray = styles.bgColor.bgBlackBright; styles.color.grey = styles.color.blackBright; styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; 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'; setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); return styles; } // Make the export immutable Object.defineProperty(module, 'exports', { enumerable: true, get: assembleStyles }); node_modules/has-flag/license 0000755 00000002125 15077334362 0012265 0 ustar 00 MIT License Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node_modules/has-flag/readme.md 0000755 00000003100 15077334362 0012471 0 ustar 00 # has-flag [](https://travis-ci.org/sindresorhus/has-flag) > Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag Correctly stops looking after an `--` argument terminator. --- <div align="center"> <b> <a href="https://tidelift.com/subscription/pkg/npm-has-flag?utm_source=npm-has-flag&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a> </b> <br> <sub> Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies. </sub> </div> --- ## Install ``` $ npm install has-flag ``` ## Usage ```js // foo.js const hasFlag = require('has-flag'); hasFlag('unicorn'); //=> true hasFlag('--unicorn'); //=> true hasFlag('f'); //=> true hasFlag('-f'); //=> true hasFlag('foo=bar'); //=> true hasFlag('foo'); //=> false hasFlag('rainbow'); //=> false ``` ``` $ node foo.js -f --unicorn --foo=bar -- --rainbow ``` ## API ### hasFlag(flag, [argv]) Returns a boolean for whether the flag exists. #### flag Type: `string` CLI flag to look for. The `--` prefix is optional. #### argv Type: `string[]`<br> Default: `process.argv` CLI arguments. ## Security To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. ## License MIT © [Sindre Sorhus](https://sindresorhus.com) node_modules/has-flag/index.d.ts 0000755 00000001254 15077334362 0012623 0 ustar 00 /** Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag. @param flag - CLI flag to look for. The `--` prefix is optional. @param argv - CLI arguments. Default: `process.argv`. @returns Whether the flag exists. @example ``` // $ ts-node foo.ts -f --unicorn --foo=bar -- --rainbow // foo.ts import hasFlag = require('has-flag'); hasFlag('unicorn'); //=> true hasFlag('--unicorn'); //=> true hasFlag('f'); //=> true hasFlag('-f'); //=> true hasFlag('foo=bar'); //=> true hasFlag('foo'); //=> false hasFlag('rainbow'); //=> false ``` */ declare function hasFlag(flag: string, argv?: string[]): boolean; export = hasFlag; node_modules/has-flag/package.json 0000755 00000001270 15077334362 0013206 0 ustar 00 { "name": "has-flag", "version": "4.0.0", "description": "Check if argv has a specific flag", "license": "MIT", "repository": "sindresorhus/has-flag", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "engines": { "node": ">=8" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "has", "check", "detect", "contains", "find", "flag", "cli", "command-line", "argv", "process", "arg", "args", "argument", "arguments", "getopt", "minimist", "optimist" ], "devDependencies": { "ava": "^1.4.1", "tsd": "^0.7.2", "xo": "^0.24.0" } } node_modules/has-flag/index.js 0000755 00000000512 15077334362 0012363 0 ustar 00 'use strict'; module.exports = (flag, argv = 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); };
SAVE
CANCEL