string-kit
Version:
A string manipulation toolbox, featuring a string formatter (inspired by sprintf), a variable inspector (output featuring ANSI colors and HTML) and various escape functions (shell argument, regexp, html, etc).
1,618 lines (1,240 loc) • 267 kB
JavaScript
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.stringKit = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
/*
String Kit
Copyright (c) 2014 - 2021 Cédric Ronvel
The MIT License (MIT)
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.
*/
"use strict" ;
/*
Number formatting class.
.format() should entirely use it for everything related to number formatting.
It avoids unsolvable rounding error with epsilon.
It is dedicated for number display, not for computing.
*/
const NUMERALS = [
'0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' ,
'a' , 'b' , 'c' , 'd' , 'e' , 'f' ,
'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' , 'x' , 'y' , 'z'
] ;
//const NUMERAL_MAP = buildNumeralMap( NUMERALS ) ;
function StringNumber( number , options = {} ) {
this.sign = 1 ;
this.digits = [] ;
this.exposant = 0 ;
this.special = null ; // It stores special values like NaN, Infinity, etc
this.decimalSeparator = options.decimalSeparator ?? '.' ;
this.forceDecimalSeparator = !! options.forceDecimalSeparator ;
this.groupSeparator = options.groupSeparator ?? '' ;
this.numerals = options.numerals ?? NUMERALS ;
this.numeralZero = options.numeralZero ?? null ; // Special numeral when the result is EXACTLY 0 (used for Roman Numerals)
this.placeNumerals = options.placeNumerals ?? null ;
//this.numeralMap = NUMERAL_MAP ;
//if ( options.numerals ) { this.numeralMap = buildNumeralMap( options.numerals ) ; }
this.set( number ) ;
}
module.exports = StringNumber ;
/*
function buildNumeralMap( numbers ) {
var map = new Map() ;
for ( let i = 0 ; i < numbers.length ; i ++ ) {
let number = numbers[ i ] ;
map.set( NUMERALS[ i ] , numbers[ i ] ) ;
}
return map ;
}
*/
StringNumber.prototype.set = function( number ) {
var matches , v , i , iMax , index , hasNonZeroHead , tailIndex ;
number = + number ;
// Reset anything, if it was already used...
this.sign = 1 ;
this.digits.length = 0 ;
this.exposant = 0 ;
this.special = null ;
if ( ! Number.isFinite( number ) ) {
this.special = number ;
return null ;
}
number = '' + number ;
matches = number.match( /(-)?([0-9]+)(?:.([0-9]+))?(?:e([+-][0-9]+))?/ ) ;
if ( ! matches ) { throw new Error( 'Unexpected error' ) ; }
this.sign = matches[ 1 ] ? -1 : 1 ;
this.exposant = matches[ 2 ].length + ( parseInt( matches[ 4 ] , 10 ) || 0 ) ;
// Copy each digits and cast them back into a number
index = 0 ;
hasNonZeroHead = false ;
tailIndex = 0 ; // used to cut trailing zero
for ( i = 0 , iMax = matches[ 2 ].length ; i < iMax ; i ++ ) {
v = + matches[ 2 ][ i ] ;
if ( v !== 0 ) {
hasNonZeroHead = true ;
this.digits[ index ] = v ;
index ++ ;
tailIndex = index ;
}
else if ( hasNonZeroHead ) {
this.digits[ index ] = v ;
index ++ ;
}
else {
this.exposant -- ;
}
}
if ( matches[ 3 ] ) {
for ( i = 0 , iMax = matches[ 3 ].length ; i < iMax ; i ++ ) {
v = + matches[ 3 ][ i ] ;
if ( v !== 0 ) {
hasNonZeroHead = true ;
this.digits[ index ] = v ;
index ++ ;
tailIndex = index ;
}
else if ( hasNonZeroHead ) {
this.digits[ index ] = v ;
index ++ ;
}
else {
this.exposant -- ;
}
}
}
if ( tailIndex !== index ) {
this.digits.length = tailIndex ;
}
} ;
StringNumber.prototype.toNumber = function() {
// Using a string representation
if ( this.special !== null ) { return this.special ; }
return parseFloat( ( this.sign < 0 ? '-' : '' ) + '0.' + this.digits.join( '' ) + 'e' + this.exposant ) ;
} ;
StringNumber.prototype.toString = function( ... args ) {
if ( this.special !== null ) { return '' + this.special ; }
if ( this.exposant > 20 || this.exposant < -20 ) { return this.toScientificString( ... args ) ; }
return this.toNoExpString( ... args ) ;
} ;
StringNumber.prototype.toExponential =
StringNumber.prototype.toExponentialString = function() {
if ( this.special !== null ) { return '' + this.special ; }
var str = this.sign < 0 ? '-' : '' ;
if ( ! this.digits.length ) { return str + '0' ; }
str += this.digits[ 0 ] ;
if ( this.digits.length > 1 ) {
str += this.decimalSeparator + this.digits.join( '' ).slice( 1 ) ;
}
str += 'e' + ( this.exposant > 0 ? '+' : '' ) + ( this.exposant - 1 ) ;
return str ;
} ;
const SUPER_NUMBER = [ '⁰' , '¹' , '²' , '³' , '⁴' , '⁵' , '⁶' , '⁷' , '⁸' , '⁹' ] ;
const SUPER_PLUS = '⁺' ;
const SUPER_MINUS = '⁻' ;
const ZERO_CHAR_CODE = '0'.charCodeAt( 0 ) ;
StringNumber.prototype.toScientific =
StringNumber.prototype.toScientificString = function() {
if ( this.special !== null ) { return '' + this.special ; }
var str = this.sign < 0 ? '-' : '' ;
if ( ! this.digits.length ) { return str + '0' ; }
str += this.digits[ 0 ] ;
if ( this.digits.length > 1 ) {
str += this.decimalSeparator + this.digits.join( '' ).slice( 1 ) ;
}
var exposantStr =
( this.exposant <= 0 ? SUPER_MINUS : '' ) +
( '' + Math.abs( this.exposant - 1 ) ).split( '' ).map( c => SUPER_NUMBER[ c.charCodeAt( 0 ) - ZERO_CHAR_CODE ] )
.join( '' ) ;
str += ' × 10' + exposantStr ;
return str ;
} ;
// leadingZero = minimal number of numbers before the dot, they will be left-padded with zero if needed.
// trailingZero = minimal number of numbers after the dot, they will be right-padded with zero if needed.
// onlyIfDecimal: set it to true if you don't want right padding zero when there is no decimal
StringNumber.prototype.toNoExp =
StringNumber.prototype.toNoExpString = function( leadingZero = 1 , trailingZero = 0 , onlyIfDecimal = false , forcePlusSign = false , exposant = this.exposant ) {
if ( this.special !== null ) { return '' + this.special ; }
var integerDigits = [] , decimalDigits = [] ,
str = this.sign < 0 ? '-' : forcePlusSign ? '+' : '' ;
if ( ! this.digits.length ) {
if ( leadingZero > 1 ) {
this.fillZeroes( integerDigits , leadingZero - 1 , leadingZero ) ;
}
integerDigits.push( this.numeralZero ?? this.placeNumerals?.[ 0 ]?.[ 0 ] ?? this.numerals[ 0 ] ) ;
if ( trailingZero && ! onlyIfDecimal ) {
this.fillZeroes( decimalDigits , trailingZero ) ;
}
}
else if ( exposant <= 0 ) {
// This number is of type 0.[0...]xyz
this.fillZeroes( integerDigits , leadingZero ) ;
this.fillZeroes( decimalDigits , -exposant , trailingZero - this.digits.length ) ;
this.appendNumerals( decimalDigits , this.digits , undefined , undefined , -exposant - 1 ) ;
if ( trailingZero && this.digits.length - exposant < trailingZero ) {
this.fillZeroes( decimalDigits , trailingZero - this.digits.length + exposant ) ;
}
}
else if ( exposant >= this.digits.length ) {
// This number is of type xyz[0...]
if ( exposant < leadingZero ) { this.fillZeroes( integerDigits , leadingZero - exposant , exposant - 1 ) ; }
this.appendNumerals( integerDigits , this.digits , undefined , undefined , exposant - 1 ) ;
this.fillZeroes( integerDigits , exposant - this.digits.length ) ;
if ( trailingZero && ! onlyIfDecimal ) {
this.fillZeroes( decimalDigits , trailingZero ) ;
}
}
else {
// Here the digits are splitted with a dot in the middle
if ( exposant < leadingZero ) { this.fillZeroes( integerDigits , leadingZero - exposant ) ; }
this.appendNumerals( integerDigits , this.digits , 0 , exposant , exposant - 1 ) ;
this.appendNumerals( decimalDigits , this.digits , exposant , undefined , this.digits.length - exposant ) ;
if (
trailingZero && this.digits.length - exposant < trailingZero
&& ( ! onlyIfDecimal || this.digits.length - exposant > 0 )
) {
this.fillZeroes( decimalDigits , trailingZero - this.digits.length + exposant ) ;
}
}
str += this.groupSeparator ?
this.groupDigits( integerDigits , this.groupSeparator ) :
integerDigits.join( '' ) ;
if ( decimalDigits.length ) {
str += this.decimalSeparator + (
this.decimalGroupSeparator ?
this.groupDigits( decimalDigits , this.decimalGroupSeparator ) :
decimalDigits.join( '' )
) ;
}
else if ( this.forceDecimalSeparator ) {
str += this.decimalSeparator ;
}
return str ;
} ;
// Metric prefix
const MUL_PREFIX = [ '' , 'k' , 'M' , 'G' , 'T' , 'P' , 'E' , 'Z' , 'Y' ] ;
const SUB_MUL_PREFIX = [ '' , 'm' , 'µ' , 'n' , 'p' , 'f' , 'a' , 'z' , 'y' ] ;
StringNumber.prototype.toMetric =
StringNumber.prototype.toMetricString = function( leadingZero = 1 , trailingZero = 0 , onlyIfDecimal = false , forcePlusSign = false ) {
if ( this.special !== null ) { return '' + this.special ; }
if ( ! this.digits.length ) { return this.sign > 0 ? '0' : '-0' ; }
var prefix = '' , fakeExposant ;
if ( this.exposant > 0 ) {
fakeExposant = 1 + ( ( this.exposant - 1 ) % 3 ) ;
prefix = MUL_PREFIX[ Math.floor( ( this.exposant - 1 ) / 3 ) ] ;
// Fallback to scientific if the number is to big
if ( prefix === undefined ) { return this.toScientificString() ; }
}
else {
fakeExposant = 3 - ( -this.exposant % 3 ) ;
prefix = SUB_MUL_PREFIX[ 1 + Math.floor( -this.exposant / 3 ) ] ;
// Fallback to scientific if the number is to small
if ( prefix === undefined ) { return this.toScientificString() ; }
}
return this.toNoExpString( leadingZero , trailingZero , onlyIfDecimal , forcePlusSign , fakeExposant ) + prefix ;
} ;
/*
type: 0=round, -1=floor, 1=ceil
Floor if < .99999
Ceil if >= .00001
*/
StringNumber.prototype.precision = function( n , type = 0 ) {
var roundUp ;
if ( this.special !== null || n >= this.digits.length ) { return this ; }
if ( n < 0 ) { this.digits.length = 0 ; return this ; }
type *= this.sign ;
if ( type < 0 ) {
roundUp =
this.digits.length > n + 4
&& this.digits[ n ] === 9 && this.digits[ n + 1 ] === 9
&& this.digits[ n + 2 ] === 9 && this.digits[ n + 3 ] === 9 && this.digits[ n + 4 ] === 9 ;
}
else if ( type > 0 ) {
roundUp =
this.digits[ n ] > 0 || this.digits[ n + 1 ] > 0
|| this.digits[ n + 2 ] > 0 || this.digits[ n + 3 ] > 0 || this.digits[ n + 4 ] > 0 ;
}
else {
roundUp = this.digits[ n ] >= 5 ;
}
if ( roundUp ) {
let i = n - 1 ,
done = false ;
// Cascading increase
for ( ; i >= 0 ; i -- ) {
if ( this.digits[ i ] < 9 ) { this.digits[ i ] ++ ; done = true ; break ; }
else { this.digits[ i ] = 0 ; }
}
if ( ! done ) {
this.exposant ++ ;
this.digits[ 0 ] = 1 ;
this.digits.length = 1 ;
}
else {
this.digits.length = i + 1 ;
}
}
else {
this.digits.length = n ;
this.removeTrailingZero() ;
}
return this ;
} ;
StringNumber.prototype.round = function( decimalPlace = 0 , type = 0 ) {
var n = this.exposant + decimalPlace ;
return this.precision( n , type ) ;
} ;
StringNumber.prototype.floor = function( decimalPlace = 0 ) {
var n = this.exposant + decimalPlace ;
return this.precision( n , -1 ) ;
} ;
StringNumber.prototype.ceil = function( decimalPlace = 0 ) {
var n = this.exposant + decimalPlace ;
return this.precision( n , 1 ) ;
} ;
StringNumber.prototype.removeTrailingZero = function() {
var i = this.digits.length - 1 ;
while( i >= 0 && this.digits[ i ] === 0 ) { i -- ; }
this.digits.length = i + 1 ;
} ;
const GROUP_SIZE = 3 ;
StringNumber.prototype.groupDigits = function( digits , separator , inverseOrder = false ) {
var str = '' ,
offset = inverseOrder ? 0 : GROUP_SIZE - ( digits.length % GROUP_SIZE ) ,
i = 0 ,
iMax = digits.length ;
for ( ; i < iMax ; i ++ ) {
str += i && ( ( i + offset ) % GROUP_SIZE === 0 ) ? separator + digits[ i ] : digits[ i ] ;
}
return str ;
} ;
StringNumber.prototype.appendNumerals = function( intoArray , sourceArray , start = 0 , end = sourceArray.length , leftPlace = end ) {
//console.log( "appendNumerals:" , { intoArray , sourceArray , start , end , leftPlace } ) ;
for ( let i = start , place = leftPlace ; i < end ; i ++ , place -- ) {
let numerals = this.placeNumerals?.[ place ] ?? this.numerals ;
intoArray.push( numerals[ sourceArray[ i ] ] ?? sourceArray[ i ] ) ;
}
return intoArray ;
} ;
StringNumber.prototype.fillZeroes = function( intoArray , count , leftPlace = count - 1 ) {
//console.log( "fillZeroes:" , { intoArray , count , leftPlace } ) ;
for ( let i = 0 , place = leftPlace ; i < count ; i ++ , place -- ) {
let numerals = this.placeNumerals?.[ place ] ?? this.numerals ;
intoArray.push( numerals[ 0 ] ?? 0 ) ;
}
return intoArray ;
} ;
const ROMAN_OPTIONS = {
numeralZero: 'N' ,
placeNumerals: [
[ '' , 'I' , 'II' , 'III' , 'IV' , 'V' , 'VI' , 'VII' , 'VIII' , 'IX' ] ,
[ '' , 'X' , 'XX' , 'XXX' , 'XL' , 'L' , 'LX' , 'LXX' , 'LXXX' , 'XC' ] ,
[ '' , 'C' , 'CC' , 'CCC' , 'CD' , 'D' , 'DC' , 'DCC' , 'DCCC' , 'CM' ] ,
[ '' , 'M' , 'MM' , 'MMM' , 'MMMM' , 'ↁ' , 'ↁↀ' , 'ↁↀↀ' , 'ↁↀↀↀ' , 'ↁↀↀↀↀ' ]
]
} ;
const ADDITIVE_ROMAN_OPTIONS = {
numeralZero: 'N' ,
placeNumerals: [
[ '' , 'I' , 'II' , 'III' , 'IIII' , 'V' , 'VI' , 'VII' , 'VIII' , 'VIIII' ] ,
[ '' , 'X' , 'XX' , 'XXX' , 'XXXX' , 'L' , 'LX' , 'LXX' , 'LXXX' , 'LXXXX' ] ,
[ '' , 'C' , 'CC' , 'CCC' , 'CCCC' , 'D' , 'DC' , 'DCC' , 'DCCC' , 'DCCCC' ] ,
[ '' , 'M' , 'MM' , 'MMM' , 'MMMM' , 'ↁ' , 'ↁↀ' , 'ↁↀↀ' , 'ↁↀↀↀ' , 'ↁↀↀↀↀ' ]
]
} ;
const APOSTROPHUS_ROMAN_OPTIONS = {
numeralZero: 'N' ,
placeNumerals: [
[ '' , 'I' , 'II' , 'III' , 'IV' , 'V' , 'VI' , 'VII' , 'VIII' , 'IX' ] ,
[ '' , 'X' , 'XX' , 'XXX' , 'XL' , 'L' , 'LX' , 'LXX' , 'LXXX' , 'XC' ] ,
[ '' , 'C' , 'CC' , 'CCC' , 'CD' , 'D' , 'DC' , 'DCC' , 'DCCC' , 'CM' ] ,
[ '' , 'M' , 'MM' , 'MMM' , 'MMMM' , 'IↃↃ' , 'IↃↃCIↃ' , 'IↃↃCIↃCIↃ' , 'IↃↃCIↃCIↃCIↃ' , 'IↃↃCIↃCIↃCIↃCIↃ' ] ,
[ '' , 'CCIↃↃ' , 'CCIↃↃCCIↃↃ' , 'CCIↃↃCCIↃↃCCIↃↃ' , 'CCIↃↃCCIↃↃCCIↃↃCCIↃↃ' , 'IↃↃↃ' , 'IↃↃↃCCIↃↃ' , 'IↃↃↃCCIↃↃCCIↃↃ' , 'IↃↃↃCCIↃↃCCIↃↃCCIↃↃ' , 'IↃↃↃCCIↃↃCCIↃↃCCIↃↃCCIↃↃ' ] ,
[ '' , 'CCCIↃↃↃ' , 'CCCIↃↃↃCCCIↃↃↃ' , 'CCCIↃↃↃCCCIↃↃↃCCCIↃↃↃ' , 'CCCIↃↃↃCCCIↃↃↃCCCIↃↃↃCCCIↃↃↃ' , 'IↃↃↃↃ' , 'IↃↃↃↃCCCIↃↃↃ' , 'IↃↃↃↃCCCIↃↃↃCCCIↃↃↃ' , 'IↃↃↃↃCCCIↃↃↃCCCIↃↃↃCCCIↃↃↃ' , 'IↃↃↃↃCCCIↃↃↃCCCIↃↃↃCCCIↃↃↃCCCIↃↃↃ' ]
]
} ;
StringNumber.roman = ( number , options ) => {
options = options ? Object.assign( {} , options , ROMAN_OPTIONS ) : ROMAN_OPTIONS ;
return new StringNumber( number , options ) ;
} ;
StringNumber.additiveRoman = ( number , options ) => {
options = options ? Object.assign( {} , options , ADDITIVE_ROMAN_OPTIONS ) : ADDITIVE_ROMAN_OPTIONS ;
return new StringNumber( number , options ) ;
} ;
},{}],2:[function(require,module,exports){
/*
String Kit
Copyright (c) 2014 - 2021 Cédric Ronvel
The MIT License (MIT)
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.
*/
"use strict" ;
// To solve dependency hell, we do not rely on terminal-kit anymore.
const ansi = {
reset: '\x1b[0m' ,
bold: '\x1b[1m' ,
dim: '\x1b[2m' ,
italic: '\x1b[3m' ,
underline: '\x1b[4m' ,
inverse: '\x1b[7m' ,
defaultColor: '\x1b[39m' ,
black: '\x1b[30m' ,
red: '\x1b[31m' ,
green: '\x1b[32m' ,
yellow: '\x1b[33m' ,
blue: '\x1b[34m' ,
magenta: '\x1b[35m' ,
cyan: '\x1b[36m' ,
white: '\x1b[37m' ,
grey: '\x1b[90m' ,
gray: '\x1b[90m' ,
brightBlack: '\x1b[90m' ,
brightRed: '\x1b[91m' ,
brightGreen: '\x1b[92m' ,
brightYellow: '\x1b[93m' ,
brightBlue: '\x1b[94m' ,
brightMagenta: '\x1b[95m' ,
brightCyan: '\x1b[96m' ,
brightWhite: '\x1b[97m' ,
defaultBgColor: '\x1b[49m' ,
bgBlack: '\x1b[40m' ,
bgRed: '\x1b[41m' ,
bgGreen: '\x1b[42m' ,
bgYellow: '\x1b[43m' ,
bgBlue: '\x1b[44m' ,
bgMagenta: '\x1b[45m' ,
bgCyan: '\x1b[46m' ,
bgWhite: '\x1b[47m' ,
bgGrey: '\x1b[100m' ,
bgGray: '\x1b[100m' ,
bgBrightBlack: '\x1b[100m' ,
bgBrightRed: '\x1b[101m' ,
bgBrightGreen: '\x1b[102m' ,
bgBrightYellow: '\x1b[103m' ,
bgBrightBlue: '\x1b[104m' ,
bgBrightMagenta: '\x1b[105m' ,
bgBrightCyan: '\x1b[106m' ,
bgBrightWhite: '\x1b[107m'
} ;
module.exports = ansi ;
ansi.fgColor = {
defaultColor: ansi.defaultColor ,
black: ansi.black ,
red: ansi.red ,
green: ansi.green ,
yellow: ansi.yellow ,
blue: ansi.blue ,
magenta: ansi.magenta ,
cyan: ansi.cyan ,
white: ansi.white ,
grey: ansi.grey ,
gray: ansi.gray ,
brightBlack: ansi.brightBlack ,
brightRed: ansi.brightRed ,
brightGreen: ansi.brightGreen ,
brightYellow: ansi.brightYellow ,
brightBlue: ansi.brightBlue ,
brightMagenta: ansi.brightMagenta ,
brightCyan: ansi.brightCyan ,
brightWhite: ansi.brightWhite
} ;
ansi.bgColor = {
defaultColor: ansi.defaultBgColor ,
black: ansi.bgBlack ,
red: ansi.bgRed ,
green: ansi.bgGreen ,
yellow: ansi.bgYellow ,
blue: ansi.bgBlue ,
magenta: ansi.bgMagenta ,
cyan: ansi.bgCyan ,
white: ansi.bgWhite ,
grey: ansi.bgGrey ,
gray: ansi.bgGray ,
brightBlack: ansi.bgBrightBlack ,
brightRed: ansi.bgBrightRed ,
brightGreen: ansi.bgBrightGreen ,
brightYellow: ansi.bgBrightYellow ,
brightBlue: ansi.bgBrightBlue ,
brightMagenta: ansi.bgBrightMagenta ,
brightCyan: ansi.bgBrightCyan ,
brightWhite: ansi.bgBrightWhite
} ;
ansi.trueColor = ( r , g , b ) => {
if ( g === undefined && typeof r === 'string' ) {
let hex = r ;
if ( hex[ 0 ] === '#' ) { hex = hex.slice( 1 ) ; } // Strip the # if necessary
if ( hex.length === 3 ) { hex = hex[ 0 ] + hex[ 0 ] + hex[ 1 ] + hex[ 1 ] + hex[ 2 ] + hex[ 2 ] ; }
r = parseInt( hex.slice( 0 , 2 ) , 16 ) || 0 ;
g = parseInt( hex.slice( 2 , 4 ) , 16 ) || 0 ;
b = parseInt( hex.slice( 4 , 6 ) , 16 ) || 0 ;
}
return '\x1b[38;2;' + r + ';' + g + ';' + b + 'm' ;
} ;
ansi.bgTrueColor = ( r , g , b ) => {
if ( g === undefined && typeof r === 'string' ) {
let hex = r ;
if ( hex[ 0 ] === '#' ) { hex = hex.slice( 1 ) ; } // Strip the # if necessary
if ( hex.length === 3 ) { hex = hex[ 0 ] + hex[ 0 ] + hex[ 1 ] + hex[ 1 ] + hex[ 2 ] + hex[ 2 ] ; }
r = parseInt( hex.slice( 0 , 2 ) , 16 ) || 0 ;
g = parseInt( hex.slice( 2 , 4 ) , 16 ) || 0 ;
b = parseInt( hex.slice( 4 , 6 ) , 16 ) || 0 ;
}
return '\x1b[48;2;' + r + ';' + g + ';' + b + 'm' ;
} ;
const ANSI_CODES = {
'0': null ,
'1': { bold: true } ,
'2': { dim: true } ,
'22': { bold: false , dim: false } ,
'3': { italic: true } ,
'23': { italic: false } ,
'4': { underline: true } ,
'24': { underline: false } ,
'5': { blink: true } ,
'25': { blink: false } ,
'7': { inverse: true } ,
'27': { inverse: false } ,
'8': { hidden: true } ,
'28': { hidden: false } ,
'9': { strike: true } ,
'29': { strike: false } ,
'30': { color: 0 } ,
'31': { color: 1 } ,
'32': { color: 2 } ,
'33': { color: 3 } ,
'34': { color: 4 } ,
'35': { color: 5 } ,
'36': { color: 6 } ,
'37': { color: 7 } ,
//'39': { defaultColor: true } ,
'39': { color: 'default' } ,
'90': { color: 8 } ,
'91': { color: 9 } ,
'92': { color: 10 } ,
'93': { color: 11 } ,
'94': { color: 12 } ,
'95': { color: 13 } ,
'96': { color: 14 } ,
'97': { color: 15 } ,
'40': { bgColor: 0 } ,
'41': { bgColor: 1 } ,
'42': { bgColor: 2 } ,
'43': { bgColor: 3 } ,
'44': { bgColor: 4 } ,
'45': { bgColor: 5 } ,
'46': { bgColor: 6 } ,
'47': { bgColor: 7 } ,
//'49': { bgDefaultColor: true } ,
'49': { bgColor: 'default' } ,
'100': { bgColor: 8 } ,
'101': { bgColor: 9 } ,
'102': { bgColor: 10 } ,
'103': { bgColor: 11 } ,
'104': { bgColor: 12 } ,
'105': { bgColor: 13 } ,
'106': { bgColor: 14 } ,
'107': { bgColor: 15 }
} ;
// Parse ANSI codes, output is compatible with the markup parser
ansi.parse = str => {
var ansiCodes , raw , part , style , output = [] ;
for ( [ , ansiCodes , raw ] of str.matchAll( /\x1b\[([0-9;]+)m|(.[^\x1b]*)/g ) ) {
if ( raw ) {
if ( output.length ) { output[ output.length - 1 ].text += raw ; }
else { output.push( { text: raw } ) ; }
}
else {
ansiCodes.split( ';' ).forEach( ansiCode => {
style = ANSI_CODES[ ansiCode ] ;
if ( style === undefined ) { return ; }
if ( ! output.length || output[ output.length - 1 ].text ) {
if ( ! style ) {
part = { text: '' } ;
}
else {
part = Object.assign( {} , part , style ) ;
part.text = '' ;
}
output.push( part ) ;
}
else {
// There is no text, no need to create a new part
if ( ! style ) {
// Replace the last part
output[ output.length - 1 ] = { text: '' } ;
}
else {
// update the last part
Object.assign( part , style ) ;
}
}
} ) ;
}
}
return output ;
} ;
},{}],3:[function(require,module,exports){
/*
String Kit
Copyright (c) 2014 - 2021 Cédric Ronvel
The MIT License (MIT)
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.
*/
"use strict" ;
var camel = {} ;
module.exports = camel ;
// Transform alphanum separated by underscore or minus to camel case
camel.toCamelCase = function( str , preserveUpperCase = false , initialUpperCase = false ) {
if ( ! str || typeof str !== 'string' ) { return '' ; }
return str.replace(
/(?:^[\s_-]*|([\s_-]+))(([^\s_-]?)([^\s_-]*))/g ,
( match , isNotFirstWord , word , firstLetter , endOfWord ) => {
if ( preserveUpperCase ) {
if ( ! isNotFirstWord && ! initialUpperCase ) { return word ; }
if ( ! firstLetter ) { return '' ; }
return firstLetter.toUpperCase() + endOfWord ;
}
if ( ! isNotFirstWord && ! initialUpperCase ) { return word.toLowerCase() ; }
if ( ! firstLetter ) { return '' ; }
return firstLetter.toUpperCase() + endOfWord.toLowerCase() ;
}
) ;
} ;
camel.camelCaseToSeparated = function( str , separator = ' ' , acronym = true ) {
if ( ! str || typeof str !== 'string' ) { return '' ; }
if ( ! acronym ) {
return str.replace( /^([A-Z])|([A-Z])/g , ( match , firstLetter , letter ) => {
if ( firstLetter ) { return firstLetter.toLowerCase() ; }
return separator + letter.toLowerCase() ;
} ) ;
}
// (^)? and (^)? does not work, so we have to use (?:(^)|)) and (?:($)|)) to capture end or not
return str.replace( /(?:(^)|)([A-Z]+)(?:($)|(?=[a-z]))/g , ( match , isStart , letters , isEnd ) => {
isStart = isStart === '' ;
isEnd = isEnd === '' ;
var prefix = isStart ? '' : separator ;
return letters.length === 1 ? prefix + letters.toLowerCase() :
isEnd ? prefix + letters :
letters.length === 2 ? prefix + letters[ 0 ].toLowerCase() + separator + letters[ 1 ].toLowerCase() :
prefix + letters.slice( 0 , -1 ) + separator + letters.slice( -1 ).toLowerCase() ;
} ) ;
} ;
// Transform camel case to alphanum separated by minus
camel.camelCaseToDash =
camel.camelCaseToDashed = ( str ) => camel.camelCaseToSeparated( str , '-' , false ) ;
},{}],4:[function(require,module,exports){
/*
Book Source
Copyright (c) 2023 Cédric Ronvel
The MIT License (MIT)
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.
*/
"use strict" ;
const latinize = require( './latinize.js' ) ;
const english = require( './english.js' ) ;
const KEYWORD_TO_CHARLIST = require( './json-data/emoji-keyword-to-charlist.json' ) ;
const CHAR_TO_CANONICAL_NAME = require( './json-data/emoji-char-to-canonical-name.json' ) ;
const emoji = {} ;
module.exports = emoji ;
emoji.getCanonicalName = emojiChar => CHAR_TO_CANONICAL_NAME[ emojiChar ] ;
const emojiToKeywordsCache = {} ;
// Return a cached and frozen array
emoji.getKeywords = emojiChar => {
if ( ! CHAR_TO_CANONICAL_NAME[ emojiChar ] ) { return ; }
if ( ! emojiToKeywordsCache[ emojiChar ] ) {
emojiToKeywordsCache[ emojiChar ] = emoji.splitIntoKeywords( CHAR_TO_CANONICAL_NAME[ emojiChar ] ) ;
Object.freeze( emojiToKeywordsCache[ emojiChar ] ) ;
}
return emojiToKeywordsCache[ emojiChar ] ;
} ;
emoji.search = ( name , bestOnly = false ) => {
var keywords = emoji.splitIntoKeywords( name ) ,
matches = {} ,
score ,
bestScore = 0 ;
for ( let keyword of keywords ) {
if ( ! KEYWORD_TO_CHARLIST[ keyword ] ) { continue ; }
for ( let emojiChar of KEYWORD_TO_CHARLIST[ keyword ] ) {
if ( ! matches[ emojiChar ] ) {
score = 1 ;
matches[ emojiChar ] = {
emoji: emojiChar ,
score ,
canonical: CHAR_TO_CANONICAL_NAME[ emojiChar ] ,
keywords: emoji.getKeywords( emojiChar )
} ;
}
else {
score = matches[ emojiChar ].score + 1 ;
matches[ emojiChar ].score = score ;
}
if ( score > bestScore ) { bestScore = score ; }
}
}
var results = [ ... Object.values( matches ) ] ;
if ( bestOnly ) { results = results.filter( e => e.score === bestScore ) ; }
results.sort( ( a , b ) => ( b.score - a.score ) || ( a.keywords.length - b.keywords.length ) ) ;
return results ;
} ;
emoji.searchBest = name => emoji.search( name , true ) ;
emoji.get = name => emoji.search( name , true )[ 0 ]?.emoji ;
// Internal API, exposed because it is used by the builder
emoji.simplifyName = name => {
name = name.toLowerCase().replace( /[“”().!]/g , '' ).replace( /[ ’',]/g , '-' ).replace( /-+/g , '-' ) ;
name = latinize( name ) ;
return name ;
} ;
emoji.simplifyKeyword = inputKeyword => {
var kw = inputKeyword ;
kw = english.undoPresentParticiple( kw ) ;
//if ( kw !== inputKeyword ) { console.log( "Changing KW:" , inputKeyword , "-->" , kw ) ; }
return kw ;
} ;
const KEYWORD_EXCLUSION = new Set( [ 'with' , 'of' ] ) ;
emoji.splitIntoKeywords = ( name , noSimplify = false ) => {
if ( ! noSimplify ) { name = emoji.simplifyName( name ) ; }
var keywords = name.split( /-/g ).filter( keyword => keyword.length >= 2 && ! KEYWORD_EXCLUSION.has( keyword ) ) ;
keywords = keywords.map( emoji.simplifyKeyword ) ;
keywords = [ ... new Set( keywords ) ] ; // Make them unique
return keywords ;
} ;
},{"./english.js":5,"./json-data/emoji-char-to-canonical-name.json":10,"./json-data/emoji-keyword-to-charlist.json":11,"./latinize.js":14}],5:[function(require,module,exports){
/*
Book Source
Copyright (c) 2023 Cédric Ronvel
The MIT License (MIT)
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.
*/
"use strict" ;
const english = {} ;
module.exports = english ;
const VOWELS = new Set( [ 'a' , 'e' , 'i' , 'o' , 'u' , 'y' ] ) ;
const VOWELS_ADDING_E = new Set( [ 'a' , 'i' , 'o' , 'u' ] ) ;
const CONSONANTS_AFTER_VOWEL_ADDING_E = new Set( [ 's' ] ) ;
const CONSONANTS_ADDING_E = new Set( [ 'v' ] ) ;
const CONSONANTS_NOT_ADDING_E = new Set( [ 'w' , 'x' ] ) ;
const DOUBLE_CONSONANTS_ADDING_E = new Set( [ 'cl' , 'dl' , 'gl' , 'kl' , 'nc' , 'pl' , 'tl' ] ) ;
const REDUCING_DOUBLE_CONSONANTS = new Set( [ 'd' , 'g' , 'm' , 'n' , 'p' ] ) ;
const CONSONANTS_AFTER_VOWELS_COMBO_NOT_ADDING_E = new Set( [ 'or' ] ) ; // Last chance fix
// Remove -ing and transform to a proper verb or noun
english.undoPresentParticiple = word => {
if ( word.endsWith( 'ing' ) && word.length >= 6 && ! word.endsWith( 'ghtning' ) ) {
let ingSuffix = 'ing' ;
//if ( word.endsWith( 'ling' ) ) { ingSuffix = 'ling' ; }
let ingLen = ingSuffix.length ;
let before = word[ word.length - ingLen - 1 ] ,
before2 = word[ word.length - ingLen - 2 ] ,
before3 = word[ word.length - ingLen - 3 ] ;
if ( VOWELS.has( before ) ) {
word = word.slice( 0 , -ingLen ) ;
}
else if ( VOWELS.has( before2 ) ) {
if ( VOWELS.has( before3 ) ) {
if ( CONSONANTS_AFTER_VOWEL_ADDING_E.has( before ) && ! CONSONANTS_AFTER_VOWELS_COMBO_NOT_ADDING_E.has( before2 + before ) ) {
word = word.slice( 0 , -ingLen ) + 'e' ;
}
else {
word = word.slice( 0 , -ingLen ) ;
}
}
else if ( VOWELS_ADDING_E.has( before2 ) && ! CONSONANTS_NOT_ADDING_E.has( before ) ) {
word = word.slice( 0 , -ingLen ) + 'e' ;
}
else {
word = word.slice( 0 , -ingLen ) ;
}
}
else if ( before === before2 && REDUCING_DOUBLE_CONSONANTS.has( before ) ) {
word = word.slice( 0 , -ingLen - 1 ) ;
}
else if ( CONSONANTS_ADDING_E.has( before ) || DOUBLE_CONSONANTS_ADDING_E.has( before2 + before ) ) {
word = word.slice( 0 , -ingLen ) + 'e' ;
}
else {
word = word.slice( 0 , -ingLen ) ;
}
}
return word ;
} ;
},{}],6:[function(require,module,exports){
/*
String Kit
Copyright (c) 2014 - 2021 Cédric Ronvel
The MIT License (MIT)
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.
*/
/*
Escape collection.
*/
"use strict" ;
// From Mozilla Developper Network
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
exports.regExp = exports.regExpPattern = str => str.replace( /([.*+?^${}()|[\]/\\])/g , '\\$1' ) ;
// This replace any single $ by a double $$
exports.regExpReplacement = str => str.replace( /\$/g , '$$$$' ) ;
// Escape for string.format()
// This replace any single % by a double %%
exports.format = str => str.replace( /%/g , '%%' ) ;
exports.jsSingleQuote = str => exports.control( str ).replace( /'/g , "\\'" ) ;
exports.jsDoubleQuote = str => exports.control( str ).replace( /"/g , '\\"' ) ;
exports.shellArg = str => '\'' + str.replace( /'/g , "'\\''" ) + '\'' ;
var escapeControlMap = {
'\r': '\\r' ,
'\n': '\\n' ,
'\t': '\\t' ,
'\x7f': '\\x7f'
} ;
// Escape \r \n \t so they become readable again, escape all ASCII control character as well, using \x syntaxe
exports.control = ( str , keepNewLineAndTab = false ) => str.replace( /[\x00-\x1f\x7f]/g , match => {
if ( keepNewLineAndTab && ( match === '\n' || match === '\t' ) ) { return match ; }
if ( escapeControlMap[ match ] !== undefined ) { return escapeControlMap[ match ] ; }
var hex = match.charCodeAt( 0 ).toString( 16 ) ;
if ( hex.length % 2 ) { hex = '0' + hex ; }
return '\\x' + hex ;
} ) ;
var escapeHtmlMap = {
'&': '&' ,
'<': '<' ,
'>': '>' ,
'"': '"' ,
"'": '''
} ;
// Only escape & < > so this is suited for content outside tags
exports.html = str => str.replace( /[&<>]/g , match => escapeHtmlMap[ match ] ) ;
// Escape & < > " so this is suited for content inside a double-quoted attribute
exports.htmlAttr = str => str.replace( /[&<>"]/g , match => escapeHtmlMap[ match ] ) ;
// Escape all html special characters & < > " '
exports.htmlSpecialChars = str => str.replace( /[&<>"']/g , match => escapeHtmlMap[ match ] ) ;
// Percent-encode all control chars and codepoint greater than 255 using percent encoding
exports.unicodePercentEncode = str => str.replace( /[\x00-\x1f\u0100-\uffff\x7f%]/g , match => {
try {
return encodeURI( match ) ;
}
catch ( error ) {
// encodeURI can throw on bad surrogate pairs, but we just strip those characters
return '' ;
}
} ) ;
// Encode HTTP header value
exports.httpHeaderValue = str => exports.unicodePercentEncode( str ) ;
},{}],7:[function(require,module,exports){
(function (Buffer){(function (){
/*
String Kit
Copyright (c) 2014 - 2021 Cédric Ronvel
The MIT License (MIT)
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.
*/
/*
String formater, inspired by C's sprintf().
*/
"use strict" ;
const inspect = require( './inspect.js' ).inspect ;
const inspectError = require( './inspect.js' ).inspectError ;
const escape = require( './escape.js' ) ;
const ansi = require( './ansi.js' ) ;
const unicode = require( './unicode.js' ) ;
const naturalSort = require( './naturalSort.js' ) ;
const StringNumber = require( './StringNumber.js' ) ;
/*
%% a single %
%s string
%S string, interpret ^ formatting
%r raw string: without sanitizer
%n natural: output the most natural representation for this type, object entries are sorted by keys
%N even more natural: avoid type hinting marks like bracket for array
%f float
%k number with metric system prefixes
%e for exponential notation (e.g. 1.23e+2)
%K for scientific notation (e.g. 1.23 × 10²)
%i %d integer
%u unsigned integer
%U unsigned positive integer (>0)
%P number to (absolute) percent (e.g.: 0.75 -> 75%)
%p number to relative percent (e.g.: 1.25 -> +25% ; 0.75 -> -25%)
%T date/time display, using ISO date, or Intl module
%t time duration, convert ms into h min s, e.g.: 2h14min52s or 2:14:52
%m convert degree into degree, minutes and seconds
%h hexadecimal (input is a number)
%x hexadecimal (input is a number), force pair of symbols (e.g. 'f' -> '0f')
%o octal
%b binary
%X hexadecimal: convert a string into hex charcode, force pair of symbols (e.g. 'f' -> '0f')
%z base64
%Z base64url
%I call string-kit's inspect()
%Y call string-kit's inspect(), but do not inspect non-enumerable
%O object (like inspect, but with ultra minimal options)
%E call string-kit's inspectError()
%J JSON.stringify()
%v roman numerals, additive variant (e.g. 4 is IIII instead of IV)
%V roman numerals
%D drop
%F filter function existing in the 'this' context, e.g. %[filter:%a%a]F
%a argument for a function
Candidate format:
%A for automatic type? probably not good: it's like %n Natural
%c for char? (can receive a string or an integer translated into an UTF8 chars)
%C for currency formating?
%B for Buffer objects?
*/
exports.formatMethod = function( ... args ) {
var arg ,
str = args[ 0 ] ,
autoIndex = 1 ,
length = args.length ;
if ( typeof str !== 'string' ) {
if ( ! str ) { str = '' ; }
else if ( typeof str.toString === 'function' ) { str = str.toString() ; }
else { str = '' ; }
}
var runtime = {
hasMarkup: false ,
shift: null ,
markupStack: []
} ;
if ( this.markupReset && this.startingMarkupReset ) {
str = ( typeof this.markupReset === 'function' ? this.markupReset( runtime.markupStack ) : this.markupReset ) + str ;
}
//console.log( 'format args:' , arguments ) ;
// /!\ each changes here should be reported on string.format.count() and string.format.hasFormatting() too /!\
// Note: the closing bracket is optional to prevent ReDoS
str = str.replace( /\^\[([^\]]*)]?|\^(.)|(%%)|%([+-]?)([0-9]*)(?:\[([^\]]*)\])?([a-zA-Z])/g ,
( match , complexMarkup , markup , doublePercent , relative , index , modeArg , mode ) => {
var replacement , i , tmp , fn , fnArgString , argMatches , argList = [] ;
//console.log( 'replaceArgs:' , arguments ) ;
if ( doublePercent ) { return '%' ; }
if ( complexMarkup ) { markup = complexMarkup ; }
if ( markup ) {
if ( this.noMarkup ) { return '^' + markup ; }
return markupReplace.call( this , runtime , match , markup ) ;
}
if ( index ) {
index = parseInt( index , 10 ) ;
if ( relative ) {
if ( relative === '+' ) { index = autoIndex + index ; }
else if ( relative === '-' ) { index = autoIndex - index ; }
}
}
else {
index = autoIndex ;
}
autoIndex ++ ;
if ( index >= length || index < 1 ) { arg = undefined ; }
else { arg = args[ index ] ; }
if ( modes[ mode ] ) {
replacement = modes[ mode ]( arg , modeArg , this ) ;
if ( this.argumentSanitizer && ! modes[ mode ].noSanitize ) { replacement = this.argumentSanitizer( replacement ) ; }
if ( this.escapeMarkup && ! modes[ mode ].noEscapeMarkup ) { replacement = exports.escapeMarkup( replacement ) ; }
if ( modeArg && ! modes[ mode ].noCommonModeArg ) { replacement = commonModeArg( replacement , modeArg ) ; }
return replacement ;
}
// Function mode
if ( mode === 'F' ) {
autoIndex -- ; // %F does not eat any arg
if ( modeArg === undefined ) { return '' ; }
tmp = modeArg.split( ':' ) ;
fn = tmp[ 0 ] ;
fnArgString = tmp[ 1 ] ;
if ( ! fn ) { return '' ; }
if ( fnArgString && ( argMatches = fnArgString.match( /%([+-]?)([0-9]*)[a-zA-Z]/g ) ) ) {
//console.log( argMatches ) ;
//console.log( fnArgString ) ;
for ( i = 0 ; i < argMatches.length ; i ++ ) {
relative = argMatches[ i ][ 1 ] ;
index = argMatches[ i ][ 2 ] ;
if ( index ) {
index = parseInt( index , 10 ) ;
if ( relative ) {
if ( relative === '+' ) { index = autoIndex + index ; } // jshint ignore:line
else if ( relative === '-' ) { index = autoIndex - index ; } // jshint ignore:line
}
}
else {
index = autoIndex ;
}
autoIndex ++ ;
if ( index >= length || index < 1 ) { argList[ i ] = undefined ; }
else { argList[ i ] = args[ index ] ; }
}
}
if ( ! this || ! this.fn || typeof this.fn[ fn ] !== 'function' ) { return '' ; }
return this.fn[ fn ].apply( this , argList ) ;
}
return '' ;
}
) ;
if ( runtime.hasMarkup && this.markupReset && this.endingMarkupReset ) {
str += typeof this.markupReset === 'function' ? this.markupReset( runtime.markupStack ) : this.markupReset ;
}
if ( this.extraArguments ) {
for ( ; autoIndex < length ; autoIndex ++ ) {
arg = args[ autoIndex ] ;
if ( arg === null || arg === undefined ) { continue ; }
else if ( typeof arg === 'string' ) { str += arg ; }
else if ( typeof arg === 'number' ) { str += arg ; }
else if ( typeof arg.toString === 'function' ) { str += arg.toString() ; }
}
}
return str ;
} ;
exports.markupMethod = function( str ) {
if ( typeof str !== 'string' ) {
if ( ! str ) { str = '' ; }
else if ( typeof str.toString === 'function' ) { str = str.toString() ; }
else { str = '' ; }
}
var runtime = {
hasMarkup: false ,
shift: null ,
markupStack: []
} ;
if ( this.parse ) {
let markupObjects , markupObject , match , complexMarkup , markup , raw , lastChunk ,
output = [] ;
// Note: the closing bracket is optional to prevent ReDoS
for ( [ match , complexMarkup , markup , raw ] of str.matchAll( /\^\[([^\]]*)]?|\^(.)|([^^]+)/g ) ) {
if ( raw ) {
if ( output.length ) { output[ output.length - 1 ].text += raw ; }
else { output.push( { text: raw } ) ; }
continue ;
}
if ( complexMarkup ) { markup = complexMarkup ; }
markupObjects = markupReplace.call( this , runtime , match , markup ) ;
if ( ! Array.isArray( markupObjects ) ) { markupObjects = [ markupObjects ] ; }
for ( markupObject of markupObjects ) {
lastChunk = output.length ? output[ output.length - 1 ] : null ;
if ( typeof markupObject === 'string' ) {
// This markup is actually a text to add to the last chunk (e.g. "^^" markup is converted to a single "^")
if ( lastChunk ) { lastChunk.text += markupObject ; }
else { output.push( { text: markupObject } ) ; }
}
else if ( ! markupObject ) {
// Null is for a markup's style reset
if ( lastChunk && lastChunk.text.length && Object.keys( lastChunk ).length > 1 ) {
// If there was style and text on the last chunk, then this means that the new markup starts a new chunk
// markupObject can be null for markup reset function, but we have to create a new chunk
output.push( { text: '' } ) ;
}
}
else {
if ( lastChunk && lastChunk.text.length ) {
// If there was text on the last chunk, then this means that the new markup starts a new chunk
output.push( Object.assign( { text: '' } , ... runtime.markupStack ) ) ;
}
else {
// There wasn't any text added, so append the current markup style to the current chunk
if ( lastChunk ) { Object.assign( lastChunk , markupObject ) ; }
else { output.push( Object.assign( { text: '' } , markupObject ) ) ; }
}
}
}
}
return output ;
}
if ( this.markupReset && this.startingMarkupReset ) {
str = ( typeof this.markupReset === 'function' ? this.markupReset( runtime.markupStack ) : this.markupReset ) + str ;
}
str = str.replace( /\^\[([^\]]*)]?|\^(.)/g , ( match , complexMarkup , markup ) => markupReplace.call( this , runtime , match , complexMarkup || markup ) ) ;
if ( runtime.hasMarkup && this.markupReset && this.endingMarkupReset ) {
str += typeof this.markupReset === 'function' ? this.markupReset( runtime.markupStack ) : this.markupReset ;
}
return str ;
} ;
// Used by both formatMethod and markupMethod
function markupReplace( runtime , match , markup ) {
var markupTarget , key , value , replacement , colonIndex ;
if ( markup === '^' ) { return '^' ; }
if ( this.shiftMarkup && this.shiftMarkup[ markup ] ) {
runtime.shift = this.shiftMarkup[ markup ] ;
return '' ;
}
if ( markup.length > 1 && this.dataMarkup && ( colonIndex = markup.indexOf( ':' ) ) !== -1 ) {
key = markup.slice( 0 , colonIndex ) ;
markupTarget = this.dataMarkup[ key ] ;
if ( markupTarget === undefined ) {
if ( this.markupCatchAll === undefined ) { return '' ; }
markupTarget = this.markupCatchAll ;
}
runtime.hasMarkup = true ;
value = markup.slice( colonIndex + 1 ) ;
if ( typeof markupTarget === 'function' ) {
replacement = markupTarget( runtime.markupStack , key , value ) ;
// method should manage markup stack themselves
}
else {
replacement = { [ markupTarget ]: value } ;
stackMarkup( runtime , replacement ) ;
}
return replacement ;
}
if ( runtime.shift ) {
markupTarget = this.shiftedMarkup?.[ runtime.shift ]?.[ markup ] ;
runtime.shift = null ;
}
else {
markupTarget = this.markup?.[ markup ] ;
}
if ( markupTarget === undefined ) {
if ( this.markupCatchAll === undefined ) { return '' ; }
markupTarget = this.markupCatchAll ;
}
runtime.hasMarkup = true ;
if ( typeof markupTarget === 'function' ) {
replacement = markupTarget( runtime.markupStack , markup ) ;
// method should manage markup stack themselves
}
else {
replacement = markupTarget ;
stackMarkup( runtime , replacement ) ;
}
return replacement ;
}
// internal method for markupReplace()
function stackMarkup( runtime , replacement ) {
if ( Array.isArray( replacement ) ) {
for ( let item of replacement ) {
if ( item === null ) { runtime.markupStack.length = 0 ; }
else { runtime.markupStack.push( item ) ; }
}
}
else {
if ( replacement === null ) { runtime.markupStack.length = 0 ; }
else { runtime.markupStack.push( replacement ) ; }
}
}
// Note: the closing bracket is optional to prevent ReDoS
exports.stripMarkup = str => str.replace( /\^\[[^\]]*]?|\^./g , match =>
match === '^^' ? '^' :
match === '^ ' ? ' ' :
''
) ;
exports.escapeMarkup = str => str.replace( /\^/g , '^^' ) ;
const DEFAULT_FORMATTER = {
argumentSanitizer: str => escape.control( str , true ) ,
extraArguments: true ,
color: false ,
noMarkup: false ,
escapeMarkup: false ,
endingMarkupReset: true ,
startingMarkupReset: false ,
markupReset: ansi.reset ,
shiftMarkup: {
'#': 'background'
} ,
markup: {
":": ansi.reset ,
" ": ansi.reset + " " ,
"-": ansi.dim ,
"+": ansi.bold ,
"_": ansi.underline ,
"/": ansi.italic ,
"!": ansi.inverse ,
"b": ansi.blue ,
"B": ansi.brightBlue ,
"c": ansi.cyan ,
"C": ansi.brightCyan ,
"g": ansi.green ,
"G": ansi.brightGreen ,
"k": ansi.black ,
"K": ansi.brightBlack ,
"m": ansi.magenta ,
"M": ansi.brightMagenta ,
"r": ansi.red ,
"R": ansi.brightRed ,
"w": ansi.white ,
"W": ansi