From 28bdc0d38db1127afa90f3c5c07f6c25fec155b7 Mon Sep 17 00:00:00 2001 From: Miau Lightouch Date: Thu, 17 May 2018 18:57:11 +0800 Subject: [PATCH] Refactoring codebase close visionmedia/debug#569 close visionmedia/debug#563 --- .eslintrc.js | 23 +++ .gitignore | 64 +++++++++ CHANGELOG.md | 13 ++ README.md | 335 +++++++++++++++++++++++++++++++++++++++++++ package.json | 39 +++++ src/browser.js | 192 +++++++++++++++++++++++++ src/common.js | 147 +++++++++++++++++++ src/debug.js | 47 ++++++ src/index.js | 19 +++ src/node.js | 158 ++++++++++++++++++++ test/browser.test.js | 245 +++++++++++++++++++++++++++++++ test/common.js | 232 ++++++++++++++++++++++++++++++ test/node.test.js | 170 ++++++++++++++++++++++ 13 files changed, 1684 insertions(+) create mode 100644 .eslintrc.js create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 README.md create mode 100644 package.json create mode 100644 src/browser.js create mode 100644 src/common.js create mode 100644 src/debug.js create mode 100644 src/index.js create mode 100644 src/node.js create mode 100644 test/browser.test.js create mode 100644 test/common.js create mode 100644 test/node.test.js diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..597055d --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,23 @@ +module.exports = { + root: true, + parserOptions: { + sourceType: "module" + }, + env: { + browser: true, + node: true, + }, + extends: [ + 'plugin:jest/recommended', + 'eslint:recommended', + 'standard' + ], + plugins: ['jest'], + rules: { + // allow async-await + 'generator-star-spacing': 'off', + // allow debugger during development + 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off', + 'no-empty': ['error', { 'allowEmptyCatch': true }] + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f9d1b64 --- /dev/null +++ b/.gitignore @@ -0,0 +1,64 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# TypeScript v1 declaration files +typings/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env + +# next.js build output +.next + +# we don't need to lock package version +yarn.lock diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..eeb2f0d --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,13 @@ +# Changelog + +## 1.0.0 / 2018-05-15 + +* Breaking: Re-write in ES6 +* Breaking: createDebug.humanize move to env.humanize +* Breaking: createDebug.enabled renamed to createDebug.enabler +* Addition: nwjs support +* Addition: `process` package support +* Addition: 99% coverage test +* Fix: JSON.stringify circular issue +* Fix: Edge > 16.16215 support console colors +* Fix: window.webkitURL is existed in Edge issue diff --git a/README.md b/README.md new file mode 100644 index 0000000..98ea8cd --- /dev/null +++ b/README.md @@ -0,0 +1,335 @@ +# debug-es + +[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) +[![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) +[![JavaScript Style Guide](https://cdn.rawgit.com/standard/standard/master/badge.svg)](https://github.com/standard/standard) + + + +A tiny JavaScript debugging utility modelled after Node.js core's debugging +technique. Works in Node.js and web browsers. + +NOTE: it's a fork of [`debug`](https://github.com/visionmedia/debug) for development. (original package is no update for about six months.) + +## Installation + +```bash +$ npm install debug-es +or +$ yarn add debug-es +``` + +## Requirement + +- ES6 support + - node >= 6 + +## Usage + +`debug-es` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. + +```js +const debug = require('debug-es')('http') +const http = require('http') +const name = 'My App' + +// fake app + +debug('booting %o', name) + +http.createServer((req, res) => { + debug(`${req.method} ${req.url}`) + res.end('hello\n') +}).listen(3000, () => debug('listening')) + +// fake worker of some kind + +require('./worker') +``` + +```js +const a = require('debug-es')('worker:a') +const b = require('debug-es')('worker:b') + +function work() { + a('doing lots of uninteresting work') + setTimeout(work, Math.random() * 1000) +} + +work() + +function workb() { + b('doing some work') + setTimeout(workb, Math.random() * 2000) +} + +workb() +``` + +The `DEBUG` environment variable is then used to enable these based on space or +comma-delimited names. + +Here are some examples: + +screen shot 2017-08-08 at 12 53 04 pm +screen shot 2017-08-08 at 12 53 38 pm +screen shot 2017-08-08 at 12 53 25 pm + +### Windows note + +On Windows the environment variable is set using the `set` command. + +```cmd +set DEBUG=*,-not_this +``` + +Note that PowerShell uses different syntax to set environment variables. + +```cmd +$env:DEBUG = "*,-not_this" +``` + +Then, run the program to be debugged as usual. + +## Namespace Colors + +Every debug instance has a color generated for it based on its namespace name. +This helps when visually parsing the debug output to identify which debug instance +a debug line belongs to. + +### Node.js + +In Node.js, colors are enabled when stderr is a TTY. You also _should_ install +the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, +otherwise debug will only use a small handful of basic colors. + + + +### Web Browser + +Colors are also enabled on "Web Inspectors" that understand the `%c` formatting +option. These are WebKit web inspectors, Firefox ([since version +31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) +and the Firebug plugin for Firefox (any version). + + + +## Millisecond diff + +When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + + +When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: + + + +## Conventions + +If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. + +## Wildcards + +The `*` character may be used as a wildcard. Suppose for example your library has +debuggers named "connect:bodyParser", "connect:compress", "connect:session", +instead of listing all three with +`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do +`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + +You can also exclude specific debuggers by prefixing them with a "-" character. +For example, `DEBUG=*,-connect:*` would include all debuggers except those +starting with "connect:". + +## Environment Variables + +When running through Node.js, you can set a few environment variables that will +change the behavior of the debug logging: + +| Name | Purpose | +|-----------|-------------------------------------------------| +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | +| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + +__Note:__ The environment variables beginning with `DEBUG_` end up being +converted into an Options object that gets used with `%o`/`%O` formatters. +See the Node.js documentation for +[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) +for the complete list. + +## Formatters + +Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. +Below are the officially supported formatters: + +| Formatter | Representation | +|-----------|----------------| +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%s` | String. | +| `%d` | Number (both integer and float). | +| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| `%%` | Single percent sign ('%'). This does not consume an argument. | + +### Custom formatters + +You can add custom formatters by extending the `debug.formatters` object. +For example, if you wanted to add support for rendering a Buffer as hex with +`%h`, you could do something like: + +```js +const createDebug = require('debug-es') +createDebug.formatters.h = (v) => { + return v.toString('hex') +} + +// ...elsewhere +const debug = createDebug('foo') +debug('this is hex: %h', new Buffer('hello world')) +// foo this is hex: 68656c6c6f20776f726c6421 +0ms +``` + +## Browser Support + +Debug's enable state is currently persisted by `localStorage`. +Consider the situation shown below where you have `worker:a` and `worker:b`, +and wish to debug both. You can enable this using `localStorage.debug`: + +```js +localStorage.debug = 'worker:*' +``` + +And then refresh the page. + +```js +const a = debug('worker:a') +const b = debug('worker:b') + +setInterval(function(){ + a('doing some work') +}, 1000) + +setInterval(function(){ + b('doing some work') +}, 1200) +``` + +## Output streams + + By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: + +```js +const debug = require('debug-es') +const error = debug('app:error') + +// by default stderr is used +error('goes to stderr!') + +const log = debug('app:log') +// set this namespace to log via console.log +log.log = console.log.bind(console) // don't forget to bind to console! +log('goes to stdout') +error('still goes to stderr!') + +// set all output to go via console.info +// overrides all per-namespace log settings +debug.log = console.info.bind(console) +error('now goes to stdout via console.info') +log('still goes to stdout, but via console.info now') +``` + +## Set dynamically + +You can also enable debug dynamically by calling the `enable()` method : + +```js +let debug = require('debug') + +console.log(1, debug.enabled('test')) + +debug.enable('test') +console.log(2, debug.enabled('test')) + +debug.disable() +console.log(3, debug.enabled('test')) + +``` + +print : + +```plain +1 false +2 true +3 false +``` + +Usage : +`enable(namespaces)` +`namespaces` can include modes separated by a colon and wildcards. + +Note that calling `enable()` completely overrides previously set DEBUG variable : + +```bash +$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' +=> false +``` + +## Checking whether a debug target is enabled + +After you've created a debug instance, you can determine whether or not it is +enabled by checking the `enabled` property: + +```javascript +const debug = require('debug')('http') + +if (debug.enabled) { + // do stuff... +} +``` + +You can also manually toggle this property to force the debug instance to be +enabled or disabled. + +## Transpile for es5 + +```bash +$ npm run build +or +$ yarn build +``` + +and transpiler will place files in `es5` folder. + +## Authors + +- TJ Holowaychuk +- Nathan Rajlich +- Andrew Rhyne +- Miau Lightouch + +## License + +(The MIT License) + +Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca> + +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. diff --git a/package.json b/package.json new file mode 100644 index 0000000..490f0f9 --- /dev/null +++ b/package.json @@ -0,0 +1,39 @@ +{ + "name": "debug-es", + "version": "1.0.0", + "description": "small debugging utility like 'debug', but write in es6", + "repository": { + "type": "git", + "url": "https://github.com/LightouchDev/debug-es" + }, + "main": "src/index.js", + "scripts": { + "coverage": "jest --verbose --coverage --collectCoverageFrom=src/**/*", + "test": "jest --verbose", + "test:debug": "node --inspect-brk ./node_modules/jest/bin/jest.js --verbose" + }, + "keywords": [ + "debug", + "logging" + ], + "author": "TJ Holowaychuk ", + "contributors": [ + "Nathan Rajlich (http://n8.io)", + "Andrew Rhyne ", + "Miau Lightouch " + ], + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + }, + "devDependencies": { + "eslint": "^4.19.1", + "eslint-config-standard": "^11.0.0-beta.0", + "eslint-plugin-import": "^2.10.0", + "eslint-plugin-jest": "^21.15.1", + "eslint-plugin-node": "^6.0.1", + "eslint-plugin-promise": "^3.7.0", + "eslint-plugin-standard": "^3.1.0", + "jest": "^22.4.3" + } +} diff --git a/src/browser.js b/src/browser.js new file mode 100644 index 0000000..4a72593 --- /dev/null +++ b/src/browser.js @@ -0,0 +1,192 @@ +'use strict' + +const createDebug = module.exports = { + /** + * Colors. + */ + colors: [ + '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', + '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', + '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', + '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', + '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', + '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', + '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', + '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', + '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', + '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', + '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' + ], + + /** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + formatters: { + j (value) { + /** + * Stringify without circular issue + * @param {any} content + */ + function safeStringify (content) { + const cache = [] + + return JSON.stringify(content, (key, value) => { + if (typeof value === 'object' && value !== null) { + if (cache.indexOf(value) !== -1) { + // Circular reference found, discard key + return + } + // Store value in our collection + cache.push(value) + } + return value + }) + } + + try { + return safeStringify(value) + } catch (error) { + return `[UnexpectedJSONParseError]: ${error.message}` + } + } + }, + humanize: require('ms'), + + /** + * LocalStorage attempts to return the LocalStorage. + * + * This is necessary because safari throws + * when a user disables cookies/LocalStorage + * and you attempt to access it. + * + * @return {LocalStorage|null} + * @api private + */ + storage: (() => { + try { + return window.localStorage + } catch (error) {} + })(), + + /** + * Colorize log arguments if enabled. + * + * NOTE: only 'this' in formatArgs is scoped in 'debug' instance, + * not in 'createDebug' scope. + * + * @api public + */ + formatArgs (args) { + const cTag = this.useColors ? '%c' : '' + args[0] = + cTag + this.namespace + ' ' + + cTag + args[0] + ' ' + + cTag + '+' + createDebug.humanize(this.diff) + + if (!this.useColors) return + const currentStyle = `color: ${this.color}` + args.splice(1, 0, currentStyle, 'color: inherit') + + // the final '%c' is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0 + let lastC = 0 + args[0].replace(/%[a-zA-Z%]/g, (match) => { + if (match === '%%') return + index++ + if (match === '%c') { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index + } + }) + args.splice(lastC, 0, currentStyle) + }, + + /** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + load () { + let namespaces + try { + namespaces = this.storage.debug + } catch (error) {} + + // If debug isn't set in LS, and we're in Electron/nwjs, try to load $DEBUG + if (!namespaces && typeof process !== 'undefined' && 'env' in process) { + namespaces = process.env.DEBUG + } + + return namespaces + }, + + /** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + /* eslint-disable no-console */ + log () { + return ( + typeof console === 'object' && + console.log && + Function.prototype.apply.call(console.log, console, arguments) + ) + }, + /* eslint-enable no-console */ + + /** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + save (namespaces) { + try { + if (namespaces == null) { + this.storage.removeItem('debug') + } else { + this.storage.debug = namespaces + } + } catch (error) {} + }, + + /** + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + useColors () { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if ( + typeof window !== 'undefined' && + window.process && + (window.process.type === 'renderer' || window.process.__nwjs) + ) return true + + // check userAgent + if (typeof navigator !== 'undefined' && navigator.userAgent) { + const UA = navigator.userAgent.toLowerCase() + + // Internet Explorer do not support colors. + if (UA.match(/trident\/\d+/)) return false + + // Microsoft Edge < 16.16215 do not support colors. + if (UA.match(/edge\/(\d+)\.(\d+)/)) { + return (parseInt(RegExp.$1, 10) >= 16) && (parseInt(RegExp.$2, 10) >= 16215) + } + + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + if (UA.match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) return true + + // double check webkit in userAgent just in case we are in a worker + if (UA.match(/applewebkit\/\d+/)) return true + } + } +} diff --git a/src/common.js b/src/common.js new file mode 100644 index 0000000..ec3ea18 --- /dev/null +++ b/src/common.js @@ -0,0 +1,147 @@ +'use strict' + +const debug = require('./debug') + +module.exports = function (env) { + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug (namespace) { + const newDebug = Object.assign(debug(createDebug), { + namespace, + enabled: createDebug.enabler(namespace), + useColors: createDebug.useColors(), + color: createDebug.selectColor(namespace), + destroy () { + const index = createDebug.instances.indexOf(newDebug) + if (index !== -1) { + createDebug.instances.splice(index, 1) + return true + } + + return false + } + }) + + typeof createDebug.init === 'function' && createDebug.init(newDebug) + + createDebug.instances.push(newDebug) + + return newDebug + } + + // module.exports = createDebug + + const props = { + colors: [], + /** + * Active `debug` instances. + */ + instances: [], + + /** + * The currently active debug mode names, and names to skip. + */ + names: [], + skips: [], + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + formatters: {}, + + /** + * Coerce `value`. + * + * @param {Mixed} value + * @return {Mixed} + * @api private + */ + coerce (value) { + if (value instanceof Error) return value.stack || value.message + return value + }, + + /** + * Disable debug output. + * + * @api public + */ + disable () { + createDebug.enable('') + }, + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + enable (namespaces) { + createDebug.save(namespaces) + + createDebug.names = [] + createDebug.skips = [] + + ;(typeof namespaces === 'string' ? namespaces : '') + .split(/[\s,]+/) + .forEach(item => { + if (!item) return // ignore empty strings + const name = item.replace(/\*/g, '.*?') + name[0] === '-' + ? createDebug.skips.push(new RegExp(`^${name.substr(1)}$`)) + : createDebug.names.push(new RegExp(`^${name}$`)) + }) + + createDebug.instances.forEach(instance => { + instance.enabled = createDebug.enabler(instance.namespace) + }) + }, + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} namespace + * @return {Boolean} + * @api public + */ + enabler (namespace) { + // FIXME: 'something*' would pass the check, what's this for? + if (namespace[namespace.length - 1] === '*') return true + + if (createDebug.skips.some(regex => regex.test(namespace))) return false + if (createDebug.names.some(regex => regex.test(namespace))) return true + + return false + }, + + /** + * Select a color. + * + * @param {String} namespace + * @return {Number} + * @api private + */ + selectColor (namespace) { + let hash = 0 + for (let i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i) + hash |= 0 // Convert to 32bit integer + } + return createDebug.colors[Math.abs(hash) % createDebug.colors.length] + } + } + + Object.assign(createDebug, props, env) + + createDebug.enable(createDebug.load()) + + return createDebug +} diff --git a/src/debug.js b/src/debug.js new file mode 100644 index 0000000..f258dd3 --- /dev/null +++ b/src/debug.js @@ -0,0 +1,47 @@ +'use strict' + +module.exports = function (createDebug) { + let prevTime + + return function debug (...args) { + if (!debug.enabled) return + + // set 'diff' timestamp + const now = +new Date() // convert to number immediately + debug.diff = now - (prevTime || now) + debug.prev = prevTime + debug.now = now + prevTime = now + + args[0] = createDebug.coerce(args[0]) + + // anything else let's inspect with %O + typeof args[0] !== 'string' && args.unshift('%O') + + // apply 'formatters' transformations + let index = 0 + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match + + index++ + const formatter = createDebug.formatters[format] + if (typeof formatter === 'function') { + const value = args[index] + match = formatter.call(debug, value) + + // now we need to remove 'args[index]' since it's inlined + args.splice(index, 1) + index-- + } + + return match + }) + + // apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(debug, args) + + // output to log() + ;(debug.log || createDebug.log).apply(debug, args) + } +} diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..cb52ae2 --- /dev/null +++ b/src/index.js @@ -0,0 +1,19 @@ +'use strict' + +/** + * Detect environment + */ + +const env = + // web browsers + typeof process === 'undefined' || + // Electron + process.type === 'renderer' || + // nwjs + process.__nwjs || + // 'process' package + process.browser + ? require('./browser.js') + : require('./node.js') + +module.exports = require('./common')(env) diff --git a/src/node.js b/src/node.js new file mode 100644 index 0000000..c530bc4 --- /dev/null +++ b/src/node.js @@ -0,0 +1,158 @@ +'use strict' + +/** + * Module dependencies. + */ + +const tty = require('tty') +const util = require('util') + +/** + * This is the Node.js implementation of `debug()`. + */ + +const createDebug = module.exports = { + /** + * Colors. + */ + colors: (() => { + try { + const supportsColor = require('supports-color') + if (supportsColor.stderr && supportsColor.stderr.has256) { + return [ + 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, + 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, + 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, + 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, + 205, 206, 207, 208, 209, 214, 215, 220, 221 + ] + } + } catch (error) { + return [ 6, 2, 3, 4, 5, 1 ] + } + })(), + + formatters: { + /** + * Map %o to `util.inspect()`, all on a single line. + */ + o (value) { + createDebug.inspectOpts.colors = createDebug.useColors + return util.inspect(value, createDebug.inspectOpts) + .replace(/\s*\n\s*/g, ' ') + }, + /** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + O (value) { + createDebug.inspectOpts.colors = createDebug.useColors + return util.inspect(value, createDebug.inspectOpts) + } + }, + + /** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + inspectOpts: Object.keys(process.env) + .filter(key => /^debug_/i.test(key)) + .reduce((obj, key) => { + // camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => k.toUpperCase()) + + // coerce string value into JS value + let value = process.env[key] + if (/^(yes|on|true|enabled)$/i.test(value)) value = true + else if (/^(no|off|false|disabled)$/i.test(value)) value = false + else if (value === 'null') value = null + else value = Number(value) + + obj[prop] = value + return obj + }, {}), + + /** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + init (debug) { + debug.inspectOpts = Object.assign({}, this.inspectOpts) + }, + + /** + * Adds ANSI color escape codes if enabled. + * + * NOTE: only 'this' in formatArgs is scoped in 'debug' instance, + * not in 'createDebug' scope. + * + * @api public + */ + formatArgs (args) { + const name = this.namespace + + if (this.useColors) { + const c = this.color + const colorCode = '\u001b[3' + (c < 8 ? c : `8;5;${c}`) + const prefix = ` ${colorCode};1m${name} \u001b[0m` + + args[0] = prefix + args[0].split('\n').join(`\n prefix`) + args.push(`${colorCode}m+${createDebug.humanize(this.diff)}\u001b[0m`) + } else { + const date = this.inspectOpts.hideDate + ? '' + : new Date().toISOString() + ' ' + args[0] = `${date}${name} ${args[0]}` + } + }, + humanize: require('ms'), + + /** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + load () { + return process.env.DEBUG + }, + + /** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + + log () { + return process.stderr.write(util.format.apply(util, arguments) + '\n') + }, + + /** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + + save (namespaces) { + if (namespaces == null) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG + } else { + process.env.DEBUG = namespaces + } + }, + + /** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + useColors () { + return 'colors' in this.inspectOpts + ? Boolean(this.inspectOpts.colors) + : tty.isatty(process.stderr.fd) + } +} diff --git a/test/browser.test.js b/test/browser.test.js new file mode 100644 index 0000000..4b5fabb --- /dev/null +++ b/test/browser.test.js @@ -0,0 +1,245 @@ +/** + * Test case for browser environment + */ +const env = 'browser' +const process = global.process + +process.browser = true + +const localStorage = window.localStorage = window.sessionStorage = { + getItem (key) { + const value = this[key] + return typeof value === 'undefined' + ? null + : value + }, + setItem (key, value) { + this[key] = value + }, + removeItem (key) { + return delete this[key] + } +} + +const commonTest = require('./common') +const { setWildcard } = commonTest +commonTest(env, tests) + +function tests () { + beforeEach(() => { window.localStorage = localStorage }) + + describe('detect environment', () => { + beforeEach(() => { + global.process = process + Object.assign(process, { + type: undefined, + __nwjs: undefined, + browser: undefined + }) + window.localStorage.removeItem('debug') + }) + + afterAll(() => { process.browser = true }) + + test(`browser: no global process object`, () => { + global.process = undefined + + const debug = require('../src') + global.process = process + expect(debug).toHaveProperty('storage', expect.anything()) + }) + test(`Electron: process.type === 'renderer'`, () => { + process.type = 'renderer' + + const debug = require('../src') + expect(debug).toHaveProperty('storage', expect.anything()) + }) + test(`nwjs: process.__nwjs is truthy`, () => { + process.__nwjs = 1 + + const debug = require('../src') + expect(debug).toHaveProperty('storage', expect.anything()) + }) + test(`'process' package support`, () => { + process.browser = true + + const debug = require('../src') + expect(debug).toHaveProperty('storage', expect.anything()) + }) + }) + + describe('formatters', () => { + describe('%j formatter', () => { + const debug = require('../src') + const { j: formatter } = debug.formatters + + // this test borrow from fast-json-stringify + test('common object', () => { + const obj = { + stringProperty: 'string1', + objectProperty: { + stringProperty: 'string2', + numberProperty: 42 + } + } + expect(formatter(obj)) + .toBe('{"stringProperty":"string1","objectProperty":{"stringProperty":"string2","numberProperty":42}}') + }) + + test('circular object', () => { + const obj = {} + obj.this = obj + + expect(formatter(obj)).toBe('{}') + }) + + test.skip('error handle', () => { + // FIXME: it's hard to make stringify throw error + const error = new Error('this is a fake error') + const obj = {} + Object.defineProperty(obj, 'error', { + get () { throw error } + }) + + expect(formatter(obj)).toBe(`[UnexpectedJSONParseError]: ${error.message}`) + }) + }) + }) + + describe('storage', () => { + test('localStorage exist', () => { + const debug = require('../src') + expect(debug.storage).toBe(localStorage) + }) + + test('localStorage not exist', () => { + delete window.localStorage + const debug = require('../src') + window.localStorage = localStorage + expect(debug.storage).toBeUndefined() + }) + }) + + describe('formatArgs', () => { + beforeEach(() => setWildcard(env)) + + test('color output: on', () => { + const debug = require('../src') + const info = debug('info') + info.log = jest.fn() + info('%%this is message%%') + expect(info.log).toBeCalledWith('%cinfo %c%%this is message%% %c+0ms', 'color: #CC3300', 'color: inherit', 'color: #CC3300') + }) + + test('color output: off', () => { + const debug = require('../src') + const info = debug('info') + info.log = jest.fn() + info.useColors = false + info('%%this is message%%') + expect(info.log).toBeCalledWith('info %%this is message%% +0ms') + }) + + test('custom color tag', () => { + const debug = require('../src') + const info = debug('info') + info.log = jest.fn() + info('%%this is %cmessage%%', 'color: #ff0000') + expect(info.log).toBeCalledWith('%cinfo %c%%this is %cmessage%% %c+0ms', 'color: #CC3300', 'color: inherit', 'color: #ff0000', 'color: #CC3300') + }) + }) + + describe('load', () => { + test('load from localStorage', () => { + const namespaces = 'test, -dummy, worker:*' + window.localStorage.setItem('debug', namespaces) + + const browser = require('../src/browser') + expect(browser.load()).toBe(namespaces) + }) + + test('load from process.env', () => { + const namespaces = 'test, -dummy, worker:*' + process.env.DEBUG = namespaces + expect(window.localStorage.getItem('debug')).toBeFalsy() + + const browser = require('../src/browser') + expect(browser.load()).toBe(namespaces) + }) + }) + + describe('save', () => { + const namespaces = 'test, -dummy, worker:*' + + test('null namespaces', () => { + const browser = require('../src/browser') + window.localStorage.setItem('debug', namespaces) + browser.save() + + expect(browser.load()).toBeUndefined() + }) + + test('valid namespaces', () => { + const browser = require('../src/browser') + browser.save(namespaces) + + expect(browser.load()).toBe(namespaces) + }) + }) + + describe('useColors', () => { + const ie11 = 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; rv:11.0) like Gecko' + const edge = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; ServiceUI 11) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299' + const edgeOld = 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10136' + const firefox = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0' + const chrome = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.170 Safari/537.36' + + Object.defineProperty(navigator, 'userAgent', (_value => { + return { + get () { + return _value + }, + set (value) { + _value = value + } + } + })(navigator.userAgent)) + + test('Electron/nwjs', () => { + const debug = require('../src') + process.type = 'renderer' + expect(debug.useColors()).toBe(true) + delete process.type + + process.__nwjs = 1 + expect(debug.useColors()).toBe(true) + delete process.__nwjs + }) + + test('IE 11', () => { + navigator.userAgent = ie11 + + expect(require('../src').useColors()).toBe(false) + }) + test('edge 12.10136', () => { + navigator.userAgent = edgeOld + + expect(require('../src').useColors()).toBe(false) + }) + test('edge 16.16299', () => { + navigator.userAgent = edge + + expect(require('../src').useColors()).toBe(true) + }) + test('firefox 61', () => { + navigator.userAgent = firefox + + expect(require('../src').useColors()).toBe(true) + }) + test('chrome 66', () => { + navigator.userAgent = chrome + + expect(require('../src').useColors()).toBe(true) + }) + }) +} diff --git a/test/common.js b/test/common.js new file mode 100644 index 0000000..85d7eca --- /dev/null +++ b/test/common.js @@ -0,0 +1,232 @@ +/* eslint-disable no-console */ + +function resetEnv (env) { + jest.resetModules() + + if (env === 'browser') { + window.localStorage.removeItem('debug') + } + + if (env === 'node') { + Object.keys(process.env) + .filter(key => /^debug_/i.test(key)) + .forEach(key => delete process.env[key]) + } + delete process.env.DEBUG +} + +function setWildcard (env) { + env === 'browser' && window.localStorage.setItem('debug', '*') + env === 'node' && (process.env.DEBUG = '*') +} + +module.exports = (env, tests) => { + beforeEach(() => resetEnv(env)) + + describe(`common test in ${env}`, () => { + describe('common.js', () => { + describe('coerce: handle Error messages', () => { + const debug = require('../src') + const message = 'this is message' + + test('Error object', () => { + const err = new Error(message) + expect(debug.coerce(err)).toBe(err.stack) + }) + test('Error object without .stack', () => { + const err = new Error(message) + delete err.stack + expect(debug.coerce(err)).toBe(err.message) + }) + test('plain strings', () => { + expect(debug.coerce(message)).toBe(message) + }) + }) + + test('disable: turn off all instances', () => { + const debug = require('../src') + debug.disable() + expect(debug.skips).toHaveLength(0) + expect(debug.names).toHaveLength(0) + + expect(debug.instances.some(instance => instance.enabled)).toBeFalsy() + }) + + describe('enable', () => { + function instancesCalc (debug) { + let truthy = 0 + let falsy = 0 + debug.instances.forEach(instance => instance.enabled ? truthy++ : falsy++) + return { falsy, truthy } + } + + test('turn on instances by namespaces', () => { + const debug = require('../src') + debug('test') + debug('dummy') + debug('worker:a') + debug('worker:b') + + const namespaces = 'test, -dummy, worker:*' + debug.enable(namespaces) + + expect(debug.load()).toBe(namespaces) + + expect(debug.names).toHaveLength(2) + expect(debug.names.map(regex => regex.toString())).toEqual(['/^test$/', '/^worker:.*?$/']) + + expect(debug.skips).toHaveLength(1) + expect(debug.skips.map(regex => regex.toString())).toEqual(['/^dummy$/']) + + expect(instancesCalc(debug)).toEqual({ falsy: 1, truthy: 3 }) + }) + + test('wildcard with some skip names', () => { + const debug = require('../src') + debug('test') + debug('dummy') + debug('worker:a') + debug('worker:b') + debug('nickname') + debug.enable('*, -dummy, -*name') + + expect(debug.names).toHaveLength(1) + expect(debug.skips).toHaveLength(2) + expect(instancesCalc(debug)).toEqual({ falsy: 2, truthy: 3 }) + }) + + test('non-string namespaces', () => { + const debug = require('../src') + expect(() => debug.enable(true)).not.toThrow() + }) + }) + + test('enabler: check namespace enabled', () => { + const debug = require('../src') + + expect(debug.enabler('')).toBe(false) + expect(debug.enabler('name*')).toBe(true) + + debug.enable('test, -dummy, worker:*') + expect(debug.enabler('test')).toBe(true) + expect(debug.enabler('test123')).toBe(false) + expect(debug.enabler('dummy')).toBe(false) + expect(debug.enabler('worker:a')).toBe(true) + expect(debug.enabler('worker:b')).toBe(true) + expect(debug.enabler('work:a')).toBe(false) + }) + }) + + describe('debug.js', () => { + beforeEach(() => setWildcard(env)) + + test('debug is disabled', () => { + resetEnv(env) + const debug = require('../src') + debug.log = jest.fn() + const info = debug('info') + info('this is disabled') + + expect(debug.log).not.toBeCalled() + }) + + describe('formatter', () => { + test('% escape', () => { + const debug = require('../src') + debug.formatArgs = jest.fn() + debug.log = () => {} + + const message = '%% message %%' + const info = debug('info') + info(message) + + expect(debug.formatArgs).toBeCalledWith([message]) + }) + + test('custom formatter', () => { + const debug = require('../src') + debug.formatArgs = jest.fn() + debug.log = () => {} + debug.formatters.z = value => value.toUpperCase() + + const info = debug('info') + info('%% %z %%', 'message') + + expect(debug.formatArgs).toBeCalledWith(['%% MESSAGE %%']) + }) + }) + + describe('log function', () => { + test('default log()', () => { + const debug = require('../src') + debug.log = jest.fn() + + const info = debug('test') + info('this is a message') + + expect(info.log).toBeFalsy() + expect(debug.log).toBeCalled() + }) + + test('custom log()', () => { + const debug = require('../src') + + const info = debug('test') + info.log = jest.fn() + info('this is a message') + + expect(info.log).toBeCalled() + }) + }) + + describe('destroy', () => { + test('destroy instance', () => { + const debug = require('../src') + debug('test') + const info = debug('info') + + expect(debug.instances).toHaveLength(2) + expect(debug.instances.indexOf(info)).toBeGreaterThan(-1) + + expect(info.destroy()).toBe(true) + expect(debug.instances).toHaveLength(1) + expect(debug.instances.indexOf(info)).toBe(-1) + }) + + test('destroy instance that not in instances array', () => { + const debug = require('../src') + const info = debug('info') + info.enabled = false + + debug.enable('*') + expect(info.enabled).toBe(true) + + // clear array + debug.instances.length = 0 + expect(debug.instances.indexOf(info)).toBe(-1) + + info.enabled = false + expect(info.destroy()).toBe(false) + + debug.enable('*') + expect(info.enabled).toBe(false) + }) + }) + }) + + test('basic sanity check', () => { + const debug = require('../src') + const info = debug('info') + info.enabled = true + expect(() => info('hello world')).not.toThrow() + expect(() => info({})).not.toThrow() + }) + }) + + tests && describe(`${env}-specific tests`, tests) +} + +Object.assign(module.exports, { + resetEnv, + setWildcard +}) diff --git a/test/node.test.js b/test/node.test.js new file mode 100644 index 0000000..9ddb84e --- /dev/null +++ b/test/node.test.js @@ -0,0 +1,170 @@ +/** + * Test case for node environment + */ +const env = 'node' + +const commonTest = require('./common') +const { setWildcard } = commonTest + +commonTest(env, tests) + +function tests () { + test('detect environment', () => { + const debug = require('../src') + expect(debug.inspectOpts).toBeTruthy() + }) + + describe('colors', () => { + test('basic color support', () => { + try { + const supportColor = require('supports-color') + Object.keys(supportColor).forEach(key => { delete supportColor[key] }) + Object.defineProperty(supportColor, 'stderr', { + get () { throw new Error('fake error') } + }) + } catch (error) {} + + expect(require('../src').colors).toHaveLength(6) + }) + + test('256-color support', () => { + expect(require('../src').colors).toHaveLength(76) + }) + }) + + describe('formatters', () => { + // FIXME: better tests required + process.env.DEBUG = '*' + const debug = require('../src') + + test('%o fomatter', () => { + expect(() => debug.formatters.o(process.versions)).not.toThrow() + }) + test('%O fomatter', () => { + expect(() => debug.formatters.O(process.versions)).not.toThrow() + }) + }) + + test('inspectOpts', () => { + process.env['DEBUG_COLORS'] = 'no' + process.env['DEBUG_DEPTH'] = 10 + process.env['DEBUG_SHOW_HIDDEN'] = 'enabled' + process.env['DEBUG_SHOW_PROXY'] = 'null' + + const result = { + colors: false, + depth: 10, + showHidden: true, + showProxy: null + } + + expect(require('../src').inspectOpts).toEqual(result) + }) + + test('init', () => { + process.env['DEBUG_COLORS'] = 'no' + process.env['DEBUG_DEPTH'] = 10 + process.env['DEBUG_SHOW_HIDDEN'] = 'enabled' + + const result = { + colors: false, + depth: 10, + showHidden: true + } + + const debug = require('../src') + const answer = {} + debug.init(answer) + + expect(answer.inspectOpts).toEqual(result) + }) + + describe('formatArgs', () => { + beforeEach(() => setWildcard(env)) + + test('color output: on', () => { + const debug = require('../src') + const info = debug('info') + const color = 166 + info.log = jest.fn() + info('%%this is message%%') + expect(info.log).toBeCalledWith(` \u001b[38;5;${color};1minfo \u001b[0m%%this is message%%`, `\u001b[38;5;${color}m+0ms\u001b[0m`) + }) + + test('color output: on, basic color support', () => { + const debug = require('../src') + const info = debug('info') + const color = 6 + info.color = color + info.log = jest.fn() + info('%%this is message%%') + expect(info.log).toBeCalledWith(` \u001b[3${color};1minfo \u001b[0m%%this is message%%`, `\u001b[3${color}m+0ms\u001b[0m`) + }) + + test('color output: off', () => { + const debug = require('../src') + const info = debug('info') + info.log = jest.fn() + info.useColors = false + info('%%this is message%%') + expect(info.log.mock.calls[0][0]).toMatch(/\w+ info %%this is message%%/) + }) + + test('color output: off, and hideDate', () => { + process.env['DEBUG_HIDE_DATE'] = 'on' + const debug = require('../src') + const info = debug('info') + info.log = jest.fn() + info.useColors = false + info('%%this is message%%') + expect(info.log).toBeCalledWith('info %%this is message%%') + }) + }) + + test('load', () => { + const namespaces = 'test, -dummy, worker:*' + process.env.DEBUG = namespaces + + expect(require('../src/node').load()).toBe(namespaces) + }) + + describe('save', () => { + const namespaces = 'test, -dummy, worker:*' + + test('null namespaces', () => { + process.env.DEBUG = namespaces + const node = require('../src/node') + node.save() + expect(node.load()).toBeUndefined() + }) + + test('valid namespaces', () => { + const node = require('../src/node') + node.save(namespaces) + expect(node.load()).toBe(namespaces) + }) + }) + + describe('useColors', () => { + test('inspectOpts.colors === true', () => { + process.env['DEBUG_COLORS'] = 'on' + expect(require('../src/node').useColors()).toBe(true) + }) + + test('inspectOpts.colors === false', () => { + process.env['DEBUG_COLORS'] = 'off' + expect(require('../src/node').useColors()).toBe(false) + }) + + test('inspectOpts.colors === undefined', () => { + expect(require('../src/node').useColors()).toBe(true) + }) + + test('inspectOpts.colors === undefined, tty.isatty() === false', () => { + const tty = require('tty') + tty.isatty = jest.fn() + tty.isatty.mockReturnValue(false) + expect(require('../src/node').useColors()).toBe(false) + }) + }) +}