UNPKG

ninjs-lodash

Version:
281 lines (250 loc) 10.7 kB
/** * Eyes.js - a customizable value inspector for Node.js * * usage: * * var inspect = require('eyes').inspector({styles: {all: 'magenta'}}); * inspect(something); // inspect with the settings passed to `inspector` * * or * * var eyes = require('eyes'); * eyes.inspect(something); // inspect with the default settings * * ~~~~~ Theme A ~~~~~ * all: 'cyan', // Overall style applied to everything * label: 'underline', // Inspection labels, like 'array' in `array: [1, 2, 3]` * other: 'inverted', // Objects which don't have a literal representation, such as functions * key: 'bold', // The keys in object literals, like 'a' in `{a: 1}` * special: 'grey', // null, undefined... * string: 'green', * number: 'magenta', * bool: 'blue', // true false * regexp: 'green', // /\d+/ * * ~~~~~ Theme B ~~~~~ * all: 'red', // Overall style applied to everything * label: 'underline', // Inspection labels, like 'array' in `array: [1, 2, 3]` * other: 'inverted', // Objects which don't have a literal representation, such as functions * key: 'grey', // The keys in object literals, like 'a' in `{a: 1}` * special: 'grey', // null, undefined... * string: 'greenbold', * number: 'magenta', * bool: 'blue', // true false * regexp: 'green' // /\d+/ * */ const _ = require('lodash'); const CODES = { 'bold' : [1, 22], 'underline' : [4, 24], 'inverse' : [7, 27], 'black' : [30, 39], 'red' : [31, 39], 'green' : [32, 39], 'yellow' : [33, 39], 'blue' : [34, 39], 'magenta' : [35, 39], 'cyan' : [36, 1], 'white' : [37, 39], 'blackbold' : [30, 1], 'redbold' : [31, 1], 'greenbold' : [32, 1], 'yellowbold' : [33, 1], 'bluebold' : [34, 1], 'magentabold' : [35, 1], 'cyanbold' : [36, 1], 'whitebold' : [37, 1], 'grey' : [90, 1] }; let stack = [] exports.defaults = { styles: { // Styles applied to stdout all: 'cyan', // Overall style applied to everything label: 'underline', // Inspection labels, like 'array' in `array: [1, 2, 3]` other: 'inverted', // Objects which don't have a literal representation, such as functions key: 'bold', // The keys in object literals, like 'a' in `{a: 1}` special: 'grey', // null, undefined... string: 'green', number: 'magenta', bool: 'blue', // true false regexp: 'green' // /\d+/ }, pretty: true, // Indent object literals indent: 2, hideFunctions: false, showHidden: false, sortKeys: false, stream: process.stdout, maxLength: false // Truncate output if longer }; // Return a curried inspect() function, with the `options` argument filled in. exports.inspector = function (options) { var that = this; return function (obj, label, opts) { return that.inspect.call(that, obj, label, merge(options || {}, opts || {})); }; }; // If we have a `stream` defined, use it to print a styled string, // if not, we just return the stringified object. exports.inspect = function (obj, label, options) { options = merge(this.defaults, options || {}); if (options.stream) { return this.print(stringify(obj, options), label, options); } else { return stringify(obj, options) + (options.styles ? '\033[39m' : ''); } }; // Output using the 'stream', and an optional label // Loop through `str`, and truncate it after `options.maxLength` has been reached. // Because escape sequences are, at this point embeded within // the output string, we can't measure the length of the string // in a useful way, without separating what is an escape sequence, // versus a printable character (`c`). So we resort to counting the // length manually. exports.print = function (str, label, options) { for (var c = 0, i = 0; i < str.length; i++) { if (str.charAt(i) === '\033') { i += 4 } // `4` because '\033[25m'.length + 1 == 5 else if (c === options.maxLength) { str = str.slice(0, i - 1) + '…'; break; } else { c++ } } return options.stream.write.call(options.stream, (label ? this.stylize(label, options.styles.label, options.styles) + ': ' : '') + this.stylize(str, options.styles.all, options.styles) + '\033[0m' + "\n"); }; // Apply a style to a string, eventually, // I'd like this to support passing multiple // styles. exports.stylize = function (str, style, styles) { var smap = style ? CODES[style] : null var allmap = styles.all ? CODES[styles.all] : null var allhead = allmap ? _.head(allmap) || 0 : 0 if(!smap) return str let head = _.head(smap) let last = _.last(smap) || 39 last = last === 39 && allhead ? allhead : last last = last === 1 ? last + ';' : last return '\033[' + head + 'm' + str + '\033[' + last + 'm' }; // Convert any object to a string, ready for output. // When an 'array' or an 'object' are encountered, they are // passed to specialized functions, which can then recursively call // stringify(). function stringify(obj, options) { var that = this, stylize = function (str, style) { return exports.stylize(str, options.styles[style], options.styles) }, index, result; if ((index = stack.indexOf(obj)) !== -1) { return stylize(new(Array)(stack.length - index + 1).join('.'), 'special'); } stack.push(obj); result = (function (obj) { switch (typeOf(obj)) { case "string" : return stylize(stringifyString(obj.indexOf("\"") === -1 ? "\"" + obj + "\"" : obj.indexOf("'") === -1 ? "'" + obj + "'" : obj, options), 'string') case "regexp" : return stylize('/' + obj.source + '/', 'regexp'); case "number" : return stylize(obj + '', 'number'); case "function" : return options.stream ? stylize("Function", 'other') : '[Function]'; case "null" : return stylize("null", 'special'); case "undefined" : return stylize("undefined", 'special'); case "boolean" : return stylize(obj + '', 'bool'); case "date" : return stylize(obj.toUTCString()); case "array" : return stringifyArray(obj, options, stack.length); case "object" : return stringifyObject(obj, options, stack.length); } })(obj); stack.pop(); return result; }; // Escape invisible characters in a string function stringifyString(str, options) { var result = str.replace(/\\/g, '\\\\') .replace(/\n/g, '\\n') .replace(/[\u0001-\u001F]/g, function (match) { return '\\0' + match[0].charCodeAt(0).toString(8); }); // Truncate the string if a maximum length is configured var truncate = options.hasOwnProperty('maxStringLength') && options.maxStringLength >= 0; if(truncate && result.length > options.maxStringLength) { var length = Math.min(result.length, options.maxStringLength - 3); result = result.substr(0, length) + "..."; } return result; } // Convert an array to a string, such as [1, 2, 3]. // This function calls stringify() for each of the elements // in the array. function stringifyArray(ary, options, level) { var out = []; var pretty = options.pretty && (ary.length > 4 || ary.some(function (o) { return (o !== null && typeof(o) === 'object' && Object.keys(o).length > 0) || (Array.isArray(o) && o.length > 0); })); var ws = pretty ? '\n' + new(Array)(level * options.indent + 1).join(' ') : ' '; var truncate = options.hasOwnProperty('maxArrayLength') && options.maxArrayLength >= 0; var length = truncate ? Math.min(ary.length, options.maxArrayLength) : ary.length; for (var i = 0; i < length; i++) { out.push(stringify(ary[i], options)); } // Add a special String if the array was truncated if(length < ary.length) out.push('<<truncated>>'); return out.length === 0 ? '[]' : '[' + ws + out.join(',' + (pretty ? ws : ' ')) + (pretty ? ws.slice(0, -1*options.indent) : ws) + ']'; }; // Convert an object to a string, such as {a: 1}. // This function calls stringify() for each of its values, // and does not output functions or prototype values. function stringifyObject(obj, options, level) { var out = []; var pretty = options.pretty && (Object.keys(obj).length > 2 || Object.keys(obj).some(function (k) { return typeof(obj[k]) === 'object' })); var ws = pretty ? '\n' + new(Array)(level * options.indent + 1).join(' ') : ' '; var keys = options.showHidden ? Object.keys(obj) : Object.getOwnPropertyNames(obj); if (options.sortKeys) keys.sort(); var truncate = options.hasOwnProperty('maxObjectKeys') && options.maxObjectKeys >= 0; // Slice the keys to the maximum length if they exceed the maxObjectKeys option var includeKeys = (truncate) ? keys.slice(0, options.maxObjectKeys) : keys; includeKeys.forEach(function (k) { if (Object.prototype.hasOwnProperty.call(obj, k) && !(obj[k] instanceof Function && options.hideFunctions)) { out.push(exports.stylize(`"${k}"`, options.styles.key, options.styles) + ': ' + stringify(obj[k], options)); } }); // Append a special String if the Object was truncated if (includeKeys.length < keys.length) out.push(exports.stylize('<<truncated>>', options.styles.key, options.styles)) return out.length === 0 ? '{}' : "{" + ws + out.join(',' + (pretty ? ws : ' ')) + (pretty ? ws.slice(0, -1*options.indent) : ws) + "}" }; // A better `typeof` function typeOf(value) { var s = typeof(value), types = [Object, Array, String, RegExp, Number, Function, Boolean, Date]; if (s === 'object' || s === 'function') { if (value) { types.forEach(function (t) { if (value instanceof t) { s = t.name.toLowerCase() } }); } else { s = 'null' } } return s; } function merge(/* variable args */) { var objs = Array.prototype.slice.call(arguments); var target = {}; objs.forEach(function (o) { Object.keys(o).forEach(function (k) { if (k === 'styles') { if (! o.styles) { target.styles = false; } else { target.styles = {} for (var s in o.styles) { target.styles[s] = o.styles[s]; } } } else { target[k] = o[k]; } }); }); return target; } _.mixin({ eyes: exports })