prettier

description: Prettier is an opinionated code formatter

repository: prettier/prettier

author: James Long

license: MIT

license: mit


code:
import { Parser } from "../index.js";

export declare const parsers: {
  acorn: Parser;
  espree: Parser;
};


code:
import { Parser } from "../index.js";

export declare const parsers: {
  __ng_action: Parser;
  __ng_binding: Parser;
  __ng_directive: Parser;
  __ng_interpolation: Parser;
};


code:
import { Parser } from "../index.js";

export declare const parsers: {
  babel: Parser;
  "babel-flow": Parser;
  "babel-ts": Parser;
  __js_expression: Parser;
  __ts_expression: Parser;
  __vue_expression: Parser;
  __vue_ts_expression: Parser;
  __vue_event_binding: Parser;
  __vue_ts_event_binding: Parser;
  __babel_estree: Parser;
  json: Parser;
  json5: Parser;
  jsonc: Parser;
  "json-stringify": Parser;
};


code:
import { Parser } from "../index.js";

export declare const parsers: {
  flow: Parser;
};


code:
import { Parser } from "../index.js";

export declare const parsers: {
  glimmer: Parser;
};


code:
import { Parser } from "../index.js";

export declare const parsers: {
  graphql: Parser;
};


code:
import { Parser } from "../index.js";

export declare const parsers: {
  angular: Parser;
  html: Parser;
  lwc: Parser;
  vue: Parser;
};


code:
import { Parser } from "../index.js";

export declare const parsers: {
  markdown: Parser;
  mdx: Parser;
  remark: Parser;
};


code:
import { Parser } from "../index.js";

export declare const parsers: {
  meriyah: Parser;
};


code:
import { Parser } from "../index.js";

export declare const parsers: {
  css: Parser;
  less: Parser;
  scss: Parser;
};


code:
import { Parser } from "../index.js";

export declare const parsers: {
  typescript: Parser;
};


code:
import { Parser } from "../index.js";

export declare const parsers: {
  yaml: Parser;
};


code:
import { CursorOptions, CursorResult, Options, SupportInfo } from "./index.js";

/**
 * formatWithCursor both formats the code, and translates a cursor position from unformatted code to formatted code.
 * This is useful for editor integrations, to prevent the cursor from moving when code is formatted
 *
 * The cursorOffset option should be provided, to specify where the cursor is.
 *
 * ```js
 * await prettier.formatWithCursor(" 1", { cursorOffset: 2, parser: "babel" });
 * ```
 * `-> { formatted: "1;\n", cursorOffset: 1 }`
 */
export function formatWithCursor(
  source: string,
  options: CursorOptions,
): Promise<CursorResult>;

/**
 * `format` is used to format text using Prettier. [Options](https://prettier.io/docs/en/options.html) may be provided to override the defaults.
 */
export function format(source: string, options?: Options): Promise<string>;

/**
 * `check` checks to see if the file has been formatted with Prettier given those options and returns a `Boolean`.
 * This is similar to the `--list-different` parameter in the CLI and is useful for running Prettier in CI scenarios.
 */
export function check(source: string, options?: Options): Promise<boolean>;

/**
 * Returns an object representing the parsers, languages and file types Prettier supports for the current version.
 */
export function getSupportInfo(): Promise<SupportInfo>;


code:
name: Node.js CI

on:
  push:
    branches: [master]
  pull_request:
    branches: [master]

jobs:
  build:
    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [12.x, 14.x, 15.x]

    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v1
        with:
          node-version: ${{ matrix.node-version }}
      - run: npm install
      - run: npm run compile
      - run: npm test


code:
require: 'coffee-script/register'
recursive: true
reporter: 'spec'
ui: 'bdd'
timeout: 20000


code:
language: node_js

node_js:
  - 10.16

sudo: false


code:
# Changelog

## `4.0.0`

* **Breaking Change**: Removed support for Node `<12.x`


code:
# pretty-error

[![Dependency status](https://david-dm.org/AriaMinaei/pretty-error.svg)](https://david-dm.org/AriaMinaei/pretty-error)
[![Build Status](https://secure.travis-ci.org/AriaMinaei/pretty-error.svg?branch=master)](https://travis-ci.org/AriaMinaei/pretty-error) [![npm](https://img.shields.io/npm/dm/pretty-error.svg)](https://npmjs.org/package/pretty-error)

A small tool to see node.js errors with less clutter:

![screenshot of pretty-error](https://github.com/AriaMinaei/pretty-error/raw/master/docs/images/pretty-error-screenshot.png)

... which is more readable compared to node's unformatted errors:

![screenshot of normal errors](https://github.com/AriaMinaei/pretty-error/raw/master/docs/images/normal-error-screenshot.png)

## Installation

Install with npm:

	$ npm install pretty-error

## Usage and Examples

To see an error rendered with colors, you can do this:

```javascript
var PrettyError = require('pretty-error');
var pe = new PrettyError();

var renderedError = pe.render(new Error('Some error message'));
console.log(renderedError);
```

Of course, you can render caught exceptions too:

```javascript
try {
   doSomethingThatThrowsAnError();
} catch (error) {
   console.log(pe.render(error));
}
```

But if you want pretty-error to render all errors, there is a shortcut for it:

```javascript
require('pretty-error').start();
```

... which is essentially equal to:

```javascript
var PrettyError = require('pretty-error');

// instantiate PrettyError, which can then be used to render error objects
var pe = new PrettyError();
pe.start();
```

You can also preload pretty-error into your code using node's [`--require`](https://nodejs.org/api/cli.html#cli_r_require_module) argument:

```
$ node --require pretty-error/start your-module.js
```

## How it Works

PrettyError turns error objects into something similar to an html document, and then uses [RenderKid](https://github.com/AriaMinaei/renderkid) to render the document using simple html/css-like commands. This allows PrettyError to be themed using simple css-like declarations.

## Theming

PrettyError's default theme is a bunch of simple css-like rules. [Here](https://github.com/AriaMinaei/pretty-error/blob/master/src/defaultStyle.coffee) is the source of the default theme.

Since the default theme is all css, you can customize it to fit your taste. Let's do a minimal one:

```javascript
// the start() shortcut returns an instance of PrettyError ...
pe = require('pretty-error').start();

// ... which we can then use to customize like this:
pe.appendStyle({
   // this is a simple selector to the element that says 'Error'
   'pretty-error > header > title > kind': {
      // which we can hide:
      display: 'none'
   },

   // the 'colon' after 'Error':
   'pretty-error > header > colon': {
      // we hide that too:
      display: 'none'
   },

   // our error message
   'pretty-error > header > message': {
      // let's change its color:
      color: 'bright-white',

      // we can use black, red, green, yellow, blue, magenta, cyan, white,
      // grey, bright-red, bright-green, bright-yellow, bright-blue,
      // bright-magenta, bright-cyan, and bright-white

      // we can also change the background color:
      background: 'cyan',

      // it understands paddings too!
      padding: '0 1' // top/bottom left/right
   },

   // each trace item ...
   'pretty-error > trace > item': {
      // ... can have a margin ...
      marginLeft: 2,

      // ... and a bullet character!
      bullet: '"<grey>o</grey>"'

      // Notes on bullets:
      //
      // The string inside the quotation mark gets used as the character
      // to show for the bullet point.
      //
      // You can set its color/background color using tags.
      //
      // This example sets the background color to white, and the text color
      // to cyan, the character will be a hyphen with a space character
      // on each side:
      // example: '"<bg-white><cyan> - </cyan></bg-white>"'
      //
      // Note that we should use a margin of 3, since the bullet will be
      // 3 characters long.
   },

   'pretty-error > trace > item > header > pointer > file': {
      color: 'bright-cyan'
   },

   'pretty-error > trace > item > header > pointer > colon': {
      color: 'cyan'
   },

   'pretty-error > trace > item > header > pointer > line': {
      color: 'bright-cyan'
   },

   'pretty-error > trace > item > header > what': {
      color: 'bright-white'
   },

   'pretty-error > trace > item > footer > addr': {
      display: 'none'
   }
});
```

This is how our minimal theme will look like: ![screenshot of our custom theme](https://github.com/AriaMinaei/pretty-error/raw/master/docs/images/custom-theme-screenshot.png)

Read [RenderKid](https://github.com/AriaMinaei/renderkid)'s docs to learn about all the css rules that are supported.

## Customization

There are a few methods to help you customize the contents of your error logs.

Let's instantiate first:

```javascript
PrettyError = require('pretty-error');
pe = new PrettyError();

// or:
pe = require('pretty-error').start();
```

#### Shortening paths

You might want to substitute long paths with shorter, more readable aliases:

```javascript
pe.alias('E:/open-source/theatrejs/lib', '(Theatre.js)');
```

#### Skipping packages

You might want to skip trace lines that belong to specific packages (chai, when, socket.io):

```javascript
pe.skipPackage('chai', 'when', 'socket.io');
```

#### Skipping node files

```javascript
// this will skip node.js, path.js, event.js, etc.
pe.skipNodeFiles();
```

#### Skipping paths

```javascript
pe.skipPath('/home/dir/someFile.js');
```

#### Skipping by callback

You can customize which trace lines get logged and which won't:
```javascript
pe.skip(function(traceLine, lineNumber){
   // if we know which package this trace line comes from, and it isn't
   // our 'demo' package ...
   if (typeof traceLine.packageName !== 'undefined' && traceLine.packageName !== 'demo') {
      // then skip this line
      return true;
   }

   // You can console.log(traceLine) to see all of it's properties.
   // Don't expect all these properties to be present, and don't assume
   // that our traceLine is always an object.
});
```

#### Modifying each trace line's contents

```javascript
pe.filter(function(traceLine, lineNumber){
   // the 'what' clause is something like:
   // 'DynamicTimeline.module.exports.DynamicTimeline._verifyProp'
   if (typeof traceLine.what !== 'undefined'){

      // we can shorten it with a regex:
      traceLine.what = traceLine.what.replace(
         /(.*\.module\.exports\.)(.*)/, '$2'
      );
   }
});
```

## Disabling colors
```javascript
pe.withoutColors(); // Errors will be rendered without coloring
```

## Integrating with frameworks

PrettyError is very simple to set up, so it should be easy to use within other frameworks.

### Integrating with [express](https://github.com/visionmedia/express)

Most frameworks such as express, catch errors automatically and provide a mechanism to handle those errors. Here is an example of how you can use PrettyError to log unhandled errors in express:

```javascript
// this is app.js

var express = require('express');
var PrettyError = require('pretty-error');

var app = express();

app.get('/', function(req, res) {
   // this will throw an error:
   var a = b;
});

var server = app.listen(3000, function(){
   console.log('Server started \n');
});

// we can now instantiaite Prettyerror:
pe = new PrettyError();

// and use it for our app's error handler:
app.use(function(err, req, res, next){
   console.log(pe.render(err));
   next();
});

// we can optionally configure prettyError to simplify the stack trace:

pe.skipNodeFiles(); // this will skip events.js and http.js and similar core node files
pe.skipPackage('express'); // this will skip all the trace lines about express` core and sub-modules
```

## Troubleshooting

`PrettyError.start()` modifies the stack traces of all errors thrown anywhere in your code, so it could potentially break packages that rely on node's original stack traces. I've only encountered this problem once, and it was with BlueBird when `Promise.longStackTraces()` was on.

In order to avoid this problem, it's better to not use `PrettyError.start()` and instead, manually catch errors and render them with PrettyError:

```javascript
var PrettyError = require('pretty-error');
var pe = new PrettyError();

// To render exceptions thrown in non-promies code:
process.on('uncaughtException', function(error){
   console.log(pe.render(error));
});

// To render unhandled rejections created in BlueBird:
process.on('unhandledRejection', function(reason){
   console.log("Unhandled rejection");
   console.log(pe.render(reason));
});

// While PrettyError.start() works out of the box with when.js` unhandled rejections,
// now that wer'e manually rendering errors, we have to instead use npmjs.org/packages/pretty-monitor
// to handle when.js rejections.

```

The only drawback with this approach is that exceptions thrown in the first tick are not prettified. To fix that, you can delay your application's startup for one tick:

```javascript
// (continued form above)

throw new Error(); // not prettified
process.nextTick(function(){
   throw new Error(); // prettified
});

```

## License

MIT


code:
declare module 'pretty-error' {
    namespace PrettyError {
        function start(): any;
        function stop(): any;

        class ParsedError {
            constructor(error: Error);
        }

        interface ConfigObject {
            skipPackages?: boolean | string[];
            skipPaths?: boolean | string[];
            skip?: boolean | PrettyError.Callback | PrettyError.Callback[];
            maxItems?: number;
            skipNodeFiles?: boolean | any; // assuming this is optional
            filters?: boolean | PrettyError.Callback | PrettyError.Callback[];
            parsedErrorFilters?:
            | boolean
            | PrettyError.Callback
            | PrettyError.Callback[];
            aliases?: boolean | Object;
        }

        type Callback = (traceLine: Object | any, lineNumber: number) => boolean;
    }

    class PrettyError {
        constructor();

        start(): PrettyError;
        stop(): any;
        config(configObject: PrettyError.ConfigObject): PrettyError;
        withoutColors(): PrettyError;
        withColors(): PrettyError;
        skipPackage(...packages: string[]): PrettyError;
        unskipPackage(...packages: string[]): PrettyError;
        unskipAllPackages(): PrettyError;
        skipPath(...paths: string[]): PrettyError;
        unskipPath(...paths: string[]): PrettyError;
        unskipAllPaths(): PrettyError;
        skip(callbacks: PrettyError.Callback): PrettyError;
        unskip(callbacks: PrettyError.Callback): PrettyError;
        unskipAll(): PrettyError;
        skipNodeFiles(): any;
        unskipNodeFiles(): any;
        filter(callbacks: PrettyError.Callback): PrettyError;
        removeFilter(callbacks: PrettyError.Callback): PrettyError;
        removeAllFilters(): PrettyError;
        filterParsedError(callbacks: PrettyError.Callback): PrettyError;
        removeParsedErrorFilter(callbacks: PrettyError.Callback): PrettyError;
        removeAllParsedErrorFilters(): PrettyError;
        setMaxItems(maxItems: number): PrettyError;
        alias(stringOrRx: string, alias: string): PrettyError;
        removeAlias(stringOrRx: string): PrettyError;
        removeAllAliases(): PrettyError;
        appendStyle(toAppend: Object): PrettyError;
        render(
            e: PrettyError.ParsedError,
            logIt?: boolean,
            useColors?: boolean
        ): string;
        getObject(e: Object): Object;
    }

    export = PrettyError;
}


code:
// Generated by CoffeeScript 1.8.0
var ParsedError, prop, sysPath, _fn, _i, _len, _ref;

sysPath = require('path');

module.exports = ParsedError = (function() {
  function ParsedError(error) {
    this.error = error;
    this._parse();
  }

  ParsedError.prototype._parse = function() {
    var m;
    this._trace = [];
    this._kind = 'Error';
    this._wrapper = '';
    if (this.error.wrapper != null) {
      this._wrapper = String(this.error.wrapper);
    }
    if (typeof this.error !== 'object') {
      this._message = String(this.error);
    } else {
      this._stack = this.error.stack;
      if (this.error.kind != null) {
        this._kind = String(this.error.kind);
      } else if (typeof this._stack === 'string') {
        if (m = this._stack.match(/^([a-zA-Z0-9\_\$]+):\ /)) {
          this._kind = m[1];
        }
      }
      this._message = (this.error.message != null) && String(this.error.message) || '';
      if (typeof this._stack === 'string') {
        this._parseStack();
      }
    }
  };

  ParsedError.prototype._parseStack = function() {
    var line, message, messageLines, reachedTrace, _i, _len, _ref;
    messageLines = [];
    reachedTrace = false;
    _ref = this._stack.split('\n');
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      line = _ref[_i];
      if (line.trim() === '') {
        continue;
      }
      if (reachedTrace) {
        this._trace.push(this._parseTraceItem(line));
      } else {
        if (line.match(/^\s*at\s.+/)) {
          reachedTrace = true;
          this._trace.push(this._parseTraceItem(line));
        } else if (!this._message.split('\n'.indexOf(line))) {
          messageLines.push(line);
        }
      }
    }
    message = messageLines.join('\n');
    if (message.substr(0, this._kind.length) === this._kind) {
      message = message.substr(this._kind.length, message.length).replace(/^\:\s+/, '');
    }
    if (message.length) {
      this._message = this._message.length ? [this._message, message].join('\n') : message;
    }
  };

  ParsedError.prototype._parseTraceItem = function(text) {
    var addr, col, d, dir, file, jsCol, jsLine, line, m, original, packageName, packages, path, r, remaining, shortenedAddr, shortenedPath, what;
    text = text.trim();
    if (text === '') {
      return;
    }
    if (!text.match(/^at\ /)) {
      return text;
    }
    text = text.replace(/^at /, '');
    if (text === 'Error (<anonymous>)' || text === 'Error (<anonymous>:null:null)') {
      return;
    }
    original = text;
    what = null;
    addr = null;
    path = null;
    dir = null;
    file = null;
    line = null;
    col = null;
    jsLine = null;
    jsCol = null;
    shortenedPath = null;
    shortenedAddr = null;
    packageName = '[current]';
    if (m = text.match(/\(([^\)]+)\)$/)) {
      addr = m[1].trim();
    }
    if (addr != null) {
      what = text.substr(0, text.length - addr.length - 2);
      what = what.trim();
    }
    if (addr == null) {
      addr = text.trim();
    }
    addr = this._fixPath(addr);
    remaining = addr;
    if (m = remaining.match(/\,\ <js>:(\d+):(\d+)$/)) {
      jsLine = m[1];
      jsCol = m[2];
      remaining = remaining.substr(0, remaining.length - m[0].length);
    }
    if (m = remaining.match(/:(\d+):(\d+)$/)) {
      line = m[1];
      col = m[2];
      remaining = remaining.substr(0, remaining.length - m[0].length);
      path = remaining;
    }
    if (path != null) {
      file = sysPath.basename(path);
      dir = sysPath.dirname(path);
      if (dir === '.') {
        dir = '';
      }
      path = this._fixPath(path);
      file = this._fixPath(file);
      dir = this._fixPath(dir);
    }
    if (dir != null) {
      d = dir.replace(/[\\]{1,2}/g, '/');
      if (m = d.match(/node_modules\/([^\/]+)(?!.*node_modules.*)/)) {
        packageName = m[1];
      }
    }
    if (jsLine == null) {
      jsLine = line;
      jsCol = col;
    }
    if (path != null) {
      r = this._rectifyPath(path);
      shortenedPath = r.path;
      shortenedAddr = shortenedPath + addr.substr(path.length, addr.length);
      packages = r.packages;
    }
    return {
      original: original,
      what: what,
      addr: addr,
      path: path,
      dir: dir,
      file: file,
      line: parseInt(line),
      col: parseInt(col),
      jsLine: parseInt(jsLine),
      jsCol: parseInt(jsCol),
      packageName: packageName,
      shortenedPath: shortenedPath,
      shortenedAddr: shortenedAddr,
      packages: packages || []
    };
  };

  ParsedError.prototype._getMessage = function() {
    return this._message;
  };

  ParsedError.prototype._getKind = function() {
    return this._kind;
  };

  ParsedError.prototype._getWrapper = function() {
    return this._wrapper;
  };

  ParsedError.prototype._getStack = function() {
    return this._stack;
  };

  ParsedError.prototype._getArguments = function() {
    return this.error["arguments"];
  };

  ParsedError.prototype._getType = function() {
    return this.error.type;
  };

  ParsedError.prototype._getTrace = function() {
    return this._trace;
  };

  ParsedError.prototype._fixPath = function(path) {
    return path.replace(/[\\]{1,2}/g, '/');
  };

  ParsedError.prototype._rectifyPath = function(path, nameForCurrentPackage) {
    var m, packages, parts, remaining, rest;
    path = String(path);
    remaining = path;
    if (!(m = path.match(/^(.+?)\/node_modules\/(.+)$/))) {
      return {
        path: path,
        packages: []
      };
    }
    parts = [];
    packages = [];
    if (typeof nameForCurrentPackage === 'string') {
      parts.push("[" + nameForCurrentPackage + "]");
      packages.push("[" + nameForCurrentPackage + "]");
    } else {
      parts.push("[" + (m[1].match(/([^\/]+)$/)[1]) + "]");
      packages.push(m[1].match(/([^\/]+)$/)[1]);
    }
    rest = m[2];
    while (m = rest.match(/([^\/]+)\/node_modules\/(.+)$/)) {
      parts.push("[" + m[1] + "]");
      packages.push(m[1]);
      rest = m[2];
    }
    if (m = rest.match(/([^\/]+)\/(.+)$/)) {
      parts.push("[" + m[1] + "]");
      packages.push(m[1]);
      rest = m[2];
    }
    parts.push(rest);
    return {
      path: parts.join("/"),
      packages: packages
    };
  };

  return ParsedError;

})();

_ref = ['message', 'kind', 'arguments', 'type', 'stack', 'trace', 'wrapper'];
_fn = function() {
  var methodName;
  methodName = '_get' + prop[0].toUpperCase() + prop.substr(1, prop.length);
  return Object.defineProperty(ParsedError.prototype, prop, {
    get: function() {
      return this[methodName]();
    }
  });
};
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  prop = _ref[_i];
  _fn();
}


code:
// Generated by CoffeeScript 1.8.0
var ParsedError, PrettyError, RenderKid, arrayUtils, defaultStyle, instance, isPlainObject, merge, nodePaths, prop, _fn, _i, _len, _ref,
  __slice = [].slice,
  __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

isPlainObject = require('lodash/isPlainObject');

defaultStyle = require('./defaultStyle');

ParsedError = require('./ParsedError');

nodePaths = require('./nodePaths');

RenderKid = require('renderkid');

merge = require('lodash/merge');

arrayUtils = {
  pluckByCallback: function(a, cb) {
    var index, removed, value, _i, _len;
    if (a.length < 1) {
      return a;
    }
    removed = 0;
    for (index = _i = 0, _len = a.length; _i < _len; index = ++_i) {
      value = a[index];
      if (cb(value, index)) {
        removed++;
        continue;
      }
      if (removed !== 0) {
        a[index - removed] = a[index];
      }
    }
    if (removed > 0) {
      a.length = a.length - removed;
    }
    return a;
  },
  pluckOneItem: function(a, item) {
    var index, reached, value, _i, _len;
    if (a.length < 1) {
      return a;
    }
    reached = false;
    for (index = _i = 0, _len = a.length; _i < _len; index = ++_i) {
      value = a[index];
      if (!reached) {
        if (value === item) {
          reached = true;
          continue;
        }
      } else {
        a[index - 1] = a[index];
      }
    }
    if (reached) {
      a.length = a.length - 1;
    }
    return a;
  }
};

instance = null;

module.exports = PrettyError = (function() {
  var self;

  self = PrettyError;

  PrettyError._filters = {
    'module.exports': function(item) {
      if (item.what == null) {
        return;
      }
      item.what = item.what.replace(/\.module\.exports\./g, ' - ');
    }
  };

  PrettyError._getDefaultStyle = function() {
    return defaultStyle();
  };

  PrettyError.start = function() {
    if (instance == null) {
      instance = new self;
      instance.start();
    }
    return instance;
  };

  PrettyError.stop = function() {
    return instance != null ? instance.stop() : void 0;
  };

  function PrettyError() {
    this._useColors = true;
    this._maxItems = 50;
    this._packagesToSkip = [];
    this._pathsToSkip = [];
    this._skipCallbacks = [];
    this._filterCallbacks = [];
    this._parsedErrorFilters = [];
    this._aliases = [];
    this._renderer = new RenderKid;
    this._style = self._getDefaultStyle();
    this._renderer.style(this._style);
  }

  PrettyError.prototype.start = function() {
    var prepeare;
    this._oldPrepareStackTrace = Error.prepareStackTrace;
    prepeare = this._oldPrepareStackTrace || function(exc, frames) {
      var result;
      result = exc.toString();
      frames = frames.map(function(frame) {
        return "  at " + (frame.toString());
      });
      return result + "\n" + frames.join("\n");
    };
    Error.prepareStackTrace = (function(_this) {
      return function(exc, trace) {
        var stack;
        stack = prepeare.apply(null, arguments);
        return _this.render({
          stack: stack,
          message: exc.toString().replace(/^.*: /, '')
        }, false);
      };
    })(this);
    return this;
  };

  PrettyError.prototype.stop = function() {
    Error.prepareStackTrace = this._oldPrepareStackTrace;
    return this._oldPrepareStackTrace = null;
  };

  PrettyError.prototype.config = function(c) {
    var alias, path, _ref;
    if (c.skipPackages != null) {
      if (c.skipPackages === false) {
        this.unskipAllPackages();
      } else {
        this.skipPackage.apply(this, c.skipPackages);
      }
    }
    if (c.skipPaths != null) {
      if (c.skipPaths === false) {
        this.unskipAllPaths();
      } else {
        this.skipPath.apply(this, c.skipPaths);
      }
    }
    if (c.skip != null) {
      if (c.skip === false) {
        this.unskipAll();
      } else {
        this.skip.apply(this, c.skip);
      }
    }
    if (c.maxItems != null) {
      this.setMaxItems(c.maxItems);
    }
    if (c.skipNodeFiles === true) {
      this.skipNodeFiles();
    } else if (c.skipNodeFiles === false) {
      this.unskipNodeFiles();
    }
    if (c.filters != null) {
      if (c.filters === false) {
        this.removeAllFilters();
      } else {
        this.filter.apply(this, c.filters);
      }
    }
    if (c.parsedErrorFilters != null) {
      if (c.parsedErrorFilters === false) {
        this.removeAllParsedErrorFilters();
      } else {
        this.filterParsedError.apply(this, c.parsedErrorFilters);
      }
    }
    if (c.aliases != null) {
      if (isPlainObject(c.aliases)) {
        _ref = c.aliases;
        for (path in _ref) {
          alias = _ref[path];
          this.alias(path, alias);
        }
      } else if (c.aliases === false) {
        this.removeAllAliases();
      }
    }
    return this;
  };

  PrettyError.prototype.withoutColors = function() {
    this._useColors = false;
    return this;
  };

  PrettyError.prototype.withColors = function() {
    this._useColors = true;
    return this;
  };

  PrettyError.prototype.skipPackage = function() {
    var packages, pkg, _i, _len;
    packages = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
    for (_i = 0, _len = packages.length; _i < _len; _i++) {
      pkg = packages[_i];
      this._packagesToSkip.push(String(pkg));
    }
    return this;
  };

  PrettyError.prototype.unskipPackage = function() {
    var packages, pkg, _i, _len;
    packages = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
    for (_i = 0, _len = packages.length; _i < _len; _i++) {
      pkg = packages[_i];
      arrayUtils.pluckOneItem(this._packagesToSkip, pkg);
    }
    return this;
  };

  PrettyError.prototype.unskipAllPackages = function() {
    this._packagesToSkip.length = 0;
    return this;
  };

  PrettyError.prototype.skipPath = function() {
    var path, paths, _i, _len;
    paths = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
    for (_i = 0, _len = paths.length; _i < _len; _i++) {
      path = paths[_i];
      this._pathsToSkip.push(path);
    }
    return this;
  };

  PrettyError.prototype.unskipPath = function() {
    var path, paths, _i, _len;
    paths = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
    for (_i = 0, _len = paths.length; _i < _len; _i++) {
      path = paths[_i];
      arrayUtils.pluckOneItem(this._pathsToSkip, path);
    }
    return this;
  };

  PrettyError.prototype.unskipAllPaths = function() {
    this._pathsToSkip.length = 0;
    return this;
  };

  PrettyError.prototype.skip = function() {
    var callbacks, cb, _i, _len;
    callbacks = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
    for (_i = 0, _len = callbacks.length; _i < _len; _i++) {
      cb = callbacks[_i];
      this._skipCallbacks.push(cb);
    }
    return this;
  };

  PrettyError.prototype.unskip = function() {
    var callbacks, cb, _i, _len;
    callbacks = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
    for (_i = 0, _len = callbacks.length; _i < _len; _i++) {
      cb = callbacks[_i];
      arrayUtils.pluckOneItem(this._skipCallbacks, cb);
    }
    return this;
  };

  PrettyError.prototype.unskipAll = function() {
    this._skipCallbacks.length = 0;
    return this;
  };

  PrettyError.prototype.skipNodeFiles = function() {
    return this.skipPath.apply(this, nodePaths);
  };

  PrettyError.prototype.unskipNodeFiles = function() {
    return this.unskipPath.apply(this, nodePaths);
  };

  PrettyError.prototype.filter = function() {
    var callbacks, cb, _i, _len;
    callbacks = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
    for (_i = 0, _len = callbacks.length; _i < _len; _i++) {
      cb = callbacks[_i];
      this._filterCallbacks.push(cb);
    }
    return this;
  };

  PrettyError.prototype.removeFilter = function() {
    var callbacks, cb, _i, _len;
    callbacks = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
    for (_i = 0, _len = callbacks.length; _i < _len; _i++) {
      cb = callbacks[_i];
      arrayUtils.pluckOneItem(this._filterCallbacks, cb);
    }
    return this;
  };

  PrettyError.prototype.removeAllFilters = function() {
    this._filterCallbacks.length = 0;
    return this;
  };

  PrettyError.prototype.filterParsedError = function() {
    var callbacks, cb, _i, _len;
    callbacks = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
    for (_i = 0, _len = callbacks.length; _i < _len; _i++) {
      cb = callbacks[_i];
      this._parsedErrorFilters.push(cb);
    }
    return this;
  };

  PrettyError.prototype.removeParsedErrorFilter = function() {
    var callbacks, cb, _i, _len;
    callbacks = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
    for (_i = 0, _len = callbacks.length; _i < _len; _i++) {
      cb = callbacks[_i];
      arrayUtils.pluckOneItem(this._parsedErrorFilters, cb);
    }
    return this;
  };

  PrettyError.prototype.removeAllParsedErrorFilters = function() {
    this._parsedErrorFilters.length = 0;
    return this;
  };

  PrettyError.prototype.setMaxItems = function(maxItems) {
    if (maxItems == null) {
      maxItems = 50;
    }
    if (maxItems === 0) {
      maxItems = 50;
    }
    this._maxItems = maxItems | 0;
    return this;
  };

  PrettyError.prototype.alias = function(stringOrRx, alias) {
    this._aliases.push({
      stringOrRx: stringOrRx,
      alias: alias
    });
    return this;
  };

  PrettyError.prototype.removeAlias = function(stringOrRx) {
    arrayUtils.pluckByCallback(this._aliases, function(pair) {
      return pair.stringOrRx === stringOrRx;
    });
    return this;
  };

  PrettyError.prototype.removeAllAliases = function() {
    this._aliases.length = 0;
    return this;
  };

  PrettyError.prototype._getStyle = function() {
    return this._style;
  };

  PrettyError.prototype.appendStyle = function(toAppend) {
    merge(this._style, toAppend);
    this._renderer.style(toAppend);
    return this;
  };

  PrettyError.prototype._getRenderer = function() {
    return this._renderer;
  };

  PrettyError.prototype.render = function(e, logIt, useColors) {
    var obj, rendered;
    if (logIt == null) {
      logIt = false;
    }
    if (useColors == null) {
      useColors = this._useColors;
    }
    obj = this.getObject(e);
    rendered = this._renderer.render(obj, useColors);
    if (logIt === true) {
      console.error(rendered);
    }
    return rendered;
  };

  PrettyError.prototype.getObject = function(e) {
    var count, header, i, item, obj, traceItems, _i, _len, _ref;
    if (!(e instanceof ParsedError)) {
      e = new ParsedError(e);
    }
    this._applyParsedErrorFiltersOn(e);
    header = {
      title: (function() {
        var ret;
        ret = {};
        if (e.wrapper !== '') {
          ret.wrapper = "" + e.wrapper;
        }
        ret.kind = e.kind;
        return ret;
      })(),
      colon: ':',
      message: String(e.message).trim()
    };
    traceItems = [];
    count = -1;
    _ref = e.trace;
    for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
      item = _ref[i];
      if (item == null) {
        continue;
      }
      if (this._skipOrFilter(item, i) === true) {
        continue;
      }
      count++;
      if (count > this._maxItems) {
        break;
      }
      if (typeof item === 'string') {
        traceItems.push({
          item: {
            custom: item
          }
        });
        continue;
      }
      traceItems.push((function() {
        var markupItem;
        markupItem = {
          item: {
            header: {
              pointer: (function() {
                if (item.file == null) {
                  return '';
                }
                return {
                  file: item.file,
                  colon: ':',
                  line: item.line
                };
              })()
            },
            footer: (function() {
              var foooter;
              foooter = {
                addr: item.shortenedAddr
              };
              if (item.extra != null) {
                foooter.extra = item.extra;
              }
              return foooter;
            })()
          }
        };
        if (typeof item.what === 'string' && item.what.trim().length > 0) {
          markupItem.item.header.what = item.what;
        }
        return markupItem;
      })());
    }
    obj = {
      'pretty-error': {
        header: header
      }
    };
    if (traceItems.length > 0) {
      obj['pretty-error'].trace = traceItems;
    }
    return obj;
  };

  PrettyError.prototype._skipOrFilter = function(item, itemNumber) {
    var cb, modName, pair, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1, _ref2, _ref3, _ref4, _ref5;
    if (typeof item === 'object') {
      if (_ref = item.modName, __indexOf.call(this._packagesToSkip, _ref) >= 0) {
        return true;
      }
      if (_ref1 = item.path, __indexOf.call(this._pathsToSkip, _ref1) >= 0) {
        return true;
      }
      _ref2 = item.packages;
      for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
        modName = _ref2[_i];
        if (__indexOf.call(this._packagesToSkip, modName) >= 0) {
          return true;
        }
      }
      if (typeof item.shortenedAddr === 'string') {
        _ref3 = this._aliases;
        for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) {
          pair = _ref3[_j];
          item.shortenedAddr = item.shortenedAddr.replace(pair.stringOrRx, pair.alias);
        }
      }
    }
    _ref4 = this._skipCallbacks;
    for (_k = 0, _len2 = _ref4.length; _k < _len2; _k++) {
      cb = _ref4[_k];
      if (cb(item, itemNumber) === true) {
        return true;
      }
    }
    _ref5 = this._filterCallbacks;
    for (_l = 0, _len3 = _ref5.length; _l < _len3; _l++) {
      cb = _ref5[_l];
      cb(item, itemNumber);
    }
    return false;
  };

  PrettyError.prototype._applyParsedErrorFiltersOn = function(error) {
    var cb, _i, _len, _ref;
    _ref = this._parsedErrorFilters;
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      cb = _ref[_i];
      cb(error);
    }
  };

  return PrettyError;

})();

_ref = ['renderer', 'style'];
_fn = function() {
  var methodName;
  methodName = '_get' + prop[0].toUpperCase() + prop.substr(1, prop.length);
  return PrettyError.prototype.__defineGetter__(prop, function() {
    return this[methodName]();
  });
};
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  prop = _ref[_i];
  _fn();
}


code:
// Generated by CoffeeScript 1.8.0
module.exports = function() {
  return {
    'pretty-error': {
      display: 'block',
      marginLeft: '2'
    },
    'pretty-error > header': {
      display: 'block'
    },
    'pretty-error > header > title > kind': {
      background: 'red',
      color: 'bright-white'
    },
    'pretty-error > header > title > wrapper': {
      marginRight: '1',
      color: 'grey'
    },
    'pretty-error > header > colon': {
      color: 'grey',
      marginRight: 1
    },
    'pretty-error > header > message': {
      color: 'bright-white'
    },
    'pretty-error > trace': {
      display: 'block',
      marginTop: 1
    },
    'pretty-error > trace > item': {
      display: 'block',
      marginBottom: 1,
      marginLeft: 2,
      bullet: '"<grey>-</grey>"'
    },
    'pretty-error > trace > item > header': {
      display: 'block'
    },
    'pretty-error > trace > item > header > pointer > file': {
      color: 'bright-yellow'
    },
    'pretty-error > trace > item > header > pointer > colon': {
      color: 'grey'
    },
    'pretty-error > trace > item > header > pointer > line': {
      color: 'bright-yellow',
      marginRight: 1
    },
    'pretty-error > trace > item > header > what': {
      color: 'white'
    },
    'pretty-error > trace > item > footer': {
      display: 'block'
    },
    'pretty-error > trace > item > footer > addr': {
      display: 'block',
      color: 'grey'
    },
    'pretty-error > trace > item > footer > extra': {
      display: 'block',
      color: 'grey'
    }
  };
};


code:
// Generated by CoffeeScript 1.8.0
module.exports = ['_debugger.js', '_http_agent.js', '_http_client.js', '_http_common.js', '_http_incoming.js', '_http_outgoing.js', '_http_server.js', '_linklist.js', '_stream_duplex.js', '_stream_passthrough.js', '_stream_readable.js', '_stream_transform.js', '_stream_writable.js', '_tls_legacy.js', '_tls_wrap.js', 'assert.js', 'buffer.js', 'child_process.js', 'cluster.js', 'console.js', 'constants.js', 'crypto.js', 'dgram.js', 'dns.js', 'domain.js', 'events.js', 'freelist.js', 'fs.js', 'http.js', 'https.js', 'module.js', 'net.js', 'os.js', 'path.js', 'punycode.js', 'querystring.js', 'readline.js', 'repl.js', 'smalloc.js', 'stream.js', 'string_decoder.js', 'sys.js', 'timers.js', 'tls.js', 'tty.js', 'url.js', 'util.js', 'vm.js', 'zlib.js', 'node.js'];


pretty-error

description: See nodejs errors with less clutter

test: mocha "test/**/*.coffee"

test:watch: mocha "test/**/*.coffee" --watch

compile: coffee --bare --compile --output ./lib ./src

compile:watch: jitter src lib -b

winwatch: start/b npm run compile:watch & npm run test:watch

prepublish: npm run compile

author: Aria Minaei

type: git

keywords: pretty error exception debug error-handling readable colorful prettify format human


code:
sysPath = require 'path'

module.exports = class ParsedError
  constructor: (@error) ->
    do @_parse

  _parse: ->
    @_trace = []
    @_kind = 'Error'
    @_wrapper = ''

    @_wrapper = String @error.wrapper if @error.wrapper?

    unless typeof @error is 'object'
      @_message = String @error
    else
      @_stack = @error.stack

      if @error.kind?
        @_kind = String @error.kind
      else if typeof @_stack is 'string'
        if m = @_stack.match /^([a-zA-Z0-9\_\$]+):\ /
          @_kind = m[1]

      @_message = @error.message? and String(@error.message) or ''
      if typeof @_stack is 'string'
        @_parseStack()

    return

  _parseStack: ->
    messageLines = []
    reachedTrace = no

    for line in @_stack.split '\n'
      continue if line.trim() is ''
      if reachedTrace
        @_trace.push @_parseTraceItem line
      else
        if line.match /^\s*at\s.+/
          reachedTrace = yes
          @_trace.push @_parseTraceItem line
        else if !@_message.split '\n'.indexOf line
          messageLines.push line

    message = messageLines.join '\n'
    if message.substr(0, @_kind.length) is @_kind
      message =
        message
        .substr(@_kind.length, message.length)
        .replace(/^\:\s+/, '')

    if message.length
      @_message = if @_message.length
      then [
        @_message
        message
      ].join '\n'
      else
        message

    return

  _parseTraceItem: (text) ->
    text = text.trim()

    return if text is ''
    return text unless text.match /^at\ /

    # remove the 'at ' part
    text = text.replace /^at /, ''

    return if text in ['Error (<anonymous>)', 'Error (<anonymous>:null:null)']

    original = text

    # the part that comes before the address
    what = null

    # address, including path to module and line/col
    addr = null

    # path to module
    path = null

    # module dir
    dir = null

    # module basename
    file = null

    # line number (if using a compiler, the line number of the module
    # in that compiler will be used)
    line = null

    # column, same as above
    col = null

    # if using a compiler, this will translate to the line number of
    # the js equivalent of that module
    jsLine = null

    # like above
    jsCol = null

    # path that doesn't include `node_module` dirs
    shortenedPath = null

    # like above
    shortenedAddr = null

    packageName = '[current]'

    # pick out the address
    if m = text.match /\(([^\)]+)\)$/
      addr = m[1].trim()

    if addr?
      what = text.substr 0, text.length - addr.length - 2
      what = what.trim()

    # might not have a 'what' clause
    unless addr?
      addr = text.trim()

    addr = @_fixPath addr
    remaining = addr

    # remove the <js> clause if the file is a compiled one
    if m = remaining.match /\,\ <js>:(\d+):(\d+)$/
      jsLine = m[1]
      jsCol = m[2]
      remaining = remaining.substr 0, remaining.length - m[0].length

    # the line/col part
    if m = remaining.match /:(\d+):(\d+)$/
      line = m[1]
      col = m[2]
      remaining = remaining.substr 0, remaining.length - m[0].length
      path = remaining

    # file and dir
    if path?
      file = sysPath.basename path
      dir = sysPath.dirname path

      if dir is '.' then dir = ''

      path = @_fixPath path
      file = @_fixPath file
      dir = @_fixPath dir

    if dir?
      d = dir.replace /[\\]{1,2}/g, '/'
      if m = d.match ///
          node_modules/([^/]+)(?!.*node_modules.*)
        ///

        packageName = m[1]

    unless jsLine?
      jsLine = line
      jsCol = col

    if path?
      r = @_rectifyPath path
      shortenedPath = r.path
      shortenedAddr = shortenedPath + addr.substr(path.length, addr.length)
      packages = r.packages

    original: original
    what: what
    addr: addr
    path: path
    dir: dir
    file: file
    line: parseInt line
    col: parseInt col
    jsLine: parseInt jsLine
    jsCol: parseInt jsCol
    packageName: packageName
    shortenedPath: shortenedPath
    shortenedAddr: shortenedAddr
    packages: packages || []

  _getMessage: -> @_message
  _getKind: -> @_kind
  _getWrapper: -> @_wrapper
  _getStack: -> @_stack
  _getArguments: -> @error.arguments
  _getType: -> @error.type
  _getTrace: -> @_trace
  _fixPath: (path) -> path.replace(///[\\]{1,2}///g, '/')

  _rectifyPath: (path, nameForCurrentPackage) ->
    path = String path
    remaining = path

    return path: path, packages: [] unless m = path.match /^(.+?)\/node_modules\/(.+)$/

    parts = []
    packages = []

    if typeof nameForCurrentPackage is 'string'
      parts.push "[#{nameForCurrentPackage}]"
      packages.push "[#{nameForCurrentPackage}]"
    else
      parts.push "[#{m[1].match(/([^\/]+)$/)[1]}]"
      packages.push m[1].match(/([^\/]+)$/)[1]

    rest = m[2]

    while m = rest.match /([^\/]+)\/node_modules\/(.+)$/
      parts.push "[#{m[1]}]"
      packages.push m[1]
      rest = m[2]

    if m = rest.match /([^\/]+)\/(.+)$/
      parts.push "[#{m[1]}]"
      packages.push m[1]
      rest = m[2]

    parts.push rest

    path: parts.join "/"
    packages: packages

for prop in ['message', 'kind', 'arguments', 'type', 'stack', 'trace', 'wrapper'] then do ->
  methodName = '_get' + prop[0].toUpperCase() + prop.substr(1, prop.length)

  Object.defineProperty ParsedError::, prop,
    get: -> this[methodName]()


code:
isPlainObject = require 'lodash/isPlainObject'
defaultStyle = require './defaultStyle'
ParsedError = require './ParsedError'
nodePaths = require './nodePaths'
RenderKid = require 'renderkid'
merge = require 'lodash/merge'

arrayUtils =
  pluckByCallback: (a, cb) ->
    return a if a.length < 1
    removed = 0

    for value, index in a
      if cb value, index
        removed++
        continue

      if removed isnt 0
        a[index - removed] = a[index]

    if removed > 0
      a.length = a.length - removed

    a

  pluckOneItem: (a, item) ->
    return a if a.length < 1
    reached = no

    for value, index in a
      if not reached
        if value is item
          reached = yes
          continue
      else
        a[index - 1] = a[index]

    a.length = a.length - 1 if reached
    a

instance = null

module.exports = class PrettyError
  self = @

  @_filters:
    'module.exports': (item) ->
      return unless item.what?
      item.what = item.what.replace /\.module\.exports\./g, ' - '
      return

  @_getDefaultStyle: ->
    defaultStyle()

  @start: ->
    unless instance?
      instance = new self
      instance.start()

    instance

  @stop: ->
    instance?.stop()

  constructor: ->
    @_useColors = yes
    @_maxItems = 50
    @_packagesToSkip = []
    @_pathsToSkip = []
    @_skipCallbacks = []
    @_filterCallbacks = []
    @_parsedErrorFilters = []
    @_aliases = []
    @_renderer = new RenderKid
    @_style = self._getDefaultStyle()
    @_renderer.style @_style

  start: ->
    @_oldPrepareStackTrace = Error.prepareStackTrace

    prepeare = @_oldPrepareStackTrace or (exc, frames) ->
      result = exc.toString()
      frames = frames.map (frame) -> "  at #{frame.toString()}"
      result + "\n" + frames.join "\n"

    # https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
    Error.prepareStackTrace = (exc, trace) =>
      stack = prepeare.apply(null, arguments)
      @render {stack, message: exc.toString().replace /^.*: /, ''}, no

    @

  stop: ->
    Error.prepareStackTrace = @_oldPrepareStackTrace
    @_oldPrepareStackTrace = null

  config: (c) ->
    if c.skipPackages?
      if c.skipPackages is no
        @unskipAllPackages()
      else
        @skipPackage.apply @, c.skipPackages

    if c.skipPaths?
      if c.skipPaths is no
        @unskipAllPaths()
      else
        @skipPath.apply @, c.skipPaths

    if c.skip?
      if c.skip is no
        @unskipAll()
      else
        @skip.apply @, c.skip

    if c.maxItems?
      @setMaxItems c.maxItems

    if c.skipNodeFiles is yes
      @skipNodeFiles()
    else if c.skipNodeFiles is no
      @unskipNodeFiles()

    if c.filters?
      if c.filters is no
        @removeAllFilters()
      else
        @filter.apply @, c.filters

    if c.parsedErrorFilters?
      if c.parsedErrorFilters is no
        @removeAllParsedErrorFilters()
      else
        @filterParsedError.apply @, c.parsedErrorFilters

    if c.aliases?
      if isPlainObject c.aliases
        @alias path, alias for path, alias of c.aliases
      else if c.aliases is no
        @removeAllAliases()

    @

  withoutColors: ->
    @_useColors = false
    @

  withColors: ->
    @_useColors = true
    @

  skipPackage: (packages...) ->
    @_packagesToSkip.push String pkg for pkg in packages
    @

  unskipPackage: (packages...) ->
    arrayUtils.pluckOneItem(@_packagesToSkip, pkg) for pkg in packages
    @

  unskipAllPackages: ->
    @_packagesToSkip.length = 0
    @

  skipPath: (paths...) ->
    @_pathsToSkip.push path for path in paths
    @

  unskipPath: (paths...) ->
    arrayUtils.pluckOneItem(@_pathsToSkip, path) for path in paths
    @

  unskipAllPaths: ->
    @_pathsToSkip.length = 0
    @

  skip: (callbacks...) ->
    @_skipCallbacks.push cb for cb in callbacks
    @

  unskip: (callbacks...) ->
    arrayUtils.pluckOneItem(@_skipCallbacks, cb) for cb in callbacks
    @

  unskipAll: ->
    @_skipCallbacks.length = 0
    @

  skipNodeFiles: ->
    @skipPath.apply @, nodePaths

  unskipNodeFiles: ->
    @unskipPath.apply @, nodePaths

  filter: (callbacks...) ->
    @_filterCallbacks.push cb for cb in callbacks
    @

  removeFilter: (callbacks...) ->
    arrayUtils.pluckOneItem(@_filterCallbacks, cb) for cb in callbacks
    @

  removeAllFilters: ->
    @_filterCallbacks.length = 0
    @

  filterParsedError: (callbacks...) ->
    @_parsedErrorFilters.push cb for cb in callbacks
    @

  removeParsedErrorFilter: (callbacks...) ->
    arrayUtils.pluckOneItem(@_parsedErrorFilters, cb) for cb in callbacks
    @

  removeAllParsedErrorFilters: ->
    @_parsedErrorFilters.length = 0
    @

  setMaxItems: (maxItems = 50) ->
    if maxItems is 0 then maxItems = 50
    @_maxItems = maxItems|0
    @

  alias: (stringOrRx, alias) ->
    @_aliases.push {stringOrRx, alias}
    @

  removeAlias: (stringOrRx) ->
    arrayUtils.pluckByCallback @_aliases, (pair) ->
      pair.stringOrRx is stringOrRx

    @

  removeAllAliases: ->
    @_aliases.length = 0
    @

  _getStyle: ->
    @_style

  appendStyle: (toAppend) ->
    merge @_style, toAppend
    @_renderer.style toAppend
    @

  _getRenderer: ->
    @_renderer

  render: (e, logIt = no, useColors = @_useColors) ->
    obj = @getObject e
    rendered = @_renderer.render(obj, useColors)
    console.error rendered if logIt is yes
    rendered

  getObject: (e) ->
    unless e instanceof ParsedError
      e = new ParsedError e

    @_applyParsedErrorFiltersOn e

    header =
      title: do ->
        ret = {}

        # some errors are thrown to display other errors.
        # we call them wrappers here.
        if e.wrapper isnt ''
          ret.wrapper = "#{e.wrapper}"

        ret.kind = e.kind
        ret

      colon: ':'

      message: String(e.message).trim()

    traceItems = []
    count = -1

    for item, i in e.trace
      continue unless item?
      continue if @_skipOrFilter(item, i) is yes

      count++

      break if count > @_maxItems

      if typeof item is 'string'
        traceItems.push item: custom: item
        continue

      traceItems.push do ->
        markupItem = item:
          header:
            pointer: do ->
              return '' unless item.file?

              file: item.file
              colon: ':'
              line: item.line

          footer: do ->
            foooter = addr: item.shortenedAddr
            if item.extra? then foooter.extra = item.extra
            foooter

        markupItem.item.header.what = item.what if typeof item.what is 'string' and item.what.trim().length > 0
        markupItem

    obj = 'pretty-error':
      header: header

    if traceItems.length > 0
      obj['pretty-error'].trace = traceItems

    obj

  _skipOrFilter: (item, itemNumber) ->
    if typeof item is 'object'
      return yes if item.modName in @_packagesToSkip
      return yes if item.path in @_pathsToSkip

      for modName in item.packages
        return yes if modName in @_packagesToSkip

      if typeof item.shortenedAddr is 'string'
        for pair in @_aliases
          item.shortenedAddr = item.shortenedAddr.replace pair.stringOrRx, pair.alias

    for cb in @_skipCallbacks
      return yes if cb(item, itemNumber) is yes

    for cb in @_filterCallbacks
      cb(item, itemNumber)

    return no

  _applyParsedErrorFiltersOn: (error) ->
    for cb in @_parsedErrorFilters
      cb error

    return

for prop in ['renderer', 'style'] then do ->
  methodName = '_get' + prop[0].toUpperCase() + prop.substr(1, prop.length)
  PrettyError::__defineGetter__ prop, -> do @[methodName]


code:
module.exports = ->
  'pretty-error':
    display: 'block'
    marginLeft: '2'

  'pretty-error > header':
    display: 'block'

  'pretty-error > header > title > kind':
    background: 'red'
    color: 'bright-white'

  'pretty-error > header > title > wrapper':
    marginRight: '1'
    color: 'grey'

  'pretty-error > header > colon':
    color: 'grey'
    marginRight: 1

  'pretty-error > header > message':
    color: 'bright-white'

  'pretty-error > trace':
    display: 'block'
    marginTop: 1

  'pretty-error > trace > item':
    display: 'block'
    marginBottom: 1
    marginLeft: 2
    bullet: '"<grey>-</grey>"'

  'pretty-error > trace > item > header':
    display: 'block'

  'pretty-error > trace > item > header > pointer > file':
    color: 'bright-yellow'

  'pretty-error > trace > item > header > pointer > colon':
    color: 'grey'

  'pretty-error > trace > item > header > pointer > line':
    color: 'bright-yellow'
    marginRight: 1

  'pretty-error > trace > item > header > what':
    color: 'white'

  'pretty-error > trace > item > footer':
    display: 'block'

  'pretty-error > trace > item > footer > addr':
    display: 'block'
    color: 'grey'

  'pretty-error > trace > item > footer > extra':
    display: 'block'
    color: 'grey'


code:
module.exports = [
  '_debugger.js'
  '_http_agent.js'
  '_http_client.js'
  '_http_common.js'
  '_http_incoming.js'
  '_http_outgoing.js'
  '_http_server.js'
  '_linklist.js'
  '_stream_duplex.js'
  '_stream_passthrough.js'
  '_stream_readable.js'
  '_stream_transform.js'
  '_stream_writable.js'
  '_tls_legacy.js'
  '_tls_wrap.js'
  'assert.js'
  'buffer.js'
  'child_process.js'
  'cluster.js'
  'console.js'
  'constants.js'
  'crypto.js'
  'dgram.js'
  'dns.js'
  'domain.js'
  'events.js'
  'freelist.js'
  'fs.js'
  'http.js'
  'https.js'
  'module.js'
  'net.js'
  'os.js'
  'path.js'
  'punycode.js'
  'querystring.js'
  'readline.js'
  'repl.js'
  'smalloc.js'
  'stream.js'
  'string_decoder.js'
  'sys.js'
  'timers.js'
  'tls.js'
  'tty.js'
  'url.js'
  'util.js'
  'vm.js'
  'zlib.js'
  'node.js'
]


code:
chai = require 'chai'
ParsedError = require '../src/ParsedError'

chai.should()

error = (what) ->
  if typeof what is 'string'
    return error -> throw Error what

  else if what instanceof Function
    try
      do what
      return null
    catch e
      return e

  else
    throw Error "bad argument for error"

describe "ParsedError", ->
  describe "constructor()", ->
    it "should accept Error() instances", ->
      (-> new ParsedError error -> throw Error "some message").should.not.throw()

    it "should accept ReferenceError() and other derivatives of Error()", ->
      (-> new ParsedError error -> throw ReferenceError "some message").should.not.throw()

    it "should accept non errors", ->
      (-> e = new ParsedError 'some string').should.not.throw()

  describe "message", ->
    it "should return the original error message", ->
      e = new ParsedError error 'a'
      e.message.should.equal 'a'

  describe "multiline message", ->
    it "should return the original error message", ->
      e = new ParsedError error 'a \n b \n c'
      e.message.should.equal 'a \n b \n c'

  describe "kind", ->
    it "should return 'Error' for normal error", ->
      e = new ParsedError error 'a'
      e.kind.should.equal 'Error'

    it "should recognize 'ReferenceError'", ->
      e = new ParsedError error -> a.b = c
      e.kind.should.equal 'ReferenceError'

  describe "type", ->
    it.skip "should return original error type", ->
      e = new ParsedError error -> a.b = c
      e.type.should.be.equal 'not_defined'

  describe "arguments", ->
    it.skip "should return original error arguments", ->
      e = new ParsedError error -> a.b = c
      e.arguments.should.be.eql ['a']

  describe "stack", ->
    it "should return original error stack", ->
      e = new ParsedError error -> a.b = c
      e.stack.should.be.equal e.error.stack

  describe "trace", ->
    it "should include correct information about each trace item", ->
      e = new ParsedError error -> a.b = c
      e.trace.should.have.length.above 2

      item = e.trace[0]
      item.should.include.keys 'original',
        'what', 'path', 'addr',
        'file', 'dir', 'col',
        'line', 'jsCol', 'jsLine'
        'packageName', 'shortenedPath', 'shortenedAddr'

      item.path.should.equal module.filename.replace(/[\\]+/g, '/')

      item.line.should.be.a 'number'
      item.col.should.be.a 'number'

  describe "_rectifyPath()", ->
    it "should work", ->
      ParsedError::_rectifyPath('F:/a/node_modules/b/node_modules/d/node_modules/e/f.js').path.should.equal '[a]/[b]/[d]/[e]/f.js'

    it "should return path when `node_modules` is not present", ->
      ParsedError::_rectifyPath('a/b/c').path.should.equal 'a/b/c'


code:
chai = require 'chai'
PrettyError = require '../src/PrettyError'
defaultStyle = require '../src/defaultStyle'

chai.should()

isFormatted = (exc) ->
  exc.stack.indexOf('  \u001b[0m\u001b[97m\u001b[41m') is 0

error = (what) ->
  if typeof what is 'string'
    return error -> throw Error what

  else if what instanceof Function
    try
      do what
    catch e
      return e

  throw Error "bad argument for error"

describe "PrettyError", ->
  describe "constructor()", ->
    it "should work", ->
      new PrettyError

  describe "getObject", ->
    it "should return a string", ->
      p = new PrettyError
      p.getObject(error "hello").should.be.an 'object'

  describe "style", ->
    it "should, by default, return the contents in `default-style`", ->
      p = new PrettyError
      p.style.should.eql defaultStyle()

    it "should return different contents after appending some styles", ->
      p = new PrettyError
      p.appendStyle 'some selector': 'display': 'block'
      p.style.should.not.eql defaultStyle()

  describe "render()", ->
    it "should work", ->
      p = new PrettyError
      p.skipNodeFiles()
      p.appendStyle 'pretty-error': marginLeft: 4

      e = error -> "a".should.equal "b"
      console.log p.render e, no

      e2 = error -> Array.split(Object)
      console.log p.render e2, no

      e3 = "Plain error message"
      console.log p.render e3, no

      e4 =
        message: "Custom error message"
        kind: "Custom Error"

      console.log p.render e4, no

      e5 =
        message: "Error with custom stack"
        stack: ['line one', 'line two']
        wrapper: 'UnhandledRejection'

      console.log p.render e5, no

      e6 = error -> PrettyError.someNonExistingFuncion()
      console.log p.render e6, no

    it.skip "should render without colors if pe._useColors is false", ->
      p = new PrettyError
      p.withoutColors()
      p.skipNodeFiles()
      p.appendStyle 'pretty-error': marginLeft: 4

      e = error -> "a".should.equal "b"
      console.log p.render e, no

  describe "start()", ->
    prepareStackTrace = null

    beforeEach ->
      {prepareStackTrace} = Error
      Error.prepareStackTrace = null

    afterEach ->
      Error.prepareStackTrace = prepareStackTrace

    it "throws unformatted error when not started", ->
      try
        throw new Error "foo bar"
      catch exc

      isFormatted(exc).should.be.eql false

    it "throws formatted the error", ->
      PrettyError.start()

      try
        throw new Error "foo bar"
      catch exc

      isFormatted(exc).should.be.eql true
      exc.stack.split(/\n/g).length.should.be.above 2

      PrettyError.stop()


code:
'use strict';

if (typeof process === 'undefined' ||
    !process.version ||
    process.version.indexOf('v0.') === 0 ||
    process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  module.exports = { nextTick: nextTick };
} else {
  module.exports = process
}

function nextTick(fn, arg1, arg2, arg3) {
  if (typeof fn !== 'function') {
    throw new TypeError('"callback" argument must be a function');
  }
  var len = arguments.length;
  var args, i;
  switch (len) {
  case 0:
  case 1:
    return process.nextTick(fn);
  case 2:
    return process.nextTick(function afterTickOne() {
      fn.call(null, arg1);
    });
  case 3:
    return process.nextTick(function afterTickTwo() {
      fn.call(null, arg1, arg2);
    });
  case 4:
    return process.nextTick(function afterTickThree() {
      fn.call(null, arg1, arg2, arg3);
    });
  default:
    args = new Array(len - 1);
    i = 0;
    while (i < args.length) {
      args[i++] = arguments[i];
    }
    return process.nextTick(function afterTick() {
      fn.apply(null, args);
    });
  }
}


process-nextick-args

description: process.nextTick but always with args

test: node test.js


code:
process-nextick-args
=====

[![Build Status](https://travis-ci.org/calvinmetcalf/process-nextick-args.svg?branch=master)](https://travis-ci.org/calvinmetcalf/process-nextick-args)

```bash
npm install --save process-nextick-args
```

Always be able to pass arguments to process.nextTick, no matter the platform

```js
var pna = require('process-nextick-args');

pna.nextTick(function (a, b, c) {
  console.log(a, b, c);
}, 'step', 3,  'profit');
```


code:
# editorconfig.org

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true


code:
language: node_js
node_js:
  - "8.10.0"
env:
  - NODE_ENV:test


code:
progress-webpack-plugin  [![npm version](https://badge.fury.io/js/progress-webpack-plugin.svg)](https://badge.fury.io/js/progress-webpack-plugin)
===
[![NPM](https://nodei.co/npm/progress-webpack-plugin.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/progress-webpack-plugin/)

inspired by [progress-bar-webpack-plugin](https://github.com/clessg/progress-bar-webpack-plugin),simple Webpack plugin that display nice progress when build

Install
===

```javascript
npm install progress-webpack-plugin --save--dev
```

Usage
===

add plugin in your webpack.config.js

```javascript
var ProgressPlugin = require('progress-webpack-plugin')

module.exports = {
    ...
    plugins:[
        new ProgressPlugin(true)
    ]
}
```

Plugin Options
===

- **minimal**: enable minimal mode or not,default value is false
- **identifier**: identifier of webpack bundle
- **onStart**: callback function when webpack bundler started
- **onFinish**: callback function when webpack bundler finished
- **onProgress**: callback function when webpack bundler running
- **clear**: whether clear console when webpack bundler finished

## License

[MIT License](http://en.wikipedia.org/wiki/MIT_License)


code:
let chalk = require('chalk')
let ProgressPlugin = require('webpack/lib/ProgressPlugin')
let log = require('log-update')
let path = require('path')

const thresholder = 0.99

function now() {
  return new Date().toTimeString().split(' ')[0]
}

function isEqual(arr1, arr2) {
  let equal = arr1.length === arr2.length
  for (let i = 0; i < arr1.length; i++) {
    if (arr1[i] !== arr2[i]) {
      equal = false
      break
    }
  }
  return equal
}

class Progress {
  constructor(options) {
    this.delegate = new ProgressPlugin(options)
  }
  apply(compiler) {
    this.delegate.apply(compiler)
    let invalid = () => {
      console.log(chalk.white('Compiling...'))
    }
    if (compiler.hooks) {
      compiler.hooks.invalid.tap('ProgressWebpckPlugin', invalid)
    } else {
      compiler.plugin('invalid', invalid)
    }
  }
}

function progressPlugin(options = {}) {
  let identifier = options.identifier || ''
  let id = identifier && identifier + ' '
  let onStart = options.onStart || (() => {})
  let onFinish = options.onFinish
  let onProgress = options.onProgress
  let coloring = onProgress === undefined
  let clear = typeof options.clear === 'boolean' ? options.clear : true
  let startTime
  let finishTime
  let duration

  let prev = {}
  const handler = (percentage, message, ...args) => {
    startTime = Date.now()
    let output = []
    if (percentage > thresholder) {
      return
    }
    if (percentage === 0) onStart()
    if (percentage > 0 && percentage < thresholder) {
      if (message === '') return
      if (
        prev.percentage === percentage &&
        prev.message === message &&
        isEqual(prev.args, args)
      ) {
        return
      }
      prev = { percentage, message, args }
      const banner = `[${Math.round(percentage * 100)}%] `
      output.push(coloring ? chalk.yellow(banner) : banner)
      output.push(
        coloring ? chalk.white(`${message} ${id}`) : `${message} ${id}`
      )
      if (args.length > 0) {
        let details = args.join(' ')
        if (
          /^\d+\/\d+\s{1}modules/.test(args[0]) === true &&
          args.length === 2
        ) {
          const rootPath = path.resolve('.')
          details = [args[0]].concat([args[1].replace(rootPath, '')]).join(' ')
        }
        if (/^import\s{1}loader/.test(args[0]) === true && args.length === 1) {
          const matches = args[0].match(
            /^import\s{1}loader\s{1}(.+\/node_modules\/)/
          )
          if (matches) {
            details = args[0].replace(matches[1], '')
          }
        }
        output.push(coloring ? chalk.grey(`(${details})`) : `(${details})`)
      }
    }

    // // 5. finished
    if (percentage === thresholder) {
      finishTime = Date.now()
      duration = (finishTime - startTime) / 1000
      duration = duration.toFixed(3)

      if (typeof onFinish === 'function') {
        onFinish(id, now(), duration)
      } else {
        output.push(
          coloring
            ? chalk.white(`Build ${id}finished at ${now()} by ${duration}s`)
            : `Build ${id}finished at ${now()} by ${duration}s`
        )
      }
    }
    if (onProgress) {
      if (percentage > 0 && percentage < thresholder) {
        onProgress(output, percentage)
      }
    } else {
      log(output.join(''))
      if (percentage === thresholder) {
        if (clear) {
          log.clear()
        } else {
          log.done()
        }
      }
    }
  }
  return new Progress({
    handler,
    entries: false,
    activeModules: false,
    modules: true,
    modulesCount: 5000,
    dependencies: false,
    dependenciesCount: 10000,
    percentBy: 'entries'
  })
}

module.exports = progressPlugin


code:
'use strict';
const x = module.exports;
const ESC = '\u001B[';
const OSC = '\u001B]';
const BEL = '\u0007';
const SEP = ';';
const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal';

x.cursorTo = (x, y) => {
	if (typeof x !== 'number') {
		throw new TypeError('The `x` argument is required');
	}

	if (typeof y !== 'number') {
		return ESC + (x + 1) + 'G';
	}

	return ESC + (y + 1) + ';' + (x + 1) + 'H';
};

x.cursorMove = (x, y) => {
	if (typeof x !== 'number') {
		throw new TypeError('The `x` argument is required');
	}

	let ret = '';

	if (x < 0) {
		ret += ESC + (-x) + 'D';
	} else if (x > 0) {
		ret += ESC + x + 'C';
	}

	if (y < 0) {
		ret += ESC + (-y) + 'A';
	} else if (y > 0) {
		ret += ESC + y + 'B';
	}

	return ret;
};

x.cursorUp = count => ESC + (typeof count === 'number' ? count : 1) + 'A';
x.cursorDown = count => ESC + (typeof count === 'number' ? count : 1) + 'B';
x.cursorForward = count => ESC + (typeof count === 'number' ? count : 1) + 'C';
x.cursorBackward = count => ESC + (typeof count === 'number' ? count : 1) + 'D';

x.cursorLeft = ESC + 'G';
x.cursorSavePosition = ESC + (isTerminalApp ? '7' : 's');
x.cursorRestorePosition = ESC + (isTerminalApp ? '8' : 'u');
x.cursorGetPosition = ESC + '6n';
x.cursorNextLine = ESC + 'E';
x.cursorPrevLine = ESC + 'F';
x.cursorHide = ESC + '?25l';
x.cursorShow = ESC + '?25h';

x.eraseLines = count => {
	let clear = '';

	for (let i = 0; i < count; i++) {
		clear += x.eraseLine + (i < count - 1 ? x.cursorUp() : '');
	}

	if (count) {
		clear += x.cursorLeft;
	}

	return clear;
};

x.eraseEndLine = ESC + 'K';
x.eraseStartLine = ESC + '1K';
x.eraseLine = ESC + '2K';
x.eraseDown = ESC + 'J';
x.eraseUp = ESC + '1J';
x.eraseScreen = ESC + '2J';
x.scrollUp = ESC + 'S';
x.scrollDown = ESC + 'T';

x.clearScreen = '\u001Bc';

x.clearTerminal = process.platform === 'win32' ?
	`${x.eraseScreen}${ESC}0f` :
	// 1. Erases the screen (Only done in case `2` is not supported)
	// 2. Erases the whole screen including scrollback buffer
	// 3. Moves cursor to the top-left position
	// More info: https://www.real-world-systems.com/docs/ANSIcode.html
	`${x.eraseScreen}${ESC}3J${ESC}H`;

x.beep = BEL;

x.link = (text, url) => {
	return [
		OSC,
		'8',
		SEP,
		SEP,
		url,
		BEL,
		text,
		OSC,
		'8',
		SEP,
		SEP,
		BEL
	].join('');
};

x.image = (buf, opts) => {
	opts = opts || {};

	let ret = OSC + '1337;File=inline=1';

	if (opts.width) {
		ret += `;width=${opts.width}`;
	}

	if (opts.height) {
		ret += `;height=${opts.height}`;
	}

	if (opts.preserveAspectRatio === false) {
		ret += ';preserveAspectRatio=0';
	}

	return ret + ':' + buf.toString('base64') + BEL;
};

x.iTerm = {};

x.iTerm.setCwd = cwd => OSC + '50;CurrentDir=' + (cwd || process.cwd()) + BEL;


ansi-escapes

description: ANSI escape codes for manipulating the terminal

repository: sindresorhus/ansi-escapes

test: xo && ava

keywords: ansi terminal console cli string tty escape escapes formatting shell xterm log logging command-line text vt100 sequence control code codes cursor iterm iterm2


code:
# ansi-escapes [![Build Status](https://travis-ci.org/sindresorhus/ansi-escapes.svg?branch=master)](https://travis-ci.org/sindresorhus/ansi-escapes)

> [ANSI escape codes](http://www.termsys.demon.co.uk/vtansi.htm) for manipulating the terminal

## Install

```
$ npm install ansi-escapes
```

## Usage

```js
const ansiEscapes = require('ansi-escapes');

// Moves the cursor two rows up and to the left
process.stdout.write(ansiEscapes.cursorUp(2) + ansiEscapes.cursorLeft);
//=> '\u001B[2A\u001B[1000D'
```

## API

### cursorTo(x, [y])

Set the absolute position of the cursor. `x0` `y0` is the top left of the screen.

### cursorMove(x, [y])

Set the position of the cursor relative to its current position.

### cursorUp(count)

Move cursor up a specific amount of rows. Default is `1`.

### cursorDown(count)

Move cursor down a specific amount of rows. Default is `1`.

### cursorForward(count)

Move cursor forward a specific amount of rows. Default is `1`.

### cursorBackward(count)

Move cursor backward a specific amount of rows. Default is `1`.

### cursorLeft

Move cursor to the left side.

### cursorSavePosition

Save cursor position.

### cursorRestorePosition

Restore saved cursor position.

### cursorGetPosition

Get cursor position.

### cursorNextLine

Move cursor to the next line.

### cursorPrevLine

Move cursor to the previous line.

### cursorHide

Hide cursor.

### cursorShow

Show cursor.

### eraseLines(count)

Erase from the current cursor position up the specified amount of rows.

### eraseEndLine

Erase from the current cursor position to the end of the current line.

### eraseStartLine

Erase from the current cursor position to the start of the current line.

### eraseLine

Erase the entire current line.

### eraseDown

Erase the screen from the current line down to the bottom of the screen.

### eraseUp

Erase the screen from the current line up to the top of the screen.

### eraseScreen

Erase the screen and move the cursor the top left position.

### scrollUp

Scroll display up one line.

### scrollDown

Scroll display down one line.

### clearScreen

Clear the terminal screen. (Viewport)

### clearTerminal

Clear the whole terminal, including scrollback buffer. (Not just the visible part of it)

### beep

Output a beeping sound.

### link(text, url)

Create a clickable link.

[Supported terminals.](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda) Use [`supports-hyperlinks`](https://github.com/jamestalmage/supports-hyperlinks) to detect link support.

### image(input, [options])

Display an image.

*Currently only supported on iTerm2 >=3*

See [term-img](https://github.com/sindresorhus/term-img) for a higher-level module.

#### input

Type: `Buffer`

Buffer of an image. Usually read in with `fs.readFile()`.

#### options

##### width
##### height

Type: `string` `number`

The width and height are given as a number followed by a unit, or the word "auto".

- `N`: N character cells.
- `Npx`: N pixels.
- `N%`: N percent of the session's width or height.
- `auto`: The image's inherent size will be used to determine an appropriate dimension.

##### preserveAspectRatio

Type: `boolean`

Default: `true`

### iTerm.setCwd([path])

Type: `string`

Default: `process.cwd()`

[Inform iTerm2](https://www.iterm2.com/documentation-escape-codes.html) of the current directory to help semantic history and enable [Cmd-clicking relative paths](https://coderwall.com/p/b7e82q/quickly-open-files-in-iterm-with-cmd-click).

## Related

- [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal

## License

MIT © [Sindre Sorhus](https://sindresorhus.com)


ansi-regex

description: Regular expression for matching ANSI escape codes

repository: chalk/ansi-regex

view-supported: node fixtures/view-codes.js

keywords: ansi styles color colour colors terminal console cli string tty escape formatting rgb 256 shell xterm command-line text regex regexp re match test find pattern


code:
# ansi-regex [![Build Status](https://travis-ci.org/chalk/ansi-regex.svg?branch=master)](https://travis-ci.org/chalk/ansi-regex)

> Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code)

## Install

```
$ npm install ansi-regex
```

## Usage

```js
const ansiRegex = require('ansi-regex');

ansiRegex().test('\u001B[4mcake\u001B[0m');
//=> true

ansiRegex().test('cake');
//=> false

'\u001B[4mcake\u001B[0m'.match(ansiRegex());
//=> ['\u001B[4m', '\u001B[0m']
```

## FAQ

### Why do you test for codes not in the ECMA 48 standard?

Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them.

On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out.

## Maintainers

- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)

## License

MIT


code:
'use strict';
const restoreCursor = require('restore-cursor');

let hidden = false;

exports.show = stream => {
	const s = stream || process.stderr;

	if (!s.isTTY) {
		return;
	}

	hidden = false;
	s.write('\u001b[?25h');
};

exports.hide = stream => {
	const s = stream || process.stderr;

	if (!s.isTTY) {
		return;
	}

	restoreCursor();
	hidden = true;
	s.write('\u001b[?25l');
};

exports.toggle = (force, stream) => {
	if (force !== undefined) {
		hidden = force;
	}

	if (hidden) {
		exports.show(stream);
	} else {
		exports.hide(stream);
	}
};


cli-cursor

description: Toggle the CLI cursor

repository: sindresorhus/cli-cursor

keywords: cli cursor ansi toggle display show hide term terminal console tty shell command-line


code:
# cli-cursor [![Build Status](https://travis-ci.org/sindresorhus/cli-cursor.svg?branch=master)](https://travis-ci.org/sindresorhus/cli-cursor)

> Toggle the CLI cursor

The cursor is [gracefully restored](https://github.com/sindresorhus/restore-cursor) if the process exits.

## Install

```
$ npm install --save cli-cursor
```

## Usage

```js
const cliCursor = require('cli-cursor');

cliCursor.hide();

const unicornsAreAwesome = true;
cliCursor.toggle(unicornsAreAwesome);
```

## API

### .show([stream])

### .hide([stream])

### .toggle(force, [stream])

`force` is useful to show or hide the cursor based on a boolean.

#### stream

Type: `Stream`<br>
Default: `process.stderr`

## License

MIT © [Sindre Sorhus](https://sindresorhus.com)


code:
'use strict';
/* eslint-disable yoda */
module.exports = x => {
	if (Number.isNaN(x)) {
		return false;
	}

	// code points are derived from:
	// http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
	if (
		x >= 0x1100 && (
			x <= 0x115f ||  // Hangul Jamo
			x === 0x2329 || // LEFT-POINTING ANGLE BRACKET
			x === 0x232a || // RIGHT-POINTING ANGLE BRACKET
			// CJK Radicals Supplement .. Enclosed CJK Letters and Months
			(0x2e80 <= x && x <= 0x3247 && x !== 0x303f) ||
			// Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
			(0x3250 <= x && x <= 0x4dbf) ||
			// CJK Unified Ideographs .. Yi Radicals
			(0x4e00 <= x && x <= 0xa4c6) ||
			// Hangul Jamo Extended-A
			(0xa960 <= x && x <= 0xa97c) ||
			// Hangul Syllables
			(0xac00 <= x && x <= 0xd7a3) ||
			// CJK Compatibility Ideographs
			(0xf900 <= x && x <= 0xfaff) ||
			// Vertical Forms
			(0xfe10 <= x && x <= 0xfe19) ||
			// CJK Compatibility Forms .. Small Form Variants
			(0xfe30 <= x && x <= 0xfe6b) ||
			// Halfwidth and Fullwidth Forms
			(0xff01 <= x && x <= 0xff60) ||
			(0xffe0 <= x && x <= 0xffe6) ||
			// Kana Supplement
			(0x1b000 <= x && x <= 0x1b001) ||
			// Enclosed Ideographic Supplement
			(0x1f200 <= x && x <= 0x1f251) ||
			// CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
			(0x20000 <= x && x <= 0x3fffd)
		)
	) {
		return true;
	}

	return false;
};


is-fullwidth-code-point

description: Check if the character represented by a given Unicode code point is fullwidth

repository: sindresorhus/is-fullwidth-code-point

keywords: fullwidth full-width full width unicode character char string str codepoint code point is detect check


code:
# is-fullwidth-code-point [![Build Status](https://travis-ci.org/sindresorhus/is-fullwidth-code-point.svg?branch=master)](https://travis-ci.org/sindresorhus/is-fullwidth-code-point)

> Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms)

## Install

```
$ npm install --save is-fullwidth-code-point
```

## Usage

```js
const isFullwidthCodePoint = require('is-fullwidth-code-point');

isFullwidthCodePoint('谢'.codePointAt());
//=> true

isFullwidthCodePoint('a'.codePointAt());
//=> false
```

## API

### isFullwidthCodePoint(input)

#### input

Type: `number`

[Code point](https://en.wikipedia.org/wiki/Code_point) of a character.

## License

MIT © [Sindre Sorhus](https://sindresorhus.com)


code:
'use strict';
const ansiEscapes = require('ansi-escapes');
const cliCursor = require('cli-cursor');
const wrapAnsi = require('wrap-ansi');

const getWidth = stream => {
	const columns = stream.columns;

	if (!columns) {
		return 80;
	}

	// Windows appears to wrap a character early
	// I hate Windows so much
	if (process.platform === 'win32') {
		return columns - 1;
	}

	return columns;
};

const main = (stream, options) => {
	options = Object.assign({
		showCursor: false
	}, options);

	let prevLineCount = 0;

	const render = function () {
		if (!options.showCursor) {
			cliCursor.hide();
		}

		let out = [].join.call(arguments, ' ') + '\n';
		out = wrapAnsi(out, getWidth(stream), {
			trim: false,
			hard: true,
			wordWrap: false
		});
		stream.write(ansiEscapes.eraseLines(prevLineCount) + out);
		prevLineCount = out.split('\n').length;
	};

	render.clear = () => {
		stream.write(ansiEscapes.eraseLines(prevLineCount));
		prevLineCount = 0;
	};

	render.done = () => {
		prevLineCount = 0;

		if (!options.showCursor) {
			cliCursor.show();
		}
	};

	return render;
};

module.exports = main(process.stdout);
module.exports.stderr = main(process.stderr);
module.exports.create = main;


log-update

description: Log by overwriting the previous output in the terminal. Useful for rendering progress bars, animations, etc.

repository: sindresorhus/log-update

test: xo && node test.js

keywords: log logger logging cli terminal term console shell update refresh overwrite output stdout progress bar animation


code:
# log-update [![Build Status](https://travis-ci.org/sindresorhus/log-update.svg?branch=master)](https://travis-ci.org/sindresorhus/log-update)

> Log by overwriting the previous output in the terminal.

> Useful for rendering progress bars, animations, etc.

![](screenshot.gif)

## Install

```
$ npm install log-update
```

## Usage

```js
const logUpdate = require('log-update');
const frames = ['-', '\\', '|', '/'];
let i = 0;

setInterval(() => {
	const frame = frames[i = ++i % frames.length];

	logUpdate(
`
        ♥♥
   ${frame} unicorns ${frame}
        ♥♥
`
	);
}, 80);
```

## API

### logUpdate(text, ...)

Log to stdout.

### logUpdate.clear()

Clear the logged output.

### logUpdate.done()

Persist the logged output.

Useful if you want to start a new log session below the current one.

### logUpdate.stderr(text, ...)

Log to stderr.

### logUpdate.stderr.clear()
### logUpdate.stderr.done()

### logUpdate.create(stream, [options])

Get a `logUpdate` method that logs to the specified stream.

#### options

Type: `Object`

##### showCursor

Type: `boolean`

Default: `false`

Show the cursor. This can be useful when a CLI accepts input from a user.

```js
// Write output but don't hide the cursor
const log = logUpdate.create(process.stdout, {
	showCursor: true
});
```

## Examples

- [listr](https://github.com/SamVerschueren/listr) - Uses this module to render an interactive task list
- [ora](https://github.com/sindresorhus/ora) - Uses this module to render awesome spinners
- [speed-test](https://github.com/sindresorhus/speed-test) - Uses this module to render a [spinner](https://github.com/sindresorhus/elegant-spinner)

## License

MIT © [Sindre Sorhus](https://sindresorhus.com)


code:
'use strict';
module.exports = (to, from) => {
	// TODO: use `Reflect.ownKeys()` when targeting Node.js 6
	for (const prop of Object.getOwnPropertyNames(from).concat(Object.getOwnPropertySymbols(from))) {
		Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
	}

	return to;
};


mimic-fn

description: Make a function mimic another one

repository: sindresorhus/mimic-fn

keywords: function mimic imitate rename copy inherit properties name func fn set infer change


code:
# mimic-fn [![Build Status](https://travis-ci.org/sindresorhus/mimic-fn.svg?branch=master)](https://travis-ci.org/sindresorhus/mimic-fn)

> Make a function mimic another one

Useful when you wrap a function in another function and like to preserve the original name and other properties.

## Install

```
$ npm install mimic-fn
```

## Usage

```js
const mimicFn = require('mimic-fn');

function foo() {}
foo.unicorn = '🦄';

function wrapper() {
	return foo() {};
}

console.log(wrapper.name);
//=> 'wrapper'

mimicFn(wrapper, foo);

console.log(wrapper.name);
//=> 'foo'

console.log(wrapper.unicorn);
//=> '🦄'
```

## API

It will copy over the properties `name`, `length`, `displayName`, and any custom properties you may have set.

### mimicFn(to, from)

It will modify `to` and return it.

#### to

Type: `Function`

Mimicking function.

#### from

Type: `Function`

Function to mimic.

## Related

- [rename-fn](https://github.com/sindresorhus/rename-fn) - Rename a function

## License

MIT © [Sindre Sorhus](https://sindresorhus.com)


code:
'use strict';
const mimicFn = require('mimic-fn');

module.exports = (fn, opts) => {
	// TODO: Remove this in v3
	if (opts === true) {
		throw new TypeError('The second argument is now an options object');
	}

	if (typeof fn !== 'function') {
		throw new TypeError('Expected a function');
	}

	opts = opts || {};

	let ret;
	let called = false;
	const fnName = fn.displayName || fn.name || '<anonymous>';

	const onetime = function () {
		if (called) {
			if (opts.throw === true) {
				throw new Error(`Function \`${fnName}\` can only be called once`);
			}

			return ret;
		}

		called = true;
		ret = fn.apply(this, arguments);
		fn = null;

		return ret;
	};

	mimicFn(onetime, fn);

	return onetime;
};


onetime

description: Ensure a function is only called once

repository: sindresorhus/onetime

keywords: once function one onetime func fn single call called prevent


code:
# onetime [![Build Status](https://travis-ci.org/sindresorhus/onetime.svg?branch=master)](https://travis-ci.org/sindresorhus/onetime)

> Ensure a function is only called once

When called multiple times it will return the return value from the first call.

*Unlike the module [once](https://github.com/isaacs/once), this one isn't naughty extending `Function.prototype`.*

## Install

```
$ npm install --save onetime
```

## Usage

```js
let i = 0;

const foo = onetime(() => i++);

foo(); //=> 0
foo(); //=> 0
foo(); //=> 0
```

```js
const foo = onetime(() => {}, {throw: true});

foo();

foo();
//=> Error: Function `foo` can only be called once
```

## API

### onetime(fn, [options])

Returns a function that only calls `fn` once.

#### fn

Type: `Function`

Function that should only be called once.

#### options

Type: `Object`

##### throw

Type: `boolean`<br>
Default: `false`

Throw an error when called more than once.

## License

MIT © [Sindre Sorhus](https://sindresorhus.com)


code:
'use strict';
const onetime = require('onetime');
const signalExit = require('signal-exit');

module.exports = onetime(() => {
	signalExit(() => {
		process.stderr.write('\u001b[?25h');
	}, {alwaysLast: true});
});


restore-cursor

description: Gracefully restore the CLI cursor on exit

repository: sindresorhus/restore-cursor

keywords: exit quit process graceful shutdown sigterm sigint terminate kill stop cli cursor ansi show term terminal console tty shell command-line


code:
# restore-cursor

> Gracefully restore the CLI cursor on exit

Prevent the cursor you've hidden interactively from remaining hidden if the process crashes.

## Install

```
$ npm install --save restore-cursor
```

## Usage

```js
const restoreCursor = require('restore-cursor');
restoreCursor();
```

## License

MIT © [Sindre Sorhus](https://sindresorhus.com)


code:
'use strict';
const stripAnsi = require('strip-ansi');
const isFullwidthCodePoint = require('is-fullwidth-code-point');

module.exports = str => {
	if (typeof str !== 'string' || str.length === 0) {
		return 0;
	}

	str = stripAnsi(str);

	let width = 0;

	for (let i = 0; i < str.length; i++) {
		const code = str.codePointAt(i);

		// Ignore control characters
		if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) {
			continue;
		}

		// Ignore combining characters
		if (code >= 0x300 && code <= 0x36F) {
			continue;
		}

		// Surrogates
		if (code > 0xFFFF) {
			i++;
		}

		width += isFullwidthCodePoint(code) ? 2 : 1;
	}

	return width;
};


string-width

description: Get the visual width of a string - the number of columns required to display it

repository: sindresorhus/string-width

keywords: string str character char unicode width visual column columns fullwidth full-width full ansi escape codes cli command-line terminal console cjk chinese japanese korean fixed-width


code:
# string-width [![Build Status](https://travis-ci.org/sindresorhus/string-width.svg?branch=master)](https://travis-ci.org/sindresorhus/string-width)

> Get the visual width of a string - the number of columns required to display it

Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width.

Useful to be able to measure the actual width of command-line output.

## Install

```
$ npm install string-width
```

## Usage

```js
const stringWidth = require('string-width');

stringWidth('古');
//=> 2

stringWidth('\u001b[1m古\u001b[22m');
//=> 2

stringWidth('a');
//=> 1
```

## Related

- [string-width-cli](https://github.com/sindresorhus/string-width-cli) - CLI for this module
- [string-length](https://github.com/sindresorhus/string-length) - Get the real length of a string
- [widest-line](https://github.com/sindresorhus/widest-line) - Get the visual width of the widest line in a string

## License

MIT © [Sindre Sorhus](https://sindresorhus.com)


code:
'use strict';
const ansiRegex = require('ansi-regex');

module.exports = input => typeof input === 'string' ? input.replace(ansiRegex(), '') : input;


strip-ansi

description: Strip ANSI escape codes

repository: chalk/strip-ansi

keywords: strip trim remove ansi styles color colour colors terminal console string tty escape formatting rgb 256 shell xterm log logging command-line text


code:
# strip-ansi [![Build Status](https://travis-ci.org/chalk/strip-ansi.svg?branch=master)](https://travis-ci.org/chalk/strip-ansi)

> Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code)

## Install

```
$ npm install strip-ansi
```

## Usage

```js
const stripAnsi = require('strip-ansi');

stripAnsi('\u001B[4mUnicorn\u001B[0m');
//=> 'Unicorn'
```

## Related

- [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right

## Maintainers

- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)

## License

MIT


code:
'use strict';
const stringWidth = require('string-width');
const stripAnsi = require('strip-ansi');

const ESCAPES = new Set([
	'\u001B',
	'\u009B'
]);

const END_CODE = 39;

const ESCAPE_CODES = new Map([
	[0, 0],
	[1, 22],
	[2, 22],
	[3, 23],
	[4, 24],
	[7, 27],
	[8, 28],
	[9, 29],
	[30, 39],
	[31, 39],
	[32, 39],
	[33, 39],
	[34, 39],
	[35, 39],
	[36, 39],
	[37, 39],
	[90, 39],
	[40, 49],
	[41, 49],
	[42, 49],
	[43, 49],
	[44, 49],
	[45, 49],
	[46, 49],
	[47, 49]
]);

const wrapAnsi = code => `${ESCAPES.values().next().value}[${code}m`;

// Calculate the length of words split on ' ', ignoring
// the extra characters added by ansi escape codes
const wordLengths = str => str.split(' ').map(s => stringWidth(s));

// Wrap a long word across multiple rows
// Ansi escape codes do not count towards length
const wrapWord = (rows, word, cols) => {
	const arr = Array.from(word);

	let insideEscape = false;
	let visible = stringWidth(stripAnsi(rows[rows.length - 1]));

	for (const item of arr.entries()) {
		const i = item[0];
		const char = item[1];
		const charLength = stringWidth(char);

		if (visible + charLength <= cols) {
			rows[rows.length - 1] += char;
		} else {
			rows.push(char);
			visible = 0;
		}

		if (ESCAPES.has(char)) {
			insideEscape = true;
		} else if (insideEscape && char === 'm') {
			insideEscape = false;
			continue;
		}

		if (insideEscape) {
			continue;
		}

		visible += charLength;

		if (visible === cols && i < arr.length - 1) {
			rows.push('');
			visible = 0;
		}
	}

	// It's possible that the last row we copy over is only
	// ansi escape characters, handle this edge-case
	if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) {
		rows[rows.length - 2] += rows.pop();
	}
};

// The wrap-ansi module can be invoked
// in either 'hard' or 'soft' wrap mode
//
// 'hard' will never allow a string to take up more
// than cols characters
//
// 'soft' allows long words to expand past the column length
const exec = (str, cols, opts) => {
	const options = opts || {};

	if (str.trim() === '') {
		return options.trim === false ? str : str.trim();
	}

	let pre = '';
	let ret = '';
	let escapeCode;

	const lengths = wordLengths(str);
	const words = str.split(' ');
	const rows = [''];

	for (const item of Array.from(words).entries()) {
		const i = item[0];
		const word = item[1];

		rows[rows.length - 1] = options.trim === false ? rows[rows.length - 1] : rows[rows.length - 1].trim();
		let rowLength = stringWidth(rows[rows.length - 1]);

		if (rowLength || word === '') {
			if (rowLength === cols && options.wordWrap === false) {
				// If we start with a new word but the current row length equals the length of the columns, add a new row
				rows.push('');
				rowLength = 0;
			}

			rows[rows.length - 1] += ' ';
			rowLength++;
		}

		// In 'hard' wrap mode, the length of a line is
		// never allowed to extend past 'cols'
		if (lengths[i] > cols && options.hard) {
			if (rowLength) {
				rows.push('');
			}
			wrapWord(rows, word, cols);
			continue;
		}

		if (rowLength + lengths[i] > cols && rowLength > 0) {
			if (options.wordWrap === false && rowLength < cols) {
				wrapWord(rows, word, cols);
				continue;
			}

			rows.push('');
		}

		if (rowLength + lengths[i] > cols && options.wordWrap === false) {
			wrapWord(rows, word, cols);
			continue;
		}

		rows[rows.length - 1] += word;
	}

	pre = rows.map(r => options.trim === false ? r : r.trim()).join('\n');

	for (const item of Array.from(pre).entries()) {
		const i = item[0];
		const char = item[1];

		ret += char;

		if (ESCAPES.has(char)) {
			const code = parseFloat(/\d[^m]*/.exec(pre.slice(i, i + 4)));
			escapeCode = code === END_CODE ? null : code;
		}

		const code = ESCAPE_CODES.get(Number(escapeCode));

		if (escapeCode && code) {
			if (pre[i + 1] === '\n') {
				ret += wrapAnsi(code);
			} else if (char === '\n') {
				ret += wrapAnsi(escapeCode);
			}
		}
	}

	return ret;
};

// For each newline, invoke the method separately
module.exports = (str, cols, opts) => {
	return String(str)
		.normalize()
		.split('\n')
		.map(line => exec(line, cols, opts))
		.join('\n');
};


wrap-ansi

description: Wordwrap a string with ANSI escape codes

repository: chalk/wrap-ansi

test: xo && nyc ava

coveralls: nyc report --reporter=text-lcov | coveralls

keywords: wrap break wordwrap wordbreak linewrap ansi styles color colour colors terminal console cli string tty escape formatting rgb 256 shell xterm log logging command-line text


code:
# wrap-ansi [![Build Status](https://travis-ci.org/chalk/wrap-ansi.svg?branch=master)](https://travis-ci.org/chalk/wrap-ansi) [![Coverage Status](https://coveralls.io/repos/github/chalk/wrap-ansi/badge.svg?branch=master)](https://coveralls.io/github/chalk/wrap-ansi?branch=master)

> Wordwrap a string with [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles)

## Install

```
$ npm install wrap-ansi
```

## Usage

```js
const chalk = require('chalk');
const wrapAnsi = require('wrap-ansi');

const input = 'The quick brown ' + chalk.red('fox jumped over ') +
	'the lazy ' + chalk.green('dog and then ran away with the unicorn.');

console.log(wrapAnsi(input, 20));
```

## API

### wrapAnsi(input, columns, [options])

Wrap words to the specified column width.

#### input

Type: `string`

String with ANSI escape codes. Like one styled by [`chalk`](https://github.com/chalk/chalk).

#### columns

Type: `number`

Number of columns to wrap the text to.

#### options

Type: `Object`

##### hard

Type: `boolean`

Default: `false`

By default the wrap is soft, meaning long words may extend past the column width. Setting this to `true` will make it hard wrap at the column width.

##### wordWrap

Type: `boolean`

Default: `true`

By default, an attempt is made to split words at spaces, ensuring that they don't extend past the configured columns. If wordWrap is `false`, each column will instead be completely filled splitting words as necessary.

##### trim

Type: `boolean`

Default: `true`

Whitespace on all lines is removed by default. Set this option to `false` if you don't want to trim.

## Related

- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes
- [cli-truncate](https://github.com/sindresorhus/cli-truncate) - Truncate a string to a specific width in the terminal
- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right
- [jsesc](https://github.com/mathiasbynens/jsesc) - Generate ASCII-only output from Unicode strings. Useful for creating test fixtures.

## Maintainers

- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)
- [Benjamin Coe](https://github.com/bcoe)

## License

MIT


progress-webpack-plugin

description: progress webpack plugin

test: mocha test

author: alichen


code:
let webpack = require('webpack')
let expect = require('chai').expect
let path = require('path')
let ProgressPlugin = require('../')

const OUTPUT_PATH = path.join(__dirname, 'dist')

describe('Progress Plugin', () => {
  it('should output correctly', done => {
    let compiler = webpack(
      {
        entry: {
          main: path.join(__dirname, 'fixture', 'entry.js')
        },
        mode: 'production',
        output: {
          path: OUTPUT_PATH,
          filename: '[name].min.js'
        },
        plugins: [
          new ProgressPlugin({
            identifier: 'test'
          })
        ]
      },
      (err, stats) => {
        expect(err).to.equal(null)
        done()
      }
    )
  })
})