'use strict'; const internals = { kCircularString: '[Circular]', // Get High Res time depending on platform. Currently only supporting node. getHighResTime() { return process.hrtime.bigint(); } }; // Initialise relative time. internals.initialTimestamp = BigInt(Date.now()) * 1000000n; internals.initialHighResTime = internals.getHighResTime(); /** * Container object for utilities used by loggers. * * @class Utilities */ module.exports = { /** * Returns the current timestamp in nanoseconds as a bigint. * * @function now * @memberof Utilities * @return {bigint} current time in nanoseconds, including fractions. */ now() { return internals.initialTimestamp + internals.getHighResTime() - internals.initialHighResTime; }, /** * Stringifies objects, avoiding circular references. * * @function stringify * @memberof Utilities * @param {Object} object the object to stringify * @return {String} the stringified object */ stringify(object) { const cache = new Set(); return JSON.stringify(object, (key, value) => { if (typeof value === 'bigint') { return String(value) + 'n'; } if (typeof value === 'object' && value !== null) { if (cache.has(value)) { return internals.kCircularString; } cache.add(value); } return value; }); }, /** * Given an ansi keyword, it will return the appropriate code. * * @function getAnsiCode * @memberof Utilities * @param {String} ansiString the name of the desired code * @return {String} the ansi code */ getAnsiCode(ansiString) { switch (ansiString) { case 'bold': return '[1m'; case 'italics': return '[3m'; case 'underline': return '[4m'; case 'inverse': return '[7m'; case 'strikethrough': return '[9m'; case 'bold_off': return '[22m'; case 'italics_off': return '[23m'; case 'underline_off': return '[24m'; case 'inverse_off': return '[27m'; case 'strikethrough_off': return '[29m'; case 'black': return '[30m'; case 'red': return '[31m'; case 'green': return '[32m'; case 'yellow': return '[33m'; case 'blue': return '[34m'; case 'magenta': return '[35m'; case 'cyan': return '[36m'; case 'white': return '[37m'; case 'default': return '[39m'; case 'black_bg': return '[40m'; case 'red_bg': return '[41m'; case 'green_bg': return '[42m'; case 'yellow_bg': return '[43m'; case 'blue_bg': return '[44m'; case 'magenta_bg': return '[45m'; case 'cyan_bg': return '[46m'; case 'white_bg': return '[47m'; case 'default_bg': return '[49m'; case 'reset': // for informative purpouses default: return '[0m'; } }, /** * Given a level, it will return the appropriate ansi keyword related * to it. * * @function getLevelAnsi * @memberof Utilities * @param {number} level the level of the log * @return {String} the ansi keyword */ getLevelAnsi(level) { switch (level) { case 0: case 1: case 2: case 3: return 'red'; case 4: return 'yellow'; case 5: case 6: return 'blue'; case 7: return 'green'; default: return 'default'; } } };