From c7b688207c997bd700753addc30487599be1eec4 Mon Sep 17 00:00:00 2001 From: axiosleo Date: Wed, 18 Nov 2026 10:14:03 +0800 Subject: [PATCH 01/12] feat: replace moment.js with custom datetime function for logging timestamps --- src/debug.js | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/debug.js b/src/debug.js index 80a4d81..ebf718c 100644 --- a/src/debug.js +++ b/src/debug.js @@ -2,10 +2,20 @@ const os = require('os'); const { prompt } = require('enquirer'); -const moment = require('moment'); var count = 0; +/** + * current local time as "YYYY-MM-DD HH:mm:ss" + */ +function datetime() { + const now = new Date(); + const pad = (n) => `${n}`.padStart(2, '0'); + const date = [now.getFullYear(), pad(now.getMonth() + 1), pad(now.getDate())].join('-'); + const time = [pad(now.getHours()), pad(now.getMinutes()), pad(now.getSeconds())].join(':'); + return `${date} ${time}`; +} + function emit(data) { // eslint-disable-next-line no-console data.forEach(d => console.log(d)); @@ -28,7 +38,7 @@ function dump(...data) { } function log(...data) { - pos('log', '38;5;243', `\x1b[33m[${moment().format('YYYY-MM-DD HH:mm:ss')}]\x1b[0m `); + pos('log', '38;5;243', `\x1b[33m[${datetime()}]\x1b[0m `); // eslint-disable-next-line no-console console.log.apply(this, data); } From 1d1940a99b94dce9471e9e9ca4ae41f5735faa7c Mon Sep 17 00:00:00 2001 From: axiosleo Date: Wed, 18 Nov 2026 10:14:16 +0800 Subject: [PATCH 02/12] refactor: replace colors.js dependency with a custom implementation in lib/colors.js --- src/lib/colors.js | 622 ++++++++++++++++++++++++++++++++++++++++++++++ src/printer.js | 6 +- 2 files changed, 623 insertions(+), 5 deletions(-) create mode 100644 src/lib/colors.js diff --git a/src/lib/colors.js b/src/lib/colors.js new file mode 100644 index 0000000..fd89be1 --- /dev/null +++ b/src/lib/colors.js @@ -0,0 +1,622 @@ +'use strict'; + +/** + * ****************************************************** + * @author https://github.com/Marak/colors.js * + * @description reference source code for compatibility * + * ****************************************************** + * + * Single-file port of colors@1.4.0, so that this package does not depend on + * "colors" any more. It behaves like `require('colors')`, including the + * String.prototype getters ('text'.red, 'text'.bold, ...). + * + * The MIT License (MIT) + * + * Original Library + * - Copyright (c) Marak Squires + * + * Additional functionality + * - Copyright (c) Sindre Sorhus (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. + */ + +const os = require('os'); +const util = require('util'); + +/** + * color support detection + */ + +function hasFlag(flag, argv) { + argv = argv || process.argv; + + const terminatorPos = argv.indexOf('--'); + const prefix = /^-{1,2}/.test(flag) ? '' : '--'; + const pos = argv.indexOf(prefix + flag); + + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); +} + +const env = process.env; + +let forceColor; +if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level: level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3, + }; +} + +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } + + if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + const min = forceColor ? 1 : 0; + + 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(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + const known = ['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function (sign) { + return sign in env; + }); + if (known || 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 ('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 'Hyper': + return 3; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + return min; +} + +function getSupportLevel(stream) { + return translateLevel(supportsColor(stream)); +} + +/** + * ANSI styles + */ + +const codes = { + reset: [0, 0], + + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], + + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + grey: [90, 39], + + brightRed: [91, 39], + brightGreen: [92, 39], + brightYellow: [93, 39], + brightBlue: [94, 39], + brightMagenta: [95, 39], + brightCyan: [96, 39], + brightWhite: [97, 39], + + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + bgGray: [100, 49], + bgGrey: [100, 49], + + bgBrightRed: [101, 49], + bgBrightGreen: [102, 49], + bgBrightYellow: [103, 49], + bgBrightBlue: [104, 49], + bgBrightMagenta: [105, 49], + bgBrightCyan: [106, 49], + bgBrightWhite: [107, 49], + + // legacy styles for colors pre v1.0.0 + blackBG: [40, 49], + redBG: [41, 49], + greenBG: [42, 49], + yellowBG: [43, 49], + blueBG: [44, 49], + magentaBG: [45, 49], + cyanBG: [46, 49], + whiteBG: [47, 49], +}; + +const ansiStyles = {}; +Object.keys(codes).forEach(function (key) { + const style = []; + style.open = '\u001b[' + codes[key][0] + 'm'; + style.close = '\u001b[' + codes[key][1] + 'm'; + ansiStyles[key] = style; +}); + +/** + * colors + */ + +const colors = {}; + +colors.themes = {}; +colors.styles = ansiStyles; +colors.supportsColor = getSupportLevel; +colors.enabled = colors.supportsColor() !== false; + +colors.enable = function () { + colors.enabled = true; +}; + +colors.disable = function () { + colors.enabled = false; +}; + +colors.strip = function (str) { + // eslint-disable-next-line no-control-regex + return ('' + str).replace(/\x1B\[\d+m/g, ''); +}; +colors.stripColors = colors.strip; + +colors.stylize = function stylize(str, style) { + if (!colors.enabled) { + return str + ''; + } + + const styleMap = ansiStyles[style]; + + // Stylize should work for non-ANSI styles, too + if (!styleMap && style in colors) { + // Style maps like trap operate as functions on strings; + // they don't have properties like open or close. + return colors[style](str); + } + + return styleMap.open + str + styleMap.close; +}; + +/** + * chainable style functions: colors.red.bold('text') + */ + +const newLineRegex = /[\r\n]+/g; +const matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + +function escapeStringRegexp(str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + return str.replace(matchOperatorsRe, '\\$&'); +} + +function applyStyle() { + const args = Array.prototype.slice.call(arguments); + + let str = args.map(function (arg) { + if (arg !== null && typeof arg !== 'undefined' && arg.constructor === String) { + return arg; + } + return util.inspect(arg); + }).join(' '); + + if (!colors.enabled || !str) { + return str; + } + + const newLinesPresent = str.indexOf('\n') !== -1; + const nestedStyles = this._styles; + + let i = nestedStyles.length; + while (i--) { + const code = ansiStyles[nestedStyles[i]]; + str = code.open + str.replace(code.closeRe, code.open) + code.close; + if (newLinesPresent) { + str = str.replace(newLineRegex, function (match) { + return code.close + match + code.open; + }); + } + } + + return str; +} + +// the prototype shared by every style function, it carries one getter per style +const proto = function colors() { }; + +function build(_styles) { + const builder = function builder() { + return applyStyle.apply(builder, arguments); + }; + builder._styles = _styles; + // a function can only get another prototype this way + Object.setPrototypeOf(builder, proto); + return builder; +} + +ansiStyles.grey = ansiStyles.gray; +Object.keys(ansiStyles).forEach(function (key) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + Object.defineProperty(proto, key, { + get: function () { + return build(this._styles.concat(key)); + }, + }); +}); + +/** + * themes, they also extend String.prototype + */ + +function addProperty(name, func) { + // same attributes as String.prototype.__defineGetter__(name, func) + // eslint-disable-next-line no-extend-native + Object.defineProperty(String.prototype, name, { + get: function () { + // colors@1.4.0 is sloppy mode code: its getters receive a String object + return func(Object(this)); + }, + enumerable: true, + configurable: true, + }); +} + +// methods of String that should not be overwritten by a theme +const stringPrototypeBlacklist = [ + '__defineGetter__', '__defineSetter__', '__lookupGetter__', + '__lookupSetter__', 'charAt', 'constructor', 'hasOwnProperty', + 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', + 'valueOf', 'charCodeAt', 'indexOf', 'lastIndexOf', 'length', + 'localeCompare', 'match', 'repeat', 'replace', 'search', 'slice', + 'split', 'substring', 'toLocaleLowerCase', 'toLocaleUpperCase', + 'toLowerCase', 'toUpperCase', 'trim', 'trimLeft', 'trimRight', +]; + +function applyTheme(theme) { + Object.keys(theme).forEach(function (prop) { + if (stringPrototypeBlacklist.indexOf(prop) !== -1) { + // eslint-disable-next-line no-console + console.log('warn: '.red + ('String.prototype' + prop).magenta + + ' is probably something you don\'t want to override. ' + + 'Ignoring style name'); + return; + } + if (typeof theme[prop] === 'string') { + colors[prop] = colors[theme[prop]]; + addProperty(prop, function (str) { + return colors[prop](str); + }); + return; + } + const themePropApplicator = function (str) { + let ret = str; + for (let t = 0; t < theme[prop].length; t++) { + ret = colors[theme[prop][t]](ret); + } + return ret; + }; + addProperty(prop, themePropApplicator); + colors[prop] = function (str) { + return themePropApplicator(str); + }; + }); +} + +colors.setTheme = function (theme) { + if (typeof theme === 'string') { + // eslint-disable-next-line no-console + console.log('colors.setTheme now only accepts an object, not a string. ' + + 'If you are trying to set a theme from a file, it is now your (the ' + + 'caller\'s) responsibility to require the file. The old syntax ' + + 'looked like colors.setTheme(__dirname + ' + + '\'/../themes/generic-logging.js\'); The new syntax looks like ' + + 'colors.setTheme(require(__dirname + ' + + '\'/../themes/generic-logging.js\'));'); + return; + } + applyTheme(theme); +}; + +/** + * custom formatters + */ + +const trapChars = { + a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'], + b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'], + c: ['\u00a9', '\u023b', '\u03fe'], + d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'], + e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc', '\u0a6c'], + f: ['\u04fa'], + g: ['\u0262'], + h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'], + i: ['\u0f0f'], + j: ['\u0134'], + k: ['\u0138', '\u04a0', '\u04c3', '\u051e'], + l: ['\u0139'], + m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'], + n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'], + o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd', '\u06dd', '\u0e4f'], + p: ['\u01f7', '\u048e'], + q: ['\u09cd'], + r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'], + s: ['\u00a7', '\u03de', '\u03df', '\u03e8'], + t: ['\u0141', '\u0166', '\u0373'], + u: ['\u01b1', '\u054d'], + v: ['\u05d8'], + w: ['\u0428', '\u0460', '\u047c', '\u0d70'], + x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'], + y: ['\u00a5', '\u04b0', '\u04cb'], + z: ['\u01b5', '\u0240'], +}; + +colors.trap = function runTheTrap(text, options) { + let result = ''; + text = text || 'Run the trap, drop the bass'; + text.split('').forEach(function (c) { + c = c.toLowerCase(); + const chars = trapChars[c] || [' ']; + const rand = Math.floor(Math.random() * chars.length); + if (typeof trapChars[c] !== 'undefined') { + result += trapChars[c][rand]; + } else { + result += c; + } + }); + return result; +}; + +// combining characters +const soul = { + up: [ + '\u030d', '\u030e', '\u0304', '\u0305', '\u033f', '\u0311', + '\u0306', '\u0310', '\u0352', '\u0357', '\u0351', '\u0307', + '\u0308', '\u030a', '\u0342', '\u0313', '\u0308', '\u034a', + '\u034b', '\u034c', '\u0303', '\u0302', '\u030c', '\u0350', + '\u0300', '\u0301', '\u030b', '\u030f', '\u0312', '\u0313', + '\u0314', '\u033d', '\u0309', '\u0363', '\u0364', '\u0365', + '\u0366', '\u0367', '\u0368', '\u0369', '\u036a', '\u036b', + '\u036c', '\u036d', '\u036e', '\u036f', '\u033e', '\u035b', + '\u0346', '\u031a', + ], + down: [ + '\u0316', '\u0317', '\u0318', '\u0319', '\u031c', '\u031d', + '\u031e', '\u031f', '\u0320', '\u0324', '\u0325', '\u0326', + '\u0329', '\u032a', '\u032b', '\u032c', '\u032d', '\u032e', + '\u032f', '\u0330', '\u0331', '\u0332', '\u0333', '\u0339', + '\u033a', '\u033b', '\u033c', '\u0345', '\u0347', '\u0348', + '\u0349', '\u034d', '\u034e', '\u0353', '\u0354', '\u0355', + '\u0356', '\u0359', '\u035a', '\u0323', + ], + mid: [ + '\u0315', '\u031b', '\u0300', '\u0301', '\u0358', '\u0321', + '\u0322', '\u0327', '\u0328', '\u0334', '\u0335', '\u0336', + '\u035c', '\u035d', '\u035e', '\u035f', '\u0360', '\u0362', + '\u0338', '\u0337', '\u0361', ' \u0489', + ], +}; + +function randomNumber(range) { + return Math.floor(Math.random() * range); +} + +colors.zalgo = function zalgo(text, options) { + text = text || ' he is here '; + options = options || {}; + options['up'] = typeof options['up'] !== 'undefined' ? options['up'] : true; + options['mid'] = typeof options['mid'] !== 'undefined' ? options['mid'] : true; + options['down'] = typeof options['down'] !== 'undefined' ? options['down'] : true; + options['size'] = typeof options['size'] !== 'undefined' ? options['size'] : 'maxi'; + + let result = ''; + text.split('').forEach(function (character) { + result = result + character; + const counts = { up: 0, down: 0, mid: 0 }; + switch (options.size) { + case 'mini': + counts.up = randomNumber(8); + counts.mid = randomNumber(2); + counts.down = randomNumber(8); + break; + case 'maxi': + counts.up = randomNumber(16) + 3; + counts.mid = randomNumber(4) + 1; + counts.down = randomNumber(64) + 3; + break; + default: + counts.up = randomNumber(8) + 1; + counts.mid = randomNumber(6) / 2; + counts.down = randomNumber(8) + 1; + break; + } + + ['up', 'mid', 'down'].forEach(function (index) { + for (let i = 0; i <= counts[index]; i++) { + if (options[index]) { + result = result + soul[index][randomNumber(soul[index].length)]; + } + } + }); + }); + return result; +}; + +/** + * maps: one style per letter + */ + +colors.maps = {}; + +colors.maps.america = function (letter, i, exploded) { + if (letter === ' ') { + return letter; + } + switch (i % 3) { + case 0: return colors.red(letter); + case 1: return colors.white(letter); + case 2: return colors.blue(letter); + } +}; + +colors.maps.zebra = function (letter, i, exploded) { + return i % 2 === 0 ? letter : colors.inverse(letter); +}; + +// RoY G BiV +const rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; + +colors.maps.rainbow = function (letter, i, exploded) { + if (letter === ' ') { + return letter; + } + return colors[rainbowColors[i % rainbowColors.length]](letter); +}; + +const randomStyles = [ + 'underline', 'inverse', 'grey', 'yellow', 'red', 'green', + 'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed', + 'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta', +]; + +colors.maps.random = function (letter, i, exploded) { + if (letter === ' ') { + return letter; + } + return colors[randomStyles[Math.round(Math.random() * (randomStyles.length - 2))]](letter); +}; + +Object.keys(colors.maps).forEach(function (map) { + colors[map] = function (str) { + return str.split('').map(colors.maps[map]).join(''); + }; +}); + +Object.keys(ansiStyles).forEach(function (name) { + Object.defineProperty(colors, name, { + get: function () { + return build([name]); + }, + }); +}); + +/** + * 'text'.red, 'text'.strip, 'text'.rainbow ... + */ + +addProperty('strip', function (str) { + return colors.strip(str); +}); + +addProperty('stripColors', function (str) { + return colors.strip(str); +}); + +['trap', 'zalgo', 'zebra', 'rainbow', 'random', 'america'].forEach(function (name) { + addProperty(name, function (str) { + return colors[name](str); + }); +}); + +Object.keys(colors.styles).forEach(function (style) { + addProperty(style, function (str) { + return colors.stylize(str, style); + }); +}); + +module.exports = colors; diff --git a/src/printer.js b/src/printer.js index 51250e7..e3a2881 100644 --- a/src/printer.js +++ b/src/printer.js @@ -1,13 +1,9 @@ 'use strict'; -/** - * @require https://github.com/Marak/colors.js - */ - const { _fixed } = require('./helper/str'); const is = require('./helper/is'); const os = require('os'); -const colors = require('colors'); +const colors = require('./lib/colors'); let quiet = false; let buffer = ''; From 7b8fcd2eb3b6f47230f04b93833bd696c061beef Mon Sep 17 00:00:00 2001 From: axiosleo Date: Wed, 18 Nov 2026 10:14:28 +0800 Subject: [PATCH 03/12] refactor: replace moment.js with Date.now() for timestamp logging in workflow --- src/workflow.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/workflow.js b/src/workflow.js index 5eddcf9..77a2258 100644 --- a/src/workflow.js +++ b/src/workflow.js @@ -1,6 +1,5 @@ 'use strict'; -const moment = require('moment'); const debug = require('./debug'); function next(workflows, curr) { @@ -31,14 +30,14 @@ class Workflow { const operator = this.operator; context.curr = { workflow: curr, - start: moment().valueOf(), + start: Date.now(), end: null, success: null, error: null }; let res = await operator[curr].call(this, context); context.curr.success = true; - context.curr.end = moment().valueOf(); + context.curr.end = Date.now(); if (!context.step_data) { context.step_data = {}; } @@ -68,7 +67,7 @@ class Workflow { context.success = false; context.curr.success = false; context.curr.error = e; - context.curr.end = moment().valueOf(); + context.curr.end = Date.now(); context.step_data[context.curr.workflow] = context.curr; reject(context); }); From 5fba066d0319bec611c7ce28772b70c016a73f68 Mon Sep 17 00:00:00 2001 From: axiosleo Date: Wed, 18 Nov 2026 10:14:46 +0800 Subject: [PATCH 04/12] refactor: remove redundant fill calculation in _fixed function and simplify variable declaration in preserveCamelCase --- src/helper/str.js | 1 - src/lib/camelcase.js | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/helper/str.js b/src/helper/str.js index 1050164..f3472ff 100644 --- a/src/helper/str.js +++ b/src/helper/str.js @@ -147,7 +147,6 @@ function _fixed(content, length = 10, fillPosition = 'r', fill = ' ') { } else { rightFill = fill.repeat(length - len); } - fill = fill.repeat(length - len); content = leftFill + content + rightFill; } return content; diff --git a/src/lib/camelcase.js b/src/lib/camelcase.js index 3887fba..2f69ba6 100644 --- a/src/lib/camelcase.js +++ b/src/lib/camelcase.js @@ -21,11 +21,10 @@ const preserveCamelCase = (string, toLowerCase, toUpperCase, preserveConsecutive let isLastCharLower = false; let isLastCharUpper = false; let isLastLastCharUpper = false; - let isLastLastCharPreserved = false; for (let index = 0; index < string.length; index++) { const character = string[index]; - isLastLastCharPreserved = index > 2 ? string[index - 3] === '-' : true; + const isLastLastCharPreserved = index > 2 ? string[index - 3] === '-' : true; if (isLastCharLower && UPPERCASE.test(character)) { string = string.slice(0, index) + '-' + string.slice(index); From bec64e58e7c82bdde3b096fb31820837c41711fb Mon Sep 17 00:00:00 2001 From: axiosleo Date: Wed, 18 Nov 2026 10:14:52 +0800 Subject: [PATCH 05/12] refactor: remove Windows locale functions and adjust locale detection logic for improved clarity --- src/lib/os-locale.js | 25 ++++--------------------- 1 file changed, 4 insertions(+), 21 deletions(-) diff --git a/src/lib/os-locale.js b/src/lib/os-locale.js index 8b1fe5b..9ddf4a6 100644 --- a/src/lib/os-locale.js +++ b/src/lib/os-locale.js @@ -7,7 +7,6 @@ * ****************************************************** */ -const lcid = require('lcid'); const { exec, execSync } = require('./exec.js'); const defaultOptions = { spawn: true }; @@ -75,20 +74,6 @@ function getUnixLocaleSync() { return getLocale(parseLocale(getStdOutSync('locale'))); } -async function getWinLocale() { - const stdout = await getStdOut('wmic', ['os', 'get', 'locale']); - const lcidCode = Number.parseInt(stdout.replace('Locale', ''), 16); - - return lcid.from(lcidCode); -} - -function getWinLocaleSync() { - const stdout = getStdOutSync('wmic', ['os', 'get', 'locale']); - const lcidCode = Number.parseInt(stdout.replace('Locale', ''), 16); - - return lcid.from(lcidCode); -} - function normalise(input) { return input.replace(/_/, '-'); } @@ -105,10 +90,9 @@ async function osLocale(options = defaultOptions) { try { const envLocale = getEnvLocale(); - if (envLocale || options.spawn === false) { + // the system locale is not detected on Windows, only the environment variables are used + if (envLocale || options.spawn === false || process.platform === 'win32') { locale = getLocale(envLocale); - } else if (process.platform === 'win32') { - locale = await getWinLocale(); } else if (process.platform === 'darwin') { locale = await getAppleLocale(); } else { @@ -133,10 +117,9 @@ function osLocaleSync(options = defaultOptions) { try { const envLocale = getEnvLocale(); - if (envLocale || options.spawn === false) { + // the system locale is not detected on Windows, only the environment variables are used + if (envLocale || options.spawn === false || process.platform === 'win32') { locale = getLocale(envLocale); - } else if (process.platform === 'win32') { - locale = getWinLocaleSync(); } else if (process.platform === 'darwin') { locale = getAppleLocaleSync(); } else { From 3285048c4d7731f8d652f785df622d4dee487df7 Mon Sep 17 00:00:00 2001 From: axiosleo Date: Wed, 18 Nov 2026 10:15:01 +0800 Subject: [PATCH 06/12] refactor: simplify ESLint configuration by removing FlatCompat and updating global assignment rule --- eslint.config.mjs | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/eslint.config.mjs b/eslint.config.mjs index 065ccb8..e2ad545 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -1,22 +1,11 @@ import globals from "globals"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; import js from "@eslint/js"; -import { FlatCompat } from "@eslint/eslintrc"; - -const __filename = fileURLToPath(import.meta.url); -const __dirname = path.dirname(__filename); -const compat = new FlatCompat({ - baseDirectory: __dirname, - recommendedConfig: js.configs.recommended, - allConfig: js.configs.all -}); export default [ { ignores: ['eslint.config.mjs'] }, - ...compat.extends("eslint:recommended"), + js.configs.recommended, { languageOptions: { globals: { @@ -59,7 +48,7 @@ export default [ "no-labels": 2, "no-with": 2, "no-loop-func": 2, - "no-native-reassign": 2, + "no-global-assign": 2, "no-redeclare": [2, { builtinGlobals: true, From 9d059544b26344d8f816ea0cde6f74d4dcc72566 Mon Sep 17 00:00:00 2001 From: axiosleo Date: Wed, 18 Nov 2026 10:15:06 +0800 Subject: [PATCH 07/12] refactor: convert module exports to namespaces and enhance Color interface with additional string methods --- index.d.ts | 101 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 95 insertions(+), 6 deletions(-) diff --git a/index.d.ts b/index.d.ts index 471be6b..bbe5d14 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,6 +1,5 @@ import Big from 'big.js'; import { ChildProcess, SpawnOptionsWithoutStdio } from 'child_process'; -import { Color } from 'colors'; type Level = number | null | boolean | string; @@ -352,7 +351,7 @@ interface LocalesConfig { format?: string } -export module locales { +export namespace locales { class Translator { constructor(options: LocalesConfig); @@ -409,6 +408,96 @@ export module locales { function disable(): void; } +/** + * The same typings as colors@1.4.0, the implementation is src/lib/colors.js + */ +interface Color { + (text: string): string; + + strip: Color; + stripColors: Color; + + black: Color; + red: Color; + green: Color; + yellow: Color; + blue: Color; + magenta: Color; + cyan: Color; + white: Color; + gray: Color; + grey: Color; + + bgBlack: Color; + bgRed: Color; + bgGreen: Color; + bgYellow: Color; + bgBlue: Color; + bgMagenta: Color; + bgCyan: Color; + bgWhite: Color; + + reset: Color; + bold: Color; + dim: Color; + italic: Color; + underline: Color; + inverse: Color; + hidden: Color; + strikethrough: Color; + + rainbow: Color; + zebra: Color; + america: Color; + trap: Color; + random: Color; + zalgo: Color; +} + +declare global { + interface String { + strip: string; + stripColors: string; + + black: string; + red: string; + green: string; + yellow: string; + blue: string; + magenta: string; + cyan: string; + white: string; + gray: string; + grey: string; + + bgBlack: string; + bgRed: string; + bgGreen: string; + bgYellow: string; + bgBlue: string; + bgMagenta: string; + bgCyan: string; + bgWhite: string; + + reset: string; + // @ts-ignore + bold: string; + dim: string; + italic: string; + underline: string; + inverse: string; + hidden: string; + strikethrough: string; + + rainbow: string; + zebra: string; + america: string; + trap: string; + random: string; + zalgo: string; + } +} + interface Printer { colors: Color /** @@ -743,7 +832,7 @@ export namespace helper { name: string, } - module obj { + namespace obj { function _flatten(obj: ObjectItem, sep?: string): ObjectItem; function _flatten(obj: T, sep: string): ObjectItem; function _unflatten(obj: ObjectItem, sep: string): ObjectItem; @@ -761,7 +850,7 @@ export namespace helper { encoding?: string // default is 'utf8' } - module str { + namespace str { class Emitter { config: EmitterConfig constructor(options?: EmitterConfig) @@ -875,7 +964,7 @@ export namespace helper { * @param dict 0123456789abcdf * @param len 8 */ - function _random(dict?: string, len?: number) + function _random(dict?: string, len?: number): string; /** * get length of string @@ -896,7 +985,7 @@ export namespace helper { length?: number } - module convert { + namespace convert { /** * convert tree to array * @param tree From 533afbf1c77874bead2302fc4eb4a131b42d554f Mon Sep 17 00:00:00 2001 From: axiosleo Date: Wed, 18 Nov 2026 10:15:13 +0800 Subject: [PATCH 08/12] refactor: update test files for consistency and clarity, including adjustments to Emitter instantiation and workflow initialization --- tests/fs.tests.js | 2 +- tests/printer.tests.js | 76 +++++++++++++++++++++++++++++++++++++++++ tests/str.tests.js | 8 ++--- tests/workflow.tests.js | 4 +-- 4 files changed, 82 insertions(+), 8 deletions(-) diff --git a/tests/fs.tests.js b/tests/fs.tests.js index d5421fa..a0fc583 100644 --- a/tests/fs.tests.js +++ b/tests/fs.tests.js @@ -4,7 +4,7 @@ const path = require('path'); const chai = require('chai'); const expect = chai.expect; const fs = require('fs'); -chai.use(require('chai-as-promised')); +chai.use(require('chai-as-promised').default); const { _ext, diff --git a/tests/printer.tests.js b/tests/printer.tests.js index aa17213..15e6452 100644 --- a/tests/printer.tests.js +++ b/tests/printer.tests.js @@ -81,3 +81,79 @@ describe('print test case', function () { expect(true).to.be.true; }); }); + +describe('colors test case', function () { + const colors = printer.colors; + let enabled; + + before(function () { + // colors are turned off on CI, enable them to assert the escape codes + enabled = colors.enabled; + colors.enable(); + }); + + after(function () { + colors.enabled = enabled; + }); + + it('string properties', function () { + expect('x'.red).to.be.equal('\u001b[31mx\u001b[39m'); + expect('x'.underline).to.be.equal('\u001b[4mx\u001b[24m'); + expect('x'.bgBrightCyan).to.be.equal('\u001b[106mx\u001b[49m'); + expect('x'.grey).to.be.equal('x'.gray); + }); + + it('style functions', function () { + expect(colors.red('x')).to.be.equal('\u001b[31mx\u001b[39m'); + expect(colors.red.bold('x')).to.be.equal('\u001b[31m\u001b[1mx\u001b[22m\u001b[39m'); + expect(colors.green('a', 1)).to.be.equal('\u001b[32ma 1\u001b[39m'); + // a nested style does not end the outer one + expect(colors.red('a' + colors.blue('b') + 'c')).to.be.equal('\u001b[31ma\u001b[34mb\u001b[31mc\u001b[39m'); + // each line is styled on its own + expect(colors.red('a\nb')).to.be.equal('\u001b[31ma\u001b[39m\n\u001b[31mb\u001b[39m'); + }); + + it('themes', function () { + printer.themes({ + highlight: ['red', 'underline'], + note: 'cyan', + }); + expect('x'.highlight).to.be.equal('\u001b[4m\u001b[31mx\u001b[39m\u001b[24m'); + expect(colors.highlight('x')).to.be.equal('\u001b[4m\u001b[31mx\u001b[39m\u001b[24m'); + expect('x'.note).to.be.equal('\u001b[36mx\u001b[39m'); + expect(colors.note('x')).to.be.equal('\u001b[36mx\u001b[39m'); + }); + + it('strip', function () { + const styled = colors.red.bold('a') + 'b'.green; + expect(colors.strip(styled)).to.be.equal('ab'); + expect(colors.stripColors(styled)).to.be.equal('ab'); + expect(styled.strip).to.be.equal('ab'); + expect(styled.stripColors).to.be.equal('ab'); + }); + + it('maps', function () { + expect('ab c'.rainbow).to.be.equal('\u001b[31ma\u001b[39m\u001b[33mb\u001b[39m \u001b[34mc\u001b[39m'); + expect('abc'.zebra).to.be.equal('a\u001b[7mb\u001b[27mc'); + expect('ab c'.america).to.be.equal('\u001b[31ma\u001b[39m\u001b[37mb\u001b[39m \u001b[31mc\u001b[39m'); + expect(colors.rainbow('ab c')).to.be.equal('ab c'.rainbow); + }); + + it('random effects', function () { + ['random', 'trap', 'zalgo'].forEach((name) => { + expect('text'[name]).to.be.a('string').and.not.equal(''); + expect(colors[name]('text')).to.be.a('string').and.not.equal(''); + }); + expect('some text'.random.strip).to.be.equal('some text'); + }); + + it('disable', function () { + colors.disable(); + expect('x'.red).to.be.equal('x'); + expect('x'.highlight).to.be.equal('x'); + expect(colors.red.bold('x')).to.be.equal('x'); + expect('ab c'.rainbow).to.be.equal('ab c'); + colors.enable(); + expect('x'.red).to.be.equal('\u001b[31mx\u001b[39m'); + }); +}); diff --git a/tests/str.tests.js b/tests/str.tests.js index bcc6695..20bb996 100644 --- a/tests/str.tests.js +++ b/tests/str.tests.js @@ -91,8 +91,9 @@ describe('str test case', function () { }); it('emitter', function () { - let emitter = new Emitter(); - emitter = new Emitter({ + // the constructor also works without options + expect(new Emitter().output()).to.be.equal(''); + const emitter = new Emitter({ indent: ' ', eol: '\n', level: 0, @@ -112,8 +113,7 @@ describe('str test case', function () { }); it('emitter rows', function () { - let emitter = new Emitter(); - emitter = new Emitter({ + const emitter = new Emitter({ indent: ' ', eol: '\n', level: 0, diff --git a/tests/workflow.tests.js b/tests/workflow.tests.js index b32d392..791438f 100644 --- a/tests/workflow.tests.js +++ b/tests/workflow.tests.js @@ -84,14 +84,12 @@ describe('workflow test case', () => { b: async () => { }, c: async () => { }, }; - let workflow = new Workflow(operator); + const workflow = new Workflow(operator); const context = {}; await workflow.start(context); expect(context.success).to.be.true; expect(context.step_data).to.include.all.keys('a', 'c'); expect(context.step_data).to.not.include.all.keys('b'); - - workflow = new Workflow(operator); }); it('reset workflows', async () => { From 9792b264aca57243bcaa15eaf97edc0527c1727d Mon Sep 17 00:00:00 2001 From: axiosleo Date: Wed, 18 Nov 2026 10:15:25 +0800 Subject: [PATCH 09/12] refactor: update CI workflow to include macOS and newer Node.js versions --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6bb6316..6b6c694 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,8 +14,8 @@ jobs: runs-on: ${{ matrix.operating-system }} strategy: matrix: - operating-system: [ubuntu-latest, windows-latest] - node-version: [18, 20, 22, 24, 25] + operating-system: [ubuntu-latest, macos-latest, windows-latest] + node-version: [20, 22, 24, 26] name: Node.js ${{ matrix.node-version }} Test on ${{ matrix.operating-system }} steps: From a095b674f360c04ea5a183a7aaa5a695a3ea21d6 Mon Sep 17 00:00:00 2001 From: axiosleo Date: Wed, 18 Nov 2026 10:15:35 +0800 Subject: [PATCH 10/12] chore: update package.json dependencies and scripts for improved linting and compatibility --- package.json | 34 ++++++++++++++-------------------- 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/package.json b/package.json index 5da3025..8b6ee86 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,7 @@ "cli-tool": "./bin/cli-tool.js" }, "scripts": { - "lint": "tsc ./index.d.ts && eslint --fix src/ tests/", + "lint": "tsc --noEmit --types node --skipDefaultLibCheck ./index.d.ts && eslint --fix src/ tests/", "test": "mocha --reporter spec --timeout 3000 tests/*.tests.js", "test-cov": "nyc -r=lcov -r=html -r=text -r=json mocha -t 10000 -R spec tests/*.tests.js", "test-one": "mocha --reporter spec --timeout 3000", @@ -31,32 +31,26 @@ }, "license": "MIT", "dependencies": { - "big.js": "^6.2.1", + "big.js": "^7.0.1", "clone-deep": "^4.0.1", - "colors": "1.4.0", "enquirer": "^2.4.1", - "lcid": "~4.0.1", - "minimist": "^1.2.8", - "moment": "^2.30.1" + "minimist": "^1.2.8" }, "repository": { "type": "git", "url": "https://github.com/AxiosLeo/node-cli" }, "devDependencies": { - "@eslint/eslintrc": "^3.2.0", - "@eslint/js": "^9.17.0", - "@types/node": "18.14.2", - "chai": "4.3.7", - "chai-as-promised": "7.1.1", - "eslint": "^9.17.0", - "expect.js": "0.3.1", - "has-flag": "5.0.1", - "mm": "3.2.1", - "mocha": "10.2.0", - "mocha-sinon": "2.1.2", - "nyc": "15.1.0", - "sinon": "16.1.3", - "typescript": "4.9.5" + "@eslint/js": "^10.0.1", + "@types/big.js": "^7.0.0", + "@types/node": "26.6.6", + "chai": "6.3.0", + "chai-as-promised": "8.0.2", + "eslint": "^10.15.0", + "globals": "^17.14.0", + "mocha": "12.0.3", + "nyc": "18.0.0", + "sinon": "22.1.0", + "typescript": "7.0.2" } } From 51aa957ba3e625b1caae0be349a4f0aedd8fb17f Mon Sep 17 00:00:00 2001 From: axiosleo Date: Wed, 18 Nov 2026 10:15:58 +0800 Subject: [PATCH 11/12] Bump 2.0.0 --- bin/cli-tool.js | 2 +- commands/init.js | 2 +- package.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/bin/cli-tool.js b/bin/cli-tool.js index 1b18277..3f9ca4f 100755 --- a/bin/cli-tool.js +++ b/bin/cli-tool.js @@ -9,7 +9,7 @@ const { App } = require('..'); const app = new App({ name: 'Cli Tool', bin: 'cli-tool', - version: '1.6.12', + version: '2.0.0', desc: 'application_desc', commands_dir: path.join(__dirname, '../commands'), commands_sort: ['help', 'init', 'make', 'exec'], diff --git a/commands/init.js b/commands/init.js index eadfea6..f5edf0d 100644 --- a/commands/init.js +++ b/commands/init.js @@ -34,7 +34,7 @@ class InitCommand extends Command { }, 'license': 'MIT', 'dependencies': { - '@axiosleo/cli-tool': '^1.6.12' + '@axiosleo/cli-tool': '^2.0.0' }, 'devDependencies': { 'eslint': '*' diff --git a/package.json b/package.json index 8b6ee86..47c7c21 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@axiosleo/cli-tool", - "version": "1.6.12", + "version": "2.0.0", "description": "Design for quickly developing CLI applications using Node.js.", "keywords": [ "cli", From 3f43a4908e8659717538c4b5d31fd3c618d3999b Mon Sep 17 00:00:00 2001 From: axiosleo Date: Wed, 18 Nov 2026 10:21:28 +0800 Subject: [PATCH 12/12] chore: update Node.js version requirement to 16.0 and improve locale detection descriptions in README files --- README-CN.md | 8 +++++--- README.md | 8 +++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/README-CN.md b/README-CN.md index a639136..b1a568a 100644 --- a/README-CN.md +++ b/README-CN.md @@ -4,7 +4,7 @@ [![NPM version](https://img.shields.io/npm/v/@axiosleo/cli-tool.svg?style=flat-square)](https://npmjs.org/package/@axiosleo/cli-tool) [![npm download](https://img.shields.io/npm/dm/@axiosleo/cli-tool.svg?style=flat-square)](https://npmjs.org/package/@axiosleo/cli-tool) -[![node version](https://img.shields.io/badge/node.js-%3E=_14.0-green.svg?style=flat-square)](http://nodejs.org/download/) +[![node version](https://img.shields.io/badge/node.js-%3E=_16.0-green.svg?style=flat-square)](http://nodejs.org/download/) [![CI Build Status](https://github.com/AxiosLeo/node-cli/actions/workflows/ci.yml/badge.svg)](https://github.com/AxiosLeo/node-cli/actions/workflows/ci.yml) [![Codecov](https://codecov.io/gh/AxiosLeo/node-cli/branch/master/graph/badge.svg)](https://codecov.io/gh/AxiosLeo/node-cli) [![License](https://img.shields.io/github/license/AxiosLeo/node-cli?color=%234bc524)](LICENSE) @@ -33,7 +33,7 @@ cli-tool make cli-tool make test ./commands/ # 将会生成 ./commands/test.js 文件 # 直接执行生成的命令行脚本文件 -cli-tool exec ./command/test.js +cli-tool exec ./commands/test.js ``` ## 使用 @@ -88,6 +88,8 @@ app.exec(""); > 开启多语言模式后,应用和命令的“描述”将会根据配置的 locales json 文件,自动翻译成对应语言 > +> 检测到的系统语言在 `sets` 中时使用它,否则使用第一项。Windows 上只读取 `LC_ALL`、`LC_MESSAGES`、`LANG`、`LANGUAGE` 这几个环境变量,都没有时按 `en-US` 处理。 +> > locales 示例 json 文件 : [locales](./locales) > > 详见 [locales wiki](https://github.com/AxiosLeo/node-cli/wiki/locales) @@ -96,7 +98,7 @@ app.exec(""); const path = require("path"); app.locale({ dir: path.join(__dirname, "../locales"), // /path/to/app/locales/dir - sets: ["en-US", "zh-CN"], // 不能为空, 且第一个元素为默认值 + sets: ["en-US", "zh-CN"], // 不能为空。检测到的系统语言在列表中时使用它,否则使用第一项。 }); app.start(); // 需要在调用 app.start() 方法前配置 locale ``` diff --git a/README.md b/README.md index 6547e65..ac61211 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ English | [简体中文](/README-CN.md) [![NPM version](https://img.shields.io/npm/v/@axiosleo/cli-tool.svg?style=flat-square)](https://npmjs.org/package/@axiosleo/cli-tool) [![npm download](https://img.shields.io/npm/dm/@axiosleo/cli-tool.svg?style=flat-square)](https://npmjs.org/package/@axiosleo/cli-tool) -[![node version](https://img.shields.io/badge/node.js-%3E=_14.0-green.svg?style=flat-square)](http://nodejs.org/download/) +[![node version](https://img.shields.io/badge/node.js-%3E=_16.0-green.svg?style=flat-square)](http://nodejs.org/download/) [![CI Build Status](https://github.com/AxiosLeo/node-cli/actions/workflows/ci.yml/badge.svg)](https://github.com/AxiosLeo/node-cli/actions/workflows/ci.yml) [![Codecov](https://codecov.io/gh/AxiosLeo/node-cli/branch/master/graph/badge.svg)](https://codecov.io/gh/AxiosLeo/node-cli) [![License](https://img.shields.io/github/license/AxiosLeo/node-cli?color=%234bc524)](LICENSE) @@ -33,7 +33,7 @@ cli-tool make cli-tool make test ./commands/ # will generate command file on ./commands/test.js # run command js script -cli-tool exec ./command/test.js +cli-tool exec ./commands/test.js ``` ## Usage @@ -88,6 +88,8 @@ app.exec(""); > The "desc" of CLI Application and Command will be automatically translated by using the locales json file. > +> The detected system locale is used when it is listed in `sets`; otherwise the first item is used. On Windows only the `LC_ALL`, `LC_MESSAGES`, `LANG` and `LANGUAGE` environment variables are read, and `en-US` is used when none of them is set. +> > locales example json file : [locales](./locales) > > see detail from [locales wiki](https://github.com/AxiosLeo/node-cli/wiki/locales) @@ -96,7 +98,7 @@ app.exec(""); const path = require("path"); app.locale({ dir: path.join(__dirname, "../locales"), // /path/to/app/locales/dir - sets: ["en-US", "zh-CN"], // cannot be empty, the first set as default. + sets: ["en-US", "zh-CN"], // cannot be empty. The detected system locale is used when it is in this list, otherwise the first item. }); app.start(); // set locale before start app ```