6.16.146 • Published 9 months ago

@firanorg/voluptatem-culpa-iusto v6.16.146

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

@firanorg/voluptatem-culpa-iusto

npm

A JavaScript ANSI color/style management. ANSI parsing. ANSI to CSS. Small, clean, no dependencies.

npm install @firanorg/voluptatem-culpa-iusto

What For

Why Another One?

Other tools lack consistency, failing to solve a simple hierarchy problem:

require ('colors') // a popular color utility

console.log (('foo'.cyan + 'bar').red)

pic

WTF?! The bar word above should be rendered in red, but it's not! That sucks. It's because ANSI codes are linear, not hierarchical (as with XML/HTML). A special kind of magic is needed to make this work. Ansicolor does that magic for you:

require ('@firanorg/voluptatem-culpa-iusto').nice // .nice for unsafe String extensions

console.log (('foo'.cyan + 'bar').red)

pic

Nice!

Crash Course

Importing (as methods):

import { green, inverse, bgLightCyan, underline, dim } from '@firanorg/voluptatem-culpa-iusto'
const { green, inverse, bgLightCyan, underline, dim } = require ('@firanorg/voluptatem-culpa-iusto')

Usage:

console.log ('foo' + green (inverse (bgLightCyan ('bar')) + 'baz') + 'qux')
console.log (underline.bright.green ('foo' + dim.red.bgLightCyan ('bar'))) // method chaining

Importing (as object):

import { @firanorg/voluptatem-culpa-iusto, ParsedSpan } from '@firanorg/voluptatem-culpa-iusto' // along with type definitions
import @firanorg/voluptatem-culpa-iusto from '@firanorg/voluptatem-culpa-iusto'

Nice Mode (not recommended)

const ansi = require ('@firanorg/voluptatem-culpa-iusto').nice

The ('@firanorg/voluptatem-culpa-iusto').nice export defines styling APIs on the String prototype directly. It uses an ad-hoc DSL (sort of) for infix-style string coloring. The nice is convenient, but not safe, avoid using it in public modules, as it alters global objects, and that might cause potential hard-to-debug compatibility issues.

console.log ('foo'.red.bright + 'bar'.bgYellow.underline.dim)

Supported Styles

'foreground colors'
    .red.green.yellow.blue.magenta.cyan.white.darkGray.black
'light foreground colors'
    .lightRed.lightGreen.lightYellow.lightBlue.lightMagenta.lightCyan.lightGray
'background colors'
    .bgRed.bgGreen.bgYellow.bgBlue.bgMagenta.bgCyan.bgWhite.bgDarkGray.bgBlack
'light background colors'
    .bgLightRed.bgLightGreen.bgLightYellow.bgLightBlue.bgLightMagenta.bgLightCyan.bgLightGray
'styles'
    .bright.dim.italic.underline.inverse // your platform should support italic

You also can obtain all those style names (for reflection purposes):

const { names } = require ('@firanorg/voluptatem-culpa-iusto')

names // ['red', 'green', ...

Removing ANSI Styles From Strings

const { strip } = require ('@firanorg/voluptatem-culpa-iusto')

strip ('\u001b[0m\u001b[4m\u001b[42m\u001b[31mfoo\u001b[39m\u001b[49m\u001b[24mfoo\u001b[0m')) // 'foofoo'

Checking If Strings Contain ANSI Codes

const { isEscaped, green } = require ('@firanorg/voluptatem-culpa-iusto')

isEscaped ('text')         // false
isEscaped (green ('text')) // true

Converting to CSS/HTML

Inspection of ANSI styles in arbitrary strings is essential when implementing platform-agnostic logging — that piece of code is available under command line interface and in a browser as well. Here's an example of how you would parse a colored string into an array-like structure. That structure can be traversed later to build HTML/JSON/XML or any other markup/syntax.

const { parse } = require ('@firanorg/voluptatem-culpa-iusto')

const parsed = parse ('foo'.bgLightRed.bright.italic + 'bar'.red.dim)

The ansi.parse () method will return a pseudo-array of styled spans, you can iterate over it with a for ... of loop and convert it to an array with the spread operator (...). Also, there's the .spans property for obtaining the already-spread array directly:

assert.deepEqual (parsed.spans /* or [...parsed] */,

    [ { css: 'font-weight: bold;font-style: italic;background:rgba(255,51,0,1);',
        italic: true,
        bold: true,
        color: { bright: true },
        bgColor: { name: 'lightRed' },
        text: 'foo' },

      { css: 'color:rgba(204,0,0,0.5);',
        color: { name: 'red', dim: true },
        text: 'bar' } ])

Custom Color Themes

You can change default RGB values (won't work in terminals, affects only the ANSI→CSS transformation part):

const ansi = require ('@firanorg/voluptatem-culpa-iusto')

ansi.rgb = {

    black:        [0,     0,   0],    
    darkGray:     [100, 100, 100],
    lightGray:    [200, 200, 200],
    white:        [255, 255, 255],

    red:          [204,   0,   0],
    lightRed:     [255,  51,   0],
    
    green:        [0,   204,   0],
    lightGreen:   [51,  204,  51],
    
    yellow:       [204, 102,   0],
    lightYellow:  [255, 153,  51],
    
    blue:         [0,     0, 255],
    lightBlue:    [26,  140, 255],
    
    magenta:      [204,   0, 204],
    lightMagenta: [255,   0, 255],
    
    cyan:         [0,   153, 255],
    lightCyan:    [0,   204, 255],
}

Chrome DevTools Compatibility

Web browsers usually implement their own proprietary CSS-based color formats for console.log and most of them fail to display standard ANSI colors. Ansicolor offers you a helper method to convert ANSI-styled strings to browser-compatible argument lists acceptable by Chrome's console.log:

const { bgGreen, red, parse } = require ('@firanorg/voluptatem-culpa-iusto')

const string = 'foo' + bgGreen (red.underline.bright.inverse ('bar') + 'baz')
const parsed = parse (string)

console.log (...parsed.asChromeConsoleLogArguments) // prints with colors in Chrome!

Here's what the format looks like:

parsed.asChromeConsoleLogArguments // [ "%cfoo%cbar%cbaz",
                                   //   "",
                                   //   "font-weight: bold;text-decoration: underline;background:rgba(255,51,0,1);color:rgba(0,204,0,1);",
                                   //   "background:rgba(0,204,0,1);"
                                   // ]

Play with this feature online: demo page. Open the DevTools console and type expressions in the input box to see colored console output.

Happy logging!

Projects That Use @firanorg/voluptatem-culpa-iusto

  • Ololog! — a better console.log for the log-driven debugging junkies
  • CCXT — a cryptocurrency trading API with 130+ exchanges
  • Grafana — beautiful monitoring & metric analytics & dashboards
quotedeeppromisesES5plugintapsortObjectcjkSymbolqueueMicrotaskiamwraprgbemojiBigInt64ArraypositivefseventskeyES7Arraycircularwhatwgcommanderdom-testing-libraryglobflatcurlxhrrandomoptimistpackage managerless cssairbnbargparseglobalchaideepcopyString.prototype.trimvarssetPrototypeOfrmdirpostcss-pluginstylesheetStreamsinstallarraycss-in-jschromewebcachees-shimsdescriptorsutilString.prototype.matchAllcolorguidclassesdayjsfunctionsfastArrayBuffer#sliceUint16ArraymkdirpUnderscoreutilities_.extendtermstreamsclonereduxauthglobalsshebangchromiumECMAScript 2018jsxECMAScript 7browserlistsettings.envstyleguideimportexporterror-handlingfast-copyless mixinsrecursivecommand-linefast-clonearktypejestfilterarraysserializationeslintFloat64ArrayenvjoihasOwnPropertymake dirgetterisConcatSpreadableslicekarmacloudtrailsymbolES2016ES2017protobufgradients cssroutinges-shim APIcollectionmimetypesisObservableargumentinspectcallbackhasOwnarraybufferpromisefindLastrequirecensores2017matchessyntaxerrorstatewatchingcorecommandmetadatabddpolyfillparentsconsoleECMAScript 3extendregexpwaitfiletoStringTagObject.getPrototypeOfjsdiffObject.valuesavaoutpututilitysharedarraybufferpostcssimmutablestructuredCloneqsformattingjsRegExp#flagsprototypelinuxprotocol-buffersfixed-widtheventDispatcherstylepackagesobjectuninstalldefinesetImmediateclass-validatorWeakMapsymlinktypedlesscssmonorepovalidationprocessmoduleBigUint64ArrayjQuerybootstrap csscontainsbeanstalkArray.prototype.flat$.extendArray.prototype.filtereventsstarterES2020unicodeidentifiersclieslint-pluginES2021testerhelpersfindcodesdateES8parsingSymbol.toStringTagpredictableemrsafeloggingauthenticationdomtelephoneaccessortc39protoECMAScript 2019internalWebSocketTypedArrayefficientObject.keysbannerchannelcomputed-typesoffsethttpbluebirdvalidxtermvariablesconfigsortedidpipeCSSStyleDeclarationqueryYAMLdescriptionlimitedcss variablestyleswindowsRFC-6455ECMAScript 5toSorteduuidECMAScript 2022momentObject.isasyncclassnamematchAllagentponyfillbundlerpatchlimitsyntaxmatchfigletjapanesefast-deep-clonerdsjshintRegExp.prototype.flagsttyurlextramkdirsfullwidthUint32Arrayeast-asian-widthdiffmime-dbsameValueZero@@toStringTagstringexpressiontaskconnectshimconfigurablepreprocessorcss nestingweaksetmergesidewatchexitless compilerserializerexpressform-validationcall-boundlintpropertyAsyncIteratortypeerrorrfc4122serializeforEachtddescapebrowserInt16Arrayduplexincludesemitamazonassertcallbindnested cssoptimizercolourmacosgroupartURLRxirqmakekinesispushtouchraterobustchinesegroupBywidthjsonpathlastflagstoolsObject.definePropertyRxJSworkflowUint8ClampedArrayjsdomlookArray.prototype.findLastIndexIteratores2016multi-packagebuffersdataArray.prototype.flattenfssigintfetchhandlerstypesafestatusES2023concurrencyautoprefixertestinggdprfull-widthelblockfilebrowserslistdeleteebsconcatMapqueuetextpicomatchfast-deep-copyfastcopytaketapees2018eslintpluginsinatrafindupweakmaploggerscheme-validationshellassignWeakSetdotenvless.jstoolkitenvironmentparserwatcherES2019privatemapreducesomees5electronautoscalinghas-owniehookformargsrm-0libphonenumbertypanionbytepathlistenersprogressproxyawesomesaucebyteLengththroatMapwgetwatchFileliveArray.prototype.findLasthasjavascripteswarningHyBinopeworkspace:*functionframeworkassertionObservablesnpmes2015superstructlrufullupsearchbundlingprefixrm -rfstatelesscomparegetfastcloneObject.assigntyped arraymimecloudformationflattenfindLastIndexes-abstractdefinePropertyendermodulesReactiveExtensionsimportcollection.es6openbreakreadableregularroute53environmentslengthreadablestreamnamesetPushdeepclonemkdirObject.fromEntriescall-bindbcrypttimedependenciesestreeworkerentriestypedarraytraverseES2022validatereducergetoptequalflatMapsimpledbcore-jsArray.prototype.containsArrayBuffercompile lesspyyamlObject.entriesecmascriptpropspinnerfluxReactiveXclassnameschecklesswordbreakresolveaccessibilityasciiCSSappextensionlook-upESreduceTypeBoxconsumefromvestpnpm9deterministictypedarrayshotbyteOffsetdatastructureansiiteratorWebSocketses8variables in cssECMAScript 2020hashvisualcloudfrontawaitReflect.getPrototypeOfconcatenumerabledirectorylanguageindeep-cloneStyleSheetECMAScript 2017elmdropfile systemMicrosoftgetPrototypeOfiterationes6shamelasticacheargvformwalkingURLSearchParamsstringifyoptionECMAScript 2015requestidlegetOwnPropertyDescriptorhooksonceregexyamlrouteinferencenumberrapidnodejswritableequalityinterruptspropertiestypeJSON-SchematrimRightsqswordwrapinstallersnslazyfind-up__proto__Float32ArraymixinsmrucloudwatcheslintconfigInt8Arraygetintrinsica11yvaluesrm -frformatsymbolscss lesssignalsreactfunctionalsharedterminaleventEmitterimmerTypeScriptJSONmochaArray.prototype.flatMaptostringtagspinnersstreambufferrestfulflagminimali18npruneexectestreaddebugpasswordwritemoveregular expressionstsintrinsictrimES2018sescallboundomit256ec2everysuperagentES2015awsprettycode pointsthrottlehardlinkspersistentnodeESnextindicatortypescriptFunction.prototype.nameparsestyled-componentspackagevaluecloudsearchreal-timefpsassertsECMAScript 2021react-testing-libraryfolderdircompilercolorsprivate dataES6trimStartobjtrimLeftoperating-systemredux-toolkitcryptocharactersnativewalknamesio-tsswfsequencelinewrapsetterjasmineapirestastformsInt32Arrayreuseschemarangeerrortypesperformancereact-hooksstylingcorsdataviewajvreact-hook-formyupES3jwtwhichdescriptordataViewpreserve-symlinkscoercibleglacierviewdebugger
@firanorg/inventore-eligendi-quam@firanorg/inventore-hic-cumque@firanorg/impedit-mollitia-sint@firanorg/id-et-quaerat@firanorg/amet-accusantium-dolor@firanorg/amet-consectetur-veniam@firanorg/cupiditate-veniam-ut@firanorg/autem-eveniet-earum@firanorg/corporis-iste-ullam@firanorg/architecto-velit-odit@firanorg/exercitationem-debitis-laborum@firanorg/et-non-error@firanorg/necessitatibus-similique-nam@firanorg/laudantium-corrupti-itaque@firanorg/necessitatibus-sunt-quia@firanorg/sit-odit-numquam@firanorg/ut-officiis-et@firanorg/temporibus-quibusdam-non@firanorg/totam-excepturi-voluptas@firanorg/veniam-temporibus-accusantium@firanorg/doloribus-laborum-qui@firanorg/dolore-cumque-distinctio@firanorg/delectus-eligendi-quae@firanorg/eligendi-aut-ducimus@firanorg/error-laboriosam-molestias@firanorg/doloribus-quasi-dolores@firanorg/dolorem-architecto-eum@firanorg/fuga-unde-tempore@firanorg/explicabo-incidunt-facere@firanorg/hic-doloremque-est@firanorg/fuga-quis-optio@firanorg/hic-tempora-dignissimos@firanorg/harum-ad-explicabo@firanorg/iure-voluptates-nobis@firanorg/itaque-consectetur-velit@firanorg/ratione-iusto-numquam@firanorg/saepe-ut-natus@firanorg/sapiente-expedita-quidem@firanorg/repellat-expedita-autem@firanorg/alias-repellat-vero@firanorg/pariatur-officia-placeat@firanorg/odit-corrupti-aperiam@firanorg/optio-velit-culpa@firanorg/numquam-inventore-ad@firanorg/non-praesentium-sint@firanorg/nulla-cupiditate-ad@firanorg/neque-est-dolorum@firanorg/voluptate-perspiciatis-placeat@firanorg/vero-laborum-tenetur@firanorg/accusamus-magnam-numquam@firanorg/a-neque-sunt@firanorg/ab-magni-explicabo@firanorg/iste-dolor-omnis@firanorg/quasi-commodi-fugit@firanorg/quia-dolores-occaecati@firanorg/quia-cumque-perspiciatis@firanorg/perferendis-iusto-vitae@firanorg/voluptatem-odit-et@firanorg/maxime-deleniti-soluta
6.16.146

9 months ago

6.16.145

9 months ago

6.14.130

10 months ago

6.14.132

10 months ago

6.14.131

10 months ago

6.14.134

10 months ago

6.14.133

10 months ago

6.14.129

10 months ago

6.14.128

10 months ago

6.16.144

9 months ago

6.16.141

9 months ago

6.16.140

9 months ago

6.16.143

9 months ago

6.16.142

9 months ago

6.16.138

9 months ago

6.16.137

9 months ago

6.16.139

9 months ago

6.16.136

10 months ago

6.16.135

10 months ago

6.15.135

10 months ago

6.15.134

10 months ago

6.14.127

10 months ago

6.14.126

10 months ago

6.14.125

10 months ago

6.14.124

10 months ago

6.13.124

10 months ago

6.13.117

10 months ago

6.13.118

10 months ago

6.13.119

10 months ago

6.13.120

10 months ago

6.13.121

10 months ago

6.13.122

10 months ago

6.13.123

10 months ago

6.12.117

10 months ago

6.12.116

10 months ago

6.12.115

10 months ago

6.11.113

10 months ago

6.11.114

10 months ago

6.11.115

10 months ago

6.10.113

10 months ago

6.9.113

11 months ago

6.9.112

11 months ago

6.9.111

11 months ago

6.9.110

11 months ago

6.8.110

11 months ago

5.8.110

11 months ago

5.8.109

11 months ago

5.8.108

11 months ago

5.8.107

11 months ago

5.7.107

11 months ago

5.7.106

11 months ago

3.4.47

1 year ago

3.4.48

1 year ago

3.4.49

1 year ago

3.4.41

1 year ago

3.4.42

1 year ago

3.4.43

1 year ago

3.4.44

1 year ago

3.4.45

1 year ago

3.4.46

1 year ago

5.6.99

11 months ago

5.6.98

11 months ago

3.4.58

1 year ago

3.2.35

1 year ago

3.4.59

1 year ago

3.2.34

1 year ago

3.2.37

1 year ago

3.2.36

1 year ago

3.2.39

1 year ago

3.2.38

1 year ago

3.4.50

1 year ago

3.4.51

1 year ago

3.4.52

1 year ago

3.4.53

1 year ago

4.5.61

1 year ago

3.4.54

1 year ago

3.4.55

1 year ago

3.4.56

1 year ago

3.2.33

1 year ago

3.4.57

1 year ago

3.2.32

1 year ago

3.1.32

1 year ago

3.1.31

1 year ago

2.1.27

1 year ago

2.1.28

1 year ago

2.1.25

1 year ago

2.1.26

1 year ago

2.1.23

1 year ago

2.1.24

1 year ago

2.1.22

1 year ago

5.5.95

11 months ago

5.5.96

11 months ago

5.5.93

11 months ago

5.5.94

11 months ago

5.5.91

11 months ago

5.5.92

11 months ago

5.5.90

11 months ago

2.1.29

1 year ago

2.1.30

1 year ago

5.7.102

11 months ago

2.1.31

1 year ago

1.1.22

1 year ago

1.1.21

1 year ago

5.7.105

11 months ago

5.7.103

11 months ago

5.5.97

11 months ago

5.7.104

11 months ago

5.5.98

11 months ago

5.5.84

12 months ago

5.5.85

12 months ago

5.5.82

12 months ago

5.5.83

12 months ago

5.5.80

12 months ago

3.3.39

1 year ago

5.5.81

12 months ago

5.6.100

11 months ago

5.6.101

11 months ago

5.6.102

11 months ago

4.4.61

1 year ago

4.4.60

1 year ago

1.0.21

1 year ago

1.0.20

1 year ago

5.5.88

12 months ago

5.5.89

11 months ago

5.5.86

12 months ago

5.5.87

12 months ago

5.5.73

12 months ago

5.5.74

12 months ago

5.5.71

12 months ago

5.5.72

12 months ago

5.5.70

12 months ago

3.3.40

1 year ago

3.3.41

1 year ago

5.5.79

12 months ago

4.4.59

1 year ago

5.5.77

12 months ago

5.5.78

12 months ago

5.5.75

12 months ago

5.5.76

12 months ago

5.5.62

1 year ago

5.5.63

1 year ago

5.5.61

1 year ago

5.5.68

1 year ago

5.5.69

12 months ago

5.5.66

1 year ago

5.5.67

1 year ago

5.5.64

1 year ago

5.5.65

1 year ago

1.0.19

1 year ago

1.0.18

1 year ago

1.0.17

1 year ago

1.0.16

1 year ago

1.0.15

1 year ago

1.0.14

1 year ago

1.0.13

1 year ago

1.0.12

1 year ago

1.0.11

1 year ago

1.0.10

1 year ago

1.0.9

1 year ago

1.0.8

1 year ago

1.0.7

1 year ago

1.0.6

1 year ago

1.0.5

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago