Commit f8dc84f4 by 马玮

Install mysql modules

parent 259a9047
All packages installed at Fri Aug 11 2017 20:32:35 GMT+0800 (CST)
\ No newline at end of file
All packages installed at Mon Aug 14 2017 15:01:52 GMT+0800 (CST)
\ No newline at end of file
lib-cov
*.seed
*.log
*.csv
*.dat
*.out
*.pid
*.gz
pids
logs
results
npm-debug.log
node_modules
Mon Aug 14 2017 15:01:51 GMT+0800 (CST)
\ No newline at end of file
language: node_js
node_js:
- 0.6
- 0.8
Copyright 2013 Thorsten Lorenz.
All rights reserved.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
# ansicolors [![build status](https://secure.travis-ci.org/thlorenz/ansicolors.png)](http://next.travis-ci.org/thlorenz/ansicolors)
Functions that surround a string with ansicolor codes so it prints in color.
## Installation
npm install ansicolors
## Usage
```js
var colors = require('ansicolors');
// foreground colors
var redHerring = colors.red('herring');
var blueMoon = colors.blue('moon');
var brighBlueMoon = colors.brightBlue('moon');
console.log(redHerring); // this will print 'herring' in red
console.log(blueMoon); // this 'moon' in blue
console.log(brightBlueMoon); // I think you got the idea
// background colors
console.log(colors.bgYellow('printed on yellow background'));
console.log(colors.bgBrightBlue('printed on bright blue background'));
// mixing background and foreground colors
// below two lines have same result (order in which bg and fg are combined doesn't matter)
console.log(colors.bgYellow(colors.blue('printed on yellow background in blue')));
console.log(colors.blue(colors.bgYellow('printed on yellow background in blue')));
```
## Tests
Look at the [tests](https://github.com/thlorenz/ansicolors/blob/master/test/ansicolors.js) to see more examples and/or run them via:
npm explore ansicolors && npm test
## Alternatives
**ansicolors** tries to meet simple use cases with a very simple API. However, if you need a more powerful ansi formatting tool,
I'd suggest to look at the [features](https://github.com/TooTallNate/ansi.js#features) of the [ansi module](https://github.com/TooTallNate/ansi.js).
// ColorCodes explained: http://www.termsys.demon.co.uk/vtansi.htm
'use strict';
var colorNums = {
white : 37
, black : 30
, blue : 34
, cyan : 36
, green : 32
, magenta : 35
, red : 31
, yellow : 33
, brightBlack : 90
, brightRed : 91
, brightGreen : 92
, brightYellow : 93
, brightBlue : 94
, brightMagenta : 95
, brightCyan : 96
, brightWhite : 97
}
, backgroundColorNums = {
bgBlack : 40
, bgRed : 41
, bgGreen : 42
, bgYellow : 43
, bgBlue : 44
, bgMagenta : 45
, bgCyan : 46
, bgWhite : 47
, bgBrightBlack : 100
, bgBrightRed : 101
, bgBrightGreen : 102
, bgBrightYellow : 103
, bgBrightBlue : 104
, bgBrightMagenta : 105
, bgBrightCyan : 106
, bgBrightWhite : 107
}
, colors = {};
Object.keys(colorNums).forEach(function (k) {
colors[k] = function (s) {
return '\u001b[' + colorNums[k] + 'm' + s + '\u001b[39m';
};
});
Object.keys(backgroundColorNums).forEach(function (k) {
colors[k] = function (s) {
return '\u001b[' + backgroundColorNums[k] + 'm' + s + '\u001b[49m';
};
});
module.exports = colors;
{
"name": "ansicolors",
"version": "0.2.1",
"description": "Functions that surround a string with ansicolor codes so it prints in color.",
"main": "ansicolors.js",
"scripts": {
"test": "node test/*.js"
},
"repository": {
"type": "git",
"url": "git://github.com/thlorenz/ansicolors.git"
},
"keywords": [
"ansi",
"colors",
"highlight",
"string"
],
"author": "Thorsten Lorenz <thlorenz@gmx.de> (thlorenz.com)",
"license": "MIT",
"readmeFilename": "README.md",
"gitHead": "858847ca28e8b360d9b70eee0592700fa2ab087d",
"_from": "ansicolors@0.2.1",
"_resolved": "http://registry.npm.taobao.org/ansicolors/download/ansicolors-0.2.1.tgz"
}
\ No newline at end of file
'use strict';
var assert = require('assert')
, colors = require('..');
console.log('Foreground colors ..');
assert.equal(colors.white('printed in white'), '\u001b[37mprinted in white\u001b[39m');
assert.equal(colors.black('printed in black'), '\u001b[30mprinted in black\u001b[39m');
assert.equal(colors.brightBlack('printed in bright black'), '\u001b[90mprinted in bright black\u001b[39m');
assert.equal(colors.green('printed in green'), '\u001b[32mprinted in green\u001b[39m');
assert.equal(colors.brightGreen('printed in bright green'), '\u001b[92mprinted in bright green\u001b[39m');
assert.equal(colors.red('printed in red'), '\u001b[31mprinted in red\u001b[39m');
assert.equal(colors.brightRed('printed in bright red'), '\u001b[91mprinted in bright red\u001b[39m');
console.log('OK');
console.log('Background colors ..');
assert.equal(
colors.bgBlack('printed with black background')
, '\u001b[40mprinted with black background\u001b[49m'
);
assert.equal(
colors.bgYellow('printed with yellow background')
, '\u001b[43mprinted with yellow background\u001b[49m'
);
assert.equal(
colors.bgBrightYellow('printed with bright yellow background')
, '\u001b[103mprinted with bright yellow background\u001b[49m'
);
assert.equal(
colors.bgWhite('printed with white background')
, '\u001b[47mprinted with white background\u001b[49m'
);
console.log('OK');
console.log('Mixing background and foreground colors ..');
assert.equal(
colors.blue(colors.bgYellow('printed in blue with yellow background'))
, '\u001b[34m\u001b[43mprinted in blue with yellow background\u001b[49m\u001b[39m'
);
assert.equal(
colors.bgYellow(colors.blue('printed in blue with yellow background again'))
, '\u001b[43m\u001b[34mprinted in blue with yellow background again\u001b[39m\u001b[49m'
);
console.log('OK');
Mon Aug 14 2017 14:58:47 GMT+0800 (CST)
\ No newline at end of file
The MIT Licence.
Copyright (c) 2012, 2013, 2014, 2015, 2016, 2017 Michael Mclaughlin
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
"name": "bignumber.js",
"main": "bignumber.js",
"version": "4.0.2",
"homepage": "https://github.com/MikeMcl/bignumber.js",
"authors": [
"Michael Mclaughlin <M8ch88l@gmail.com>"
],
"description": "A library for arbitrary-precision decimal and non-decimal arithmetic",
"moduleType": [
"amd",
"globals",
"node"
],
"keywords": [
"arbitrary",
"precision",
"arithmetic",
"big",
"number",
"decimal",
"float",
"biginteger",
"bigdecimal",
"bignumber",
"bigint",
"bignum"
],
"license": "MIT",
"ignore": [
".*",
"*.json",
"test"
]
}
{
"name": "bignumber.js",
"description": "A library for arbitrary-precision decimal and non-decimal arithmetic",
"version": "4.0.2",
"keywords": [
"arbitrary",
"precision",
"arithmetic",
"big",
"number",
"decimal",
"float",
"biginteger",
"bigdecimal",
"bignumber",
"bigint",
"bignum"
],
"repository": {
"type": "git",
"url": "https://github.com/MikeMcl/bignumber.js.git"
},
"main": "bignumber.js",
"author": {
"name": "Michael Mclaughlin",
"email": "M8ch88l@gmail.com"
},
"engines": {
"node": "*"
},
"license": "MIT",
"scripts": {
"test": "node ./test/every-test.js",
"build": "uglifyjs bignumber.js --source-map bignumber.js.map -c -m -o bignumber.min.js --preamble \"/* bignumber.js v4.0.2 https://github.com/MikeMcl/bignumber.js/LICENCE */\""
},
"_from": "bignumber.js@4.0.2",
"_resolved": "http://registry.npm.taobao.org/bignumber.js/download/bignumber.js-4.0.2.tgz"
}
\ No newline at end of file
Mon Aug 14 2017 15:01:50 GMT+0800 (CST)
\ No newline at end of file
language: node_js
node_js:
- "0.10"
- "0.12"
- "iojs"
Copyright 2012 Thorsten Lorenz.
All rights reserved.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
# cardinal [![Build Status](https://secure.travis-ci.org/thlorenz/cardinal.png)](http://travis-ci.org/thlorenz/cardinal)
[![NPM](https://nodei.co/npm/cardinal.png?downloads=true&stars=true)](https://nodei.co/npm/cardinal/)
**car·di·nal** *(kärdn-l, kärdnl)* - crested thick-billed North American finch having bright red plumage in the male.
![screenshot](https://github.com/thlorenz/cardinal/raw/master/assets/screen-shot.png)
## Features
- highlights JavaScript code with ANSI colors to improve terminal output
- theming support, see [custom color themes](https://github.com/thlorenz/cardinal/tree/master/themes)
- optionally print line numbers
- API and command line interface (`cdl`)
- `.cardinalrc` config to customize settings
- supports UNIX pipes
***
**Table of Contents** *generated with [DocToc](http://doctoc.herokuapp.com/)*
- [Installation](#installation)
- [As library](#as-library)
- [As Commandline Tool](#as-commandline-tool)
- [Commandline](#commandline)
- [Highlight a file](#highlight-a-file)
- [As part of a UNIX pipe](#as-part-of-a-unix-pipe)
- [Theme](#theme)
- [API](#api)
- [*highlight(code[, opts])*](#highlightcode-opts)
- [*highlightFileSync(fullPath[, opts])*](#highlightfilesyncfullpath-opts)
- [*highlightFile(fullPath[, opts], callback)*](#highlightfilefullpath-opts-callback)
- [opts](#opts)
- [Examples ([*browse*](https://github.com/thlorenz/cardinal/tree/master/examples))](#examples-[browse]https://githubcom/thlorenz/cardinal/tree/master/examples)
## Installation
### As library
npm install cardinal
### As Commandline Tool
[sudo] npm install -g cardinal
**Note:**
When installed globally, cardinal exposes itself as the `cdl` command.
## Commandline
### Highlight a file
cdl <file.js> [options]
**options**:
- `--nonum`: turns off line number printing (relevant if it is turned on inside `~/.cardinalrc`
### As part of a UNIX pipe
cat file.js | grep console | cdl
**Note:**
Not all code lines may be parsable JavaScript. In these cases the line is printed to the terminal without
highlighting it.
### Theme
The default theme will be used for highlighting.
To use a different theme, include a `.cardinalrc` file in your `HOME` directory.
This is a JSON file of the following form:
```json
{
"theme": "hide-semicolons",
"linenos": true|false
}
```
- `theme` can be the name of any of the [built-in themes](https://github.com/thlorenz/cardinal/tree/master/themes) or the
full path to a custom theme anywhere on your computer.
- linenos toggles line number printing
## API
### *highlight(code[, opts])*
- returns the highlighted version of the passed code ({String}) or throws an error if it was not able to parse it
- opts (see below)
### *highlightFileSync(fullPath[, opts])*
- returns the highlighted version of the file whose fullPath ({String}) was passed or throws an error if it was not able
to parse it
- opts (see below)
### *highlightFile(fullPath[, opts], callback)*
- calls back with the highlighted version of the file whose fullPath ({String}) was passed or with an error if it was not able
to parse it
- opts (see below)
- `callback` ({Function}) has the following signature: `function (err, highlighted) { .. }`
### opts
opts is an {Object} with the following properties:
- `theme` {Object} is used to optionally override the theme used to highlight
- `linenos` {Boolean} if `true` line numbers are included in the highlighted code
- `firstline` {Integer} sets line number of the first line when line numbers are printed
**Note** The `json` option is obsoleted and not necessary anymore as cardinal properly understands both JSON and JavaScript.
## Examples ([*browse*](https://github.com/thlorenz/cardinal/tree/master/examples))
- [sample .cardinalrc](https://github.com/thlorenz/cardinal/blob/master/examples/.cardinalrc)
- [highlighting a code snippet](https://github.com/thlorenz/cardinal/blob/master/examples/highlight-string.js) via
***highlight()***
- [file that highlights itself](https://github.com/thlorenz/cardinal/blob/master/examples/highlight-self.js) via
***highlightFile()*** including line numbers
- [file that highlights itself hiding all
semicolons](https://github.com/thlorenz/cardinal/blob/master/examples/highlight-self-hide-semicolons.js) via
***highlightFileSync()***
#!/usr/bin/env node
var cardinal = require('..')
, utl = require('../utl')
, settings = require('../settings')
, args = process.argv
, theme = settings.resolveTheme()
, opts = settings.getSettings()
, highlighted
;
opts = opts || {};
opts.theme = theme;
function usage() {
var msg = [
'Usage: cdl <filename.js> [options]'
, ''
, 'Options (~/.cardinalrc overrides):'
, ' --nonum: turn off line printing'
, ''
, 'Unix Pipe Example: cat filename.js | grep console | cdl'
, ''
].join('\n');
console.log(msg);
}
function highlightFile () {
try {
highlighted = cardinal.highlightFileSync(args[2], opts);
console.log(highlighted);
} catch (e) {
console.trace();
console.error(e);
}
}
// E.g., "cardinal myfile.js"
if (args.length === 3) return highlightFile();
var opt = args[3];
// E.g., "cardinal myfile.js --nonum"
if (opt && opt.indexOf('--') === 0 ) {
if ((/^--(nonum|noline)/i).test(opt)) opts.linenos = false;
else {
usage();
return console.error('Unknown option: ', opt);
}
return highlightFile();
}
// UNIX pipes e.g., "cat myfile.js | grep console | cardinal
var stdin = process.stdin
, stdout = process.stdout;
// line numbers don't make sense when we are printing line by line
opts.linenos = false;
stdin.setEncoding('utf-8');
stdin.resume();
stdin
.on('data', function (chunk) {
chunk.split('\n').forEach(function (line) {
try {
stdout.write(cardinal.highlight(line, opts) + '\n');
} catch (e) {
// line doesn't represent a valid js snippet and therefore cannot be parsed -> just print as is
stdout.write(line + '\n');
}
});
});
module.exports = {
highlight: require('./lib/highlight')
, highlightFile: require('./lib/highlightFile')
, highlightFileSync: require('./lib/highlightFileSync')
};
# Cardinal Examples
You can run the examples individually or as a demo:
- install cardinal: `npm install cardinal`
- explore cardinal: `npm explore cardinal`
- run the demo: `npm run demo`
// This file will highlight the passed code using the custom theme when run via: "node highlight-json"
var cardinal = require('..');
var json = JSON.stringify({
foo: 'bar',
baz: 'quux'
});
console.log(cardinal.highlight(json));
/*
* This file will highlight itself using a custom theme when run via: "node highlight-self-hide-semicolons"
* The custom theme highlights semicolons as 'black', thus hiding them.
*/
var cardinal = require('..')
, hideSemicolonsTheme = require('../themes/hide-semicolons');
function highlight () {
// Using the synchronous highlightFileSync()
// For asynchronous highlighting use: highlightFile() - see highlight-self.js
try {
var highlighted = cardinal.highlightFileSync(__filename, {theme: hideSemicolonsTheme});
console.log(highlighted);
} catch (err) {
console.error(err);
}
}
highlight();
// This file will highlight itself using the default theme when run via: "node highlight-self"
var cardinal = require('..');
function highlight () {
// Using the asynchronous highlightFile()
// For synchronous highlighting use: highlightFileSync() - see highlight-self-hide-semicolons.js
cardinal.highlightFile(__filename, { linenos: true }, function (err, res) {
if (err) return console.error(err);
console.log(res);
});
}
highlight();
// This file will highlight the passed code using the custom theme when run via: "node highlight-string"
var cardinal = require('..');
var code = '' +
function add (a, b) {
var sum = a + b;
return sum;
} +
'';
console.log(cardinal.highlight(code));
var redeyed = require('redeyed')
, theme = require('../themes/default')
, colors = require('ansicolors')
, colorSurround = colors.brightBlack
, surroundClose = '\u001b[39m'
;
function trimEmptyLines(lines) {
// remove lines from the end until we find a non-empy one
var line = lines.pop();
while(!line || !line.length)
line = lines.pop();
// put the non-empty line back
if (line) lines.push(line);
}
function addLinenos (highlightedCode, firstline) {
var highlightedLines = highlightedCode.split('\n');
trimEmptyLines(highlightedLines);
var linesLen = highlightedLines.length
, lines = []
, totalDigits
, lineno
;
function getDigits (n) {
if (n < 10) return 1;
if (n < 100) return 2;
if (n < 1000) return 3;
if (n < 10000) return 4;
// this works for up to 99,999 lines - any questions?
return 5;
}
function pad (n, totalDigits) {
// not pretty, but simple and should perform quite well
var padDigits= totalDigits - getDigits(n);
switch(padDigits) {
case 0: return '' + n;
case 1: return ' ' + n;
case 2: return ' ' + n;
case 3: return ' ' + n;
case 4: return ' ' + n;
case 5: return ' ' + n;
}
}
totalDigits = getDigits(linesLen + firstline - 1);
for (var i = 0; i < linesLen; i++) {
// Don't close the escape sequence here in order to not break multi line code highlights like block comments
lineno = colorSurround(pad(i + firstline, totalDigits) + ': ').replace(surroundClose, '');
lines.push(lineno + highlightedLines[i]);
}
return lines.join('\n');
}
module.exports = function highlight (code, opts) {
opts = opts || { };
try {
var result = redeyed(code, opts.theme || theme)
, firstline = opts.firstline && !isNaN(opts.firstline) ? opts.firstline : 1;
return opts.linenos ? addLinenos(result.code, firstline) : result.code;
} catch (e) {
e.message = 'Unable to perform highlight. The code contained syntax errors: ' + e.message;
throw e;
}
};
var fs = require('fs')
, highlight = require('./highlight');
function isFunction (obj) {
return toString.call(obj) == '[object Function]';
}
module.exports = function highlightFile (fullPath, opts, cb) {
if (isFunction(opts)) {
cb = opts;
opts = { };
}
opts = opts || { };
fs.readFile(fullPath, 'utf-8', function (err, code) {
if (err) return cb(err);
try {
cb(null, highlight(code, opts));
} catch (e) {
cb(e);
}
});
};
var fs = require('fs')
, highlight = require('./highlight');
module.exports = function highlightFileSync (fullPath, opts) {
var code = fs.readFileSync(fullPath, 'utf-8');
opts = opts || { };
return highlight(code, opts);
};
../../_ansicolors@0.2.1@ansicolors
\ No newline at end of file
../../_redeyed@1.0.1@redeyed
\ No newline at end of file
{
"name": "cardinal",
"version": "1.0.0",
"description": "Syntax highlights JavaScript code with ANSI colors to be printed to the terminal.",
"main": "cardinal.js",
"scripts": {
"test": "tap ./test/*.js",
"demo": "node examples/highlight-string.js; node examples/highlight-self; node examples/highlight-self-hide-semicolons;"
},
"bin": {
"cdl": "./bin/cdl.js"
},
"repository": {
"type": "git",
"url": "git://github.com/thlorenz/cardinal.git"
},
"keywords": [
"syntax",
"highlight",
"theme",
"javascript",
"json",
"terminal",
"console",
"print",
"output"
],
"author": "Thorsten Lorenz <thlorenz@gmx.de> (thlorenz.com)",
"license": "MIT",
"dependencies": {
"ansicolors": "~0.2.1",
"redeyed": "~1.0.0"
},
"devDependencies": {
"tap": "~0.3.1",
"readdirp": "~0.2.1"
},
"_from": "cardinal@1.0.0",
"_resolved": "http://registry.npm.taobao.org/cardinal/download/cardinal-1.0.0.tgz"
}
\ No newline at end of file
var path = require('path')
, util = require('util')
, fs = require('fs')
, utl = require('./utl')
, home = process.env.HOME
, settings;
function getSettings (home_) {
if (settings) return settings;
try {
settingsJson = fs.readFileSync(path.join(home_ || home, '.cardinalrc'), 'utf-8');
} catch (_) {
// no .cardinalrc found - not a problem
return undefined;
}
try {
return JSON.parse(settingsJson);
} catch (e) {
// Have a .cardinalrc, but something about it is wrong - warn the user
// Coudn't parse the contained JSON
console.error(e);
return undefined;
}
}
// home_ mainly to be used during tests
// Resolves the preferred theme from the .cardinalrc found in the HOME directory
// If it couldn't be resolved, undefined is returned
function resolveTheme (home_) {
var themePath
, settings = getSettings(home_);
if (!settings || !settings.theme) return undefined;
try {
// allow specifying just the name of a built-in theme or a full path to a custom theme
themePath = utl.isPath(settings.theme) ? settings.theme : path.join(__dirname, 'themes', settings.theme);
return require(themePath);
} catch (e) {
// Specified theme path is invalid
console.error(e);
return undefined;
}
}
module.exports = {
resolveTheme: resolveTheme
, getSettings: getSettings
};
'use strict';
/*jshint asi: true*/
var test = require('tap').test
, fs = require('fs')
, customTheme = require('./fixtures/custom')
, cardinal = require('..')
function inspect(obj, depth) {
console.log(require('util').inspect(obj, false, depth || 5, true));
}
test('\nhighlighting a block comment without line numbers', function (t) {
var code = fs.readFileSync(__dirname + '/fixtures/block-comment.js', 'utf8');
var highlighted = cardinal.highlight(code, { theme: customTheme });
t.equal(highlighted, '\n\u001b[90m/**\n * This is a meaningless block jsdoc for a meaningless function.\n * Joins two strings, separating them to appear on two lines.\n * \n * @name foo\n * @function\n * @param uno {String} first string\n * @param dos {String} second string\n * @return {String} result of the join\n */\u001b[39m\n\u001b[96mmodule\u001b[39m\u001b[32m.\u001b[39m\u001b[96mexports\u001b[39m \u001b[93m=\u001b[39m \u001b[94mfunction\u001b[39m \u001b[96mfoo\u001b[39m \u001b[90m(\u001b[39m\u001b[96muno\u001b[39m\u001b[32m,\u001b[39m \u001b[96mdos\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m\n \u001b[31mreturn\u001b[39m \u001b[96muno\u001b[39m \u001b[93m+\u001b[39m \u001b[92m\'\\n\'\u001b[39m \u001b[93m+\u001b[39m \u001b[96mdos\u001b[39m\u001b[90m;\u001b[39m\n\u001b[33m}\u001b[39m\n')
t.end()
})
test('\nhighlighting a block comment with line numbers', function (t) {
var code = fs.readFileSync(__dirname + '/fixtures/block-comment.js', 'utf8');
var highlighted = cardinal.highlight(code, { theme: customTheme, linenos: true });
t.equal(highlighted, '\u001b[90m 1: \n\u001b[90m 2: \u001b[90m/**\n\u001b[90m 3: * This is a meaningless block jsdoc for a meaningless function.\n\u001b[90m 4: * Joins two strings, separating them to appear on two lines.\n\u001b[90m 5: * \n\u001b[90m 6: * @name foo\n\u001b[90m 7: * @function\n\u001b[90m 8: * @param uno {String} first string\n\u001b[90m 9: * @param dos {String} second string\n\u001b[90m10: * @return {String} result of the join\n\u001b[90m11: */\u001b[39m\n\u001b[90m12: \u001b[96mmodule\u001b[39m\u001b[32m.\u001b[39m\u001b[96mexports\u001b[39m \u001b[93m=\u001b[39m \u001b[94mfunction\u001b[39m \u001b[96mfoo\u001b[39m \u001b[90m(\u001b[39m\u001b[96muno\u001b[39m\u001b[32m,\u001b[39m \u001b[96mdos\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m\n\u001b[90m13: \u001b[31mreturn\u001b[39m \u001b[96muno\u001b[39m \u001b[93m+\u001b[39m \u001b[92m\'\\n\'\u001b[39m \u001b[93m+\u001b[39m \u001b[96mdos\u001b[39m\u001b[90m;\u001b[39m\n\u001b[90m14: \u001b[33m}\u001b[39m')
t.end()
})
/*jshint asi:true */
'use strict';
var fs = require('fs')
, path = require('path')
, utl = require('../utl')
, highlighter = require('..')
, colors = require('ansicolors')
, diffFile = path.join(__dirname, 'fixtures', 'git-diff.txt')
, diff = fs.readFileSync(diffFile, 'utf-8')
// @@ is not a valid js token, so when we see it, we can be sure that we are dealing with a git or svn diff
var diffRegex = /^@@[^@]+@@$/m;
var diffIndRegex = /^(@@[^@]+@@)(.*)$/;
var addRemRegex = /^[+\-]/;
var lines = diff.split('\n');
function isDiff(lines) {
return !!lines
.filter(function (line) {
return diffRegex.test(line);
})
.length;
}
var diff = isDiff(lines);
function tryHighlight(code) {
// TODO: need to remove symbols added to get valid code
// this should be done by getting the splits instead of the actual code from the highlighter
// now we can remove first / last one after highlighting completed
function tryAppending(appended, tryNext) {
try {
return highlighter.highlight(code + appended);
} catch (e) {
return tryNext(code);
}
}
function tryRemoveLeadingComma(tryNext) {
var success;
try {
success = highlighter.highlight(code.replace(/^( +),(.+)$/, '$1 $2'));
return success;
} catch (e) {
return tryNext(code);
}
}
function tryPlain() {
try {
return highlighter.highlight(code);
} catch (e) {
return tryCloseMustache();
}
}
function tryCloseMustache() { return tryAppending('}', tryCloseParen); }
function tryCloseParen() { return tryAppending('\\)', tryCloseMustacheParen); }
function tryCloseMustacheParen() { return tryAppending('})', tryRemovingCommas);}
function tryRemovingCommas() { return tryRemoveLeadingComma(giveUp); }
function giveUp() { return code; }
return tryPlain();
}
function highlightDiffInd(line, matches) {
var highlighted = colors.brightBlue(matches[1])
, code = matches[2];
return code ? highlighted + tryHighlight(code) : highlighted;
}
function colorsAddRemove(c) {
return addRemRegex.test(c) ? colors.yellow(c) : c;
}
function highlightDiff(line) {
var diffIndMatches = diffIndRegex.exec(line);
return diffIndMatches
? highlightDiffInd(line, diffIndMatches)
: colorsAddRemove(line[0]) + tryHighlight(line.slice(1));
}
var highlightFn = diff ? highlightDiff : tryHighlight;
var highlightedLines = lines.map(highlightFn);
console.log(highlightedLines.join('\n'));
'use strict';
/*jshint asi: true*/
var test = require('tap').test
, util = require('util')
, fs = require('fs')
, path = require('path')
, customTheme = require('./fixtures/custom')
, cardinal = require('..')
function inspect (obj) {
return console.log(util.inspect(obj, false, 5, false))
}
var file = path.join(__dirname, 'fixtures/foo.js')
, fileWithErrors = path.join(__dirname, 'fixtures/foo-with-errors.js')
test('supplying custom theme', function (t) {
cardinal.highlightFile(file, { theme: customTheme }, function (err, highlighted) {
t.equals(null, err, 'no error')
t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[96mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \n \u001b[32mvar\u001b[39m \u001b[96ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[96ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[31mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \n\u001b[33m}\u001b[39m\n')
t.end()
})
})
test('not supplying custom theme', function (t) {
cardinal.highlightFile(file, function (err, highlighted) {
t.equals(null, err, 'no error')
t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[37mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \n \u001b[32mvar\u001b[39m \u001b[37ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[37ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[91mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \n\u001b[33m}\u001b[39m\n')
t.end()
})
})
test('syntactically invalid code', function (t) {
cardinal.highlightFile(fileWithErrors, function (err, highlighted) {
t.equals(null, err, 'no error')
t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \n \u001b[32mvar\u001b[39m \u001b[37ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[37ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[91mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \n\u001b[33m}\u001b[39m\u001b[90m;\u001b[39m\n')
t.end()
})
})
test('non existing file', function (t) {
cardinal.highlightFile('./not/existing', function (err, highlighted) {
t.similar(err.message, /ENOENT. .*not.existing/)
t.end()
})
})
'use strict';
/*jshint asi: true*/
var test = require('tap').test
, util = require('util')
, fs = require('fs')
, path = require('path')
, customTheme = require('./fixtures/custom')
, cardinal = require('..')
function inspect (obj) {
return console.log(util.inspect(obj, false, 5, false))
}
var file = path.join(__dirname, 'fixtures/foo.js')
, fileWithErrors = path.join(__dirname, 'fixtures/foo-with-errors.js')
test('supplying custom theme', function (t) {
var highlighted = cardinal.highlightFileSync(file, { theme: customTheme });
t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[96mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \n \u001b[32mvar\u001b[39m \u001b[96ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[96ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[31mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \n\u001b[33m}\u001b[39m\n')
t.end()
})
test('not supplying custom theme', function (t) {
var highlighted = cardinal.highlightFileSync(file);
t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[37mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \n \u001b[32mvar\u001b[39m \u001b[37ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[37ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[91mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \n\u001b[33m}\u001b[39m\n')
t.end()
})
test('syntactically invalid code', function (t) {
var highlighted = cardinal.highlightFileSync(fileWithErrors);
t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \n \u001b[32mvar\u001b[39m \u001b[37ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[37ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[91mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \n\u001b[33m}\u001b[39m\u001b[90m;\u001b[39m\n')
t.end()
})
test('non existing file', function (t) {
try {
cardinal.highlightFileSync('./not/existing');
} catch (e) {
t.similar(e.message, /ENOENT. .*not.existing/)
t.end()
}
})
// Test Cases
// highlightDiff('@@ -25,22 +31,47 @@ function resolveTheme (config) { }')
'use strict';
/*jshint asi: true*/
var test = require('tap').test
, util = require('util')
, path = require('path')
, cardinal = require('..')
function inspect (obj) {
return console.log(util.inspect(obj, false, 5, false))
}
var file = path.join(__dirname, 'fixtures/json.json');
test('without custom theme', function (t) {
cardinal.highlightFile(file, function (err, highlighted) {
t.equals(null, err, 'no error');
t.equals(highlighted, '\u001b[33m{\u001b[39m\u001b[32m"foo"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"bar"\u001b[39m\u001b[32m,\u001b[39m\u001b[32m"baz"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"quux"\u001b[39m\u001b[32m,\u001b[39m\u001b[32m"bam"\u001b[39m\u001b[93m:\u001b[39m\u001b[90mnull\u001b[39m\u001b[33m}\u001b[39m');
t.end();
});
});
'use strict';
/*jshint asi: true*/
var test = require('tap').test
, util = require('util')
, path = require('path')
, cardinal = require('..')
function inspect (obj) {
return console.log(util.inspect(obj, false, 5, false))
}
var file = path.join(__dirname, 'fixtures/json.json');
test('without custom theme', function (t) {
var highlighted = cardinal.highlightFileSync(file);
t.equals(highlighted, '\u001b[33m{\u001b[39m\u001b[32m"foo"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"bar"\u001b[39m\u001b[32m,\u001b[39m\u001b[32m"baz"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"quux"\u001b[39m\u001b[32m,\u001b[39m\u001b[32m"bam"\u001b[39m\u001b[93m:\u001b[39m\u001b[90mnull\u001b[39m\u001b[33m}\u001b[39m');
t.end();
});
'use strict';
/*jshint asi: true*/
var test = require('tap').test
, util = require('util')
, customTheme = require('./fixtures/custom')
, cardinal = require('..')
function inspect (obj) {
return console.log(util.inspect(obj, false, 5, false))
}
var json = JSON.stringify({
foo: 'bar',
baz: 'quux',
bam: null
});
test('supplying custom theme', function (t) {
var highlighted = cardinal.highlight(json, { theme: customTheme });
t.equals(highlighted, '\u001b[33m{\u001b[39m\u001b[92m"foo"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"bar"\u001b[39m\u001b[32m,\u001b[39m\u001b[92m"baz"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"quux"\u001b[39m\u001b[32m,\u001b[39m\u001b[92m"bam"\u001b[39m\u001b[93m:\u001b[39m\u001b[90mnull\u001b[39m\u001b[33m}\u001b[39m')
t.end();
});
test('not supplying custom theme', function (t) {
var highlighted = cardinal.highlight(json);
t.equals(highlighted, '\u001b[33m{\u001b[39m\u001b[32m"foo"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"bar"\u001b[39m\u001b[32m,\u001b[39m\u001b[32m"baz"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"quux"\u001b[39m\u001b[32m,\u001b[39m\u001b[32m"bam"\u001b[39m\u001b[93m:\u001b[39m\u001b[90mnull\u001b[39m\u001b[33m}\u001b[39m')
t.end();
});
test('with the obsoleted json option (ignored)', function (t) {
var highlighted = cardinal.highlight(json, { json: true });
t.equals(highlighted, '\u001b[33m{\u001b[39m\u001b[32m"foo"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"bar"\u001b[39m\u001b[32m,\u001b[39m\u001b[32m"baz"\u001b[39m\u001b[93m:\u001b[39m\u001b[92m"quux"\u001b[39m\u001b[32m,\u001b[39m\u001b[32m"bam"\u001b[39m\u001b[93m:\u001b[39m\u001b[90mnull\u001b[39m\u001b[33m}\u001b[39m')
t.end();
});
'use strict';
/*jshint asi: true*/
var test = require('tap').test
, util = require('util')
, fs = require('fs')
, customTheme = require('./fixtures/custom')
, cardinal = require('..')
function inspect (obj) {
return console.log(util.inspect(obj, false, 5, false))
}
var code = 'function foo() { var a = 3; return a > 2 ? true : false; }'
, codeWithErrors = 'function () { var a = 3; return a > 2 ? true : false; }';
test('supplying custom theme', function (t) {
var highlighted = cardinal.highlight(code, { theme: customTheme });
t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[96mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \u001b[32mvar\u001b[39m \u001b[96ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[96ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[31mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \u001b[33m}\u001b[39m')
t.end()
})
test('not supplying custom theme', function (t) {
var highlighted = cardinal.highlight(code);
t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[37mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \u001b[32mvar\u001b[39m \u001b[37ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[37ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[91mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \u001b[33m}\u001b[39m')
t.end()
})
test('syntactically invalid code', function (t) {
var highlighted = cardinal.highlight(codeWithErrors);
t.equals(highlighted, '\u001b[94mfunction\u001b[39m \u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \u001b[32mvar\u001b[39m \u001b[37ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[37ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[91mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \u001b[33m}\u001b[39m')
t.end()
})
test('line numbers no firstline given', function (t) {
var highlighted = cardinal.highlight(code, { linenos: true });
t.equals(highlighted, '\u001b[90m1: \u001b[94mfunction\u001b[39m \u001b[37mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \u001b[32mvar\u001b[39m \u001b[37ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[37ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[91mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \u001b[33m}\u001b[39m')
t.end()
})
test('line numbers firstline 99', function (t) {
var highlighted = cardinal.highlight(code, { linenos: true, firstline: 99 });
t.equals(highlighted, '\u001b[90m99: \u001b[94mfunction\u001b[39m \u001b[37mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m \u001b[32mvar\u001b[39m \u001b[37ma\u001b[39m \u001b[93m=\u001b[39m \u001b[34m3\u001b[39m\u001b[90m;\u001b[39m \u001b[31mreturn\u001b[39m \u001b[37ma\u001b[39m \u001b[93m>\u001b[39m \u001b[34m2\u001b[39m \u001b[93m?\u001b[39m \u001b[91mtrue\u001b[39m \u001b[93m:\u001b[39m \u001b[91mfalse\u001b[39m\u001b[90m;\u001b[39m \u001b[33m}\u001b[39m')
t.end()
})
test('line numbers multi line no first line given', function (t) {
var multilineCode = '' +
function foo () {
return 1;
};
var highlighted = cardinal.highlight(multilineCode, { linenos: true });
t.equals(highlighted,'\u001b[90m1: \u001b[94mfunction\u001b[39m \u001b[37mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m\n\u001b[90m2: \u001b[31mreturn\u001b[39m \u001b[34m1\u001b[39m\u001b[90m;\u001b[39m\n\u001b[90m3: \u001b[33m}\u001b[39m')
t.end()
})
test('line numbers multi line first line 99', function (t) {
var multilineCode = '' +
function foo () {
return 1;
};
var highlighted = cardinal.highlight(multilineCode, { linenos: true, firstline: 99 });
t.equals(highlighted,'\u001b[90m 99: \u001b[94mfunction\u001b[39m \u001b[37mfoo\u001b[39m\u001b[90m(\u001b[39m\u001b[90m)\u001b[39m \u001b[33m{\u001b[39m\n\u001b[90m100: \u001b[31mreturn\u001b[39m \u001b[34m1\u001b[39m\u001b[90m;\u001b[39m\n\u001b[90m101: \u001b[33m}\u001b[39m')
t.end()
})
'use strict';
/*jshint asi: true*/
// applying esprima to a bunch of files of contained libraries as a smoke test
var test = require('tap').test
, path = require('path')
, fs = require('fs')
, readdirp = require('readdirp')
, cardinal = require('..')
, node_modules = path.join(__dirname, '..', 'node_modules')
, tapdir = path.join(node_modules, 'tap')
, redeyeddir = path.join(node_modules, 'redeyed')
test('tap', function (t) {
var invalidTapFiles = [
'async-map-ordered.js'
, 'prof.js'
]
readdirp({ root: tapdir, fileFilter: '*.js' })
.on('data', function (entry) {
if (~invalidTapFiles.indexOf(entry.name)) return
var code = fs.readFileSync(entry.fullPath, 'utf-8')
, result = cardinal.highlight(code);
t.assert(~result.indexOf('[32mvar\u001b[39m') || !(~result.indexOf('var ')), 'highlighted ' + entry.path)
})
.on('end', t.end.bind(t))
})
test('redeyed', function (t) {
readdirp({ root: redeyeddir, fileFilter: 'redeyed.js' })
.on('data', function (entry) {
var code = fs.readFileSync(entry.fullPath, 'utf-8')
, result = cardinal.highlight(code);
t.assert(~result.indexOf('[32mvar\u001b[39m') || !(~result.indexOf('var ')), 'highlighted ' + entry.path)
})
.on('end', t.end.bind(t))
})
/**
* This is a meaningless block jsdoc for a meaningless function.
* Joins two strings, separating them to appear on two lines.
*
* @name foo
* @function
* @param uno {String} first string
* @param dos {String} second string
* @return {String} result of the join
*/
module.exports = function foo (uno, dos) {
return uno + '\n' + dos;
}
var colors = require('ansicolors');
// Change the below definitions in order to tweak the color theme.
module.exports = {
'Boolean': {
// changed from default
'true' : colors.red
, 'false' : undefined
, _default : colors.brightRed
}
, 'Identifier': {
'undefined' : colors.brightBlack
, 'self' : colors.brightRed
, 'console' : colors.blue
, 'log' : colors.blue
, 'warn' : colors.red
, 'error' : colors.brightRed
//
// changed from default
, _default : colors.brightCyan
}
, 'Null': {
_default: colors.brightBlack
}
, 'Numeric': {
_default: colors.blue
}
, 'String': {
_default: colors.brightGreen
}
, 'Keyword': {
'break' : undefined
, 'case' : undefined
, 'catch' : colors.cyan
, 'continue' : undefined
, 'debugger' : undefined
, 'default' : undefined
, 'delete' : colors.red
, 'do' : undefined
, 'else' : undefined
, 'finally' : colors.cyan
, 'for' : undefined
, 'function' : undefined
, 'if' : undefined
, 'in' : undefined
, 'instanceof' : undefined
, 'new' : colors.red
, 'return' : colors.red
, 'switch' : undefined
, 'this' : colors.brightRed
, 'throw' : undefined
, 'try' : colors.cyan
, 'typeof' : undefined
, 'var' : colors.green
, 'void' : undefined
, 'while' : undefined
, 'with' : undefined
, _default : colors.brightBlue
}
, 'Punctuator': {
';': colors.brightBlack
, '.': colors.green
, ',': colors.green
, '{': colors.yellow
, '}': colors.yellow
, '(': colors.brightBlack
, ')': colors.brightBlack
, '[': colors.yellow
, ']': colors.yellow
, '<': undefined
, '>': undefined
, '+': undefined
, '-': undefined
, '*': undefined
, '%': undefined
, '&': undefined
, '|': undefined
, '^': undefined
, '!': undefined
, '~': undefined
, '?': undefined
, ':': undefined
, '=': undefined
, '<=': undefined
, '>=': undefined
, '==': undefined
, '!=': undefined
, '++': undefined
, '--': undefined
, '<<': undefined
, '>>': undefined
, '&&': undefined
, '||': undefined
, '+=': undefined
, '-=': undefined
, '*=': undefined
, '%=': undefined
, '&=': undefined
, '|=': undefined
, '^=': undefined
, '/=': undefined
, '===': undefined
, '!==': undefined
, '>>>': undefined
, '<<=': undefined
, '>>=': undefined
, '>>>=': undefined
, _default: colors.brightYellow
}
// line comment
, Line: {
_default: colors.brightBlack
}
/* block comment */
, Block: {
_default: colors.brightBlack
}
, _default: undefined
};
function () {
var a = 3; return a > 2 ? true : false;
};
function foo() {
var a = 3; return a > 2 ? true : false;
}
diff --git a/test/settings.js b/test/settings.js
index 7b28d66..642688f 100644
--- a/test/settings.js
+++ b/test/settings.js
@@ -1,14 +1,20 @@
'use strict';
/*jshint asi: true*/
-var test = require('tap').test
- , path = require('path')
- , fs = require('fs')
- , settings = require('../settings')
- , existsSync = fs.existsSync || path.existsSync
+var test = require('tap').test
+ , path = require('path')
+ , fs = require('fs')
, hideSemicolonsTheme = require('../themes/hide-semicolons')
, home = path.join(__dirname, 'fixtures', 'home')
, rcpath = path.join(home, '.cardinalrc')
+ , existsSync = fs.existsSync || path.existsSync
+ , settingsResolve = require.resolve('../settings')
+ , settings
+
+function setup () {
+ delete require.cache[settingsResolve]
+ settings = require(settingsResolve)
+}
function writerc(config) {
fs.writeFileSync(rcpath, JSON.stringify(config), 'utf-8')
@@ -25,22 +31,47 @@ function resolveTheme (config) {
return result;
}
+function getSettings (config) {
+ writerc(config)
+ var result = settings.getSettings(home)
+ removerc()
+ return result;
+}
+
if (!existsSync(home)) fs.mkdirSync(home);
test('no .cardinalrc in home', function (t) {
+ setup()
var theme = settings.resolveTheme(home)
t.equals(theme, undefined, 'resolves no theme')
t.end()
})
test('.cardinalrc with theme "hide-semicolons" in home', function (t) {
+ setup()
var theme = resolveTheme({ theme: "hide-semicolons" })
t.deepEquals(theme, hideSemicolonsTheme, 'resolves hide-semicolons theme')
t.end()
})
test('.cardinalrc with full path to "hide-semicolons.js" in home', function (t) {
+ setup()
var theme = resolveTheme({ theme: path.join(__dirname, '..', 'themes', 'hide-semicolons.js') })
t.deepEquals(theme, hideSemicolonsTheme, 'resolves hide-semicolons theme')
t.end()
})
+
+test('.cardinalrc with linenos: true', function (t) {
+ setup()
+ var opts = { linenos: true }
+ t.deepEquals(getSettings(opts), opts)
+ t.end()
+})
+
+test('.cardinalrc with linenos: true and theme', function (t) {
+ setup()
+ var opts = { linenos: true, theme: 'some theme' }
+ t.deepEquals(getSettings(opts), opts)
+ t.end()
+})
+
{"foo":"bar","baz":"quux","bam":null}
\ No newline at end of file
Index: grunt.js
===================================================================
--- grunt.js (revision 31200)
+++ grunt.js (working copy)
@@ -12,6 +12,7 @@
module.exports = function (grunt) {
+ console.log('hello world');
// Project configuration.
grunt.initConfig({
lint: {
@@ -19,10 +20,6 @@
'packages/services.web/{!(test)/**/,}*.js',
'packages/error/**/*.js'
],
- scripts: [
- 'grunt.js',
- 'db/**/*.js'
- ],
browser: [
'packages/web/server.js',
'packages/web/server/**/*.js',
'use strict';
/*jshint asi: true*/
var test = require('tap').test
, path = require('path')
, fs = require('fs')
, hideSemicolonsTheme = require('../themes/hide-semicolons')
, home = path.join(__dirname, 'fixtures', 'home')
, rcpath = path.join(home, '.cardinalrc')
, existsSync = fs.existsSync || path.existsSync
, settingsResolve = require.resolve('../settings')
, settings
function setup () {
delete require.cache[settingsResolve]
settings = require(settingsResolve)
}
function writerc(config) {
fs.writeFileSync(rcpath, JSON.stringify(config), 'utf-8')
}
function removerc () {
fs.unlinkSync(rcpath)
}
function resolveTheme (config) {
writerc(config)
var result = settings.resolveTheme(home)
removerc()
return result;
}
function getSettings (config) {
writerc(config)
var result = settings.getSettings(home)
removerc()
return result;
}
if (!existsSync(home)) fs.mkdirSync(home);
test('no .cardinalrc in home', function (t) {
setup()
var theme = settings.resolveTheme(home)
t.equals(theme, undefined, 'resolves no theme')
t.end()
})
test('.cardinalrc with theme "hide-semicolons" in home', function (t) {
setup()
var theme = resolveTheme({ theme: "hide-semicolons" })
t.deepEquals(theme, hideSemicolonsTheme, 'resolves hide-semicolons theme')
t.end()
})
test('.cardinalrc with full path to "hide-semicolons.js" in home', function (t) {
setup()
var theme = resolveTheme({ theme: path.join(__dirname, '..', 'themes', 'hide-semicolons.js') })
t.deepEquals(theme, hideSemicolonsTheme, 'resolves hide-semicolons theme')
t.end()
})
test('.cardinalrc with linenos: true', function (t) {
setup()
var opts = { linenos: true }
t.deepEquals(getSettings(opts), opts)
t.end()
})
test('.cardinalrc with linenos: true and theme', function (t) {
setup()
var opts = { linenos: true, theme: 'some theme' }
t.deepEquals(getSettings(opts), opts)
t.end()
})
'use strict';
/*jshint asi: true*/
var test = require('tap').test
, path = require('path')
, fs = require('fs')
, themesdir = path.join(__dirname, '..', 'themes')
, allFiles = fs.readdirSync(themesdir)
test('validate themes by requiring all of them', function (t) {
allFiles
.filter(function (file) { return path.extname(file) === '.js'; })
.forEach(function (theme) {
try {
t.ok(require(path.join(themesdir, theme)), theme + ' is valid')
} catch (e) {
t.fail('theme: ' + theme + ' is invalid! ' + e.message)
}
})
t.end()
})
# cardinal themes
These are the built in themes that come with cardinal.
You can create more themes by copying and then editing the [empty
theme](https://github.com/thlorenz/cardinal/blob/master/themes/empty.js) which is provided for that purpose.
The [hide semicolons theme](https://github.com/thlorenz/cardinal/blob/master/themes/hide-semicolons.js) has the added
benefit of making all semicolons invisible. This makes code more readable at times.
Find out how to change the theme used by cardinal [here](https://github.com/thlorenz/cardinal#theme).
# sharing themes
To add your theme to the cardinal built-in themes, follow the below steps:
1. fork the cardinal repository
2. add your theme to the themes folder and commit your changes
3. create a pull request
If you believe that your theme is better than the current default theme, let me know by creating an issue.
This will allow others to cast their vote. If enough people agree, your theme will be promoted to be the default.
## Contributed Themes
### tomorrow night
[![tomorrow-night](https://github.com/thlorenz/cardinal/raw/master/assets/theme-tomorrow-night.png)](https://github.com/thlorenz/cardinal/blob/master/themes/tomorrow-night.js)
*by [firede](https://github.com/firede)*
var colors = require('ansicolors');
// Change the below definitions in order to tweak the color theme.
module.exports = {
'Boolean': {
'true' : undefined
, 'false' : undefined
, _default : colors.brightRed
}
, 'Identifier': {
'undefined' : colors.brightBlack
, 'self' : colors.brightRed
, 'console' : colors.blue
, 'log' : colors.blue
, 'warn' : colors.red
, 'error' : colors.brightRed
, _default : colors.white
}
, 'Null': {
_default: colors.brightBlack
}
, 'Numeric': {
_default: colors.blue
}
, 'String': {
_default: function (s, info) {
var nextToken = info.tokens[info.tokenIndex + 1];
// show keys of object literals and json in different color
return (nextToken && nextToken.type === 'Punctuator' && nextToken.value === ':')
? colors.green(s)
: colors.brightGreen(s);
}
}
, 'Keyword': {
'break' : undefined
, 'case' : undefined
, 'catch' : colors.cyan
, 'class' : undefined
, 'const' : undefined
, 'continue' : undefined
, 'debugger' : undefined
, 'default' : undefined
, 'delete' : colors.red
, 'do' : undefined
, 'else' : undefined
, 'enum' : undefined
, 'export' : undefined
, 'extends' : undefined
, 'finally' : colors.cyan
, 'for' : undefined
, 'function' : undefined
, 'if' : undefined
, 'implements' : undefined
, 'import' : undefined
, 'in' : undefined
, 'instanceof' : undefined
, 'let' : undefined
, 'new' : colors.red
, 'package' : undefined
, 'private' : undefined
, 'protected' : undefined
, 'public' : undefined
, 'return' : colors.red
, 'static' : undefined
, 'super' : undefined
, 'switch' : undefined
, 'this' : colors.brightRed
, 'throw' : undefined
, 'try' : colors.cyan
, 'typeof' : undefined
, 'var' : colors.green
, 'void' : undefined
, 'while' : undefined
, 'with' : undefined
, 'yield' : undefined
, _default : colors.brightBlue
}
, 'Punctuator': {
';': colors.brightBlack
, '.': colors.green
, ',': colors.green
, '{': colors.yellow
, '}': colors.yellow
, '(': colors.brightBlack
, ')': colors.brightBlack
, '[': colors.yellow
, ']': colors.yellow
, '<': undefined
, '>': undefined
, '+': undefined
, '-': undefined
, '*': undefined
, '%': undefined
, '&': undefined
, '|': undefined
, '^': undefined
, '!': undefined
, '~': undefined
, '?': undefined
, ':': undefined
, '=': undefined
, '<=': undefined
, '>=': undefined
, '==': undefined
, '!=': undefined
, '++': undefined
, '--': undefined
, '<<': undefined
, '>>': undefined
, '&&': undefined
, '||': undefined
, '+=': undefined
, '-=': undefined
, '*=': undefined
, '%=': undefined
, '&=': undefined
, '|=': undefined
, '^=': undefined
, '/=': undefined
, '=>': undefined
, '===': undefined
, '!==': undefined
, '>>>': undefined
, '<<=': undefined
, '>>=': undefined
, '...': undefined
, '>>>=': undefined
, _default: colors.brightYellow
}
// line comment
, Line: {
_default: colors.brightBlack
}
/* block comment */
, Block: {
_default: colors.brightBlack
}
, _default: undefined
};
/*
* Copy this file and use it as a starting point for your custom cardinal color theme.
* Just fill in or change the entries for the tokens you want to color
* Keep in mind that more specific configurations override less specific ones.
*/
var colors = require('ansicolors');
// Change the below definitions in order to tweak the color theme.
module.exports = {
'Boolean': {
'true' : undefined
, 'false' : undefined
, _default : undefined
}
, 'Identifier': {
_default: undefined
}
, 'Null': {
_default: undefined
}
, 'Numeric': {
_default: undefined
}
, 'String': {
_default: undefined
}
, 'Keyword': {
'break' : undefined
, 'case' : undefined
, 'catch' : undefined
, 'class' : undefined
, 'const' : undefined
, 'continue' : undefined
, 'debugger' : undefined
, 'default' : undefined
, 'delete' : undefined
, 'do' : undefined
, 'else' : undefined
, 'enum' : undefined
, 'export' : undefined
, 'extends' : undefined
, 'finally' : undefined
, 'for' : undefined
, 'function' : undefined
, 'if' : undefined
, 'implements' : undefined
, 'import' : undefined
, 'in' : undefined
, 'instanceof' : undefined
, 'interface' : undefined
, 'let' : undefined
, 'new' : undefined
, 'package' : undefined
, 'private' : undefined
, 'protected' : undefined
, 'public' : undefined
, 'return' : undefined
, 'static' : undefined
, 'super' : undefined
, 'switch' : undefined
, 'this' : undefined
, 'throw' : undefined
, 'try' : undefined
, 'typeof' : undefined
, 'var' : undefined
, 'void' : undefined
, 'while' : undefined
, 'with' : undefined
, 'yield' : undefined
, _default : undefined
}
, 'Punctuator': {
';': undefined
, '.': undefined
, ',': undefined
, '{': undefined
, '}': undefined
, '(': undefined
, ')': undefined
, '[': undefined
, ']': undefined
, '<': undefined
, '>': undefined
, '+': undefined
, '-': undefined
, '*': undefined
, '%': undefined
, '&': undefined
, '|': undefined
, '^': undefined
, '!': undefined
, '~': undefined
, '?': undefined
, ':': undefined
, '=': undefined
, '<=': undefined
, '>=': undefined
, '==': undefined
, '!=': undefined
, '++': undefined
, '--': undefined
, '<<': undefined
, '>>': undefined
, '&&': undefined
, '||': undefined
, '+=': undefined
, '-=': undefined
, '*=': undefined
, '%=': undefined
, '&=': undefined
, '|=': undefined
, '^=': undefined
, '/=': undefined
, '=>': undefined
, '===': undefined
, '!==': undefined
, '>>>': undefined
, '<<=': undefined
, '>>=': undefined
, '...': undefined
, '>>>=': undefined
, _default: undefined
}
// line comment
, Line: {
_default: undefined
}
/* block comment */
, Block: {
_default: undefined
}
, _default: undefined
};
var colors = require('ansicolors');
// Change the below definitions in order to tweak the color theme.
module.exports = {
'Boolean': {
'true' : undefined
, 'false' : undefined
, _default : colors.brightRed
}
, 'Identifier': {
'undefined' : colors.brightBlack
, 'self' : colors.brightRed
, 'console' : colors.blue
, 'log' : colors.blue
, 'warn' : colors.red
, 'error' : colors.brightRed
, _default : colors.white
}
, 'Null': {
_default: colors.brightBlack
}
, 'Numeric': {
_default: colors.blue
}
, 'String': {
_default: function (s, info) {
var nextToken = info.tokens[info.tokenIndex + 1];
// show keys of object literals and json in different color
return (nextToken && nextToken.type === 'Punctuator' && nextToken.value === ':')
? colors.green(s)
: colors.brightGreen(s);
}
}
, 'Keyword': {
'break' : undefined
, 'case' : undefined
, 'catch' : colors.cyan
, 'class' : undefined
, 'const' : undefined
, 'continue' : undefined
, 'debugger' : undefined
, 'default' : undefined
, 'delete' : colors.red
, 'do' : undefined
, 'else' : undefined
, 'enum' : undefined
, 'export' : undefined
, 'extends' : undefined
, 'finally' : colors.cyan
, 'for' : undefined
, 'function' : undefined
, 'if' : undefined
, 'implements' : undefined
, 'import' : undefined
, 'in' : undefined
, 'instanceof' : undefined
, 'let' : undefined
, 'new' : colors.red
, 'package' : undefined
, 'private' : undefined
, 'protected' : undefined
, 'public' : undefined
, 'return' : colors.red
, 'static' : undefined
, 'super' : undefined
, 'switch' : undefined
, 'this' : colors.brightRed
, 'throw' : undefined
, 'try' : colors.cyan
, 'typeof' : undefined
, 'var' : colors.green
, 'void' : undefined
, 'while' : undefined
, 'with' : undefined
, 'yield' : undefined
, _default : colors.brightBlue
}
, 'Punctuator': {
// setting semicolon's color to the same as the terminal background makes it invisible
';': colors.black
, '.': colors.green
, ',': colors.green
, '{': colors.yellow
, '}': colors.yellow
, '(': colors.brightBlack
, ')': colors.brightBlack
, '[': colors.yellow
, ']': colors.yellow
, '<': undefined
, '>': undefined
, '+': undefined
, '-': undefined
, '*': undefined
, '%': undefined
, '&': undefined
, '|': undefined
, '^': undefined
, '!': undefined
, '~': undefined
, '?': undefined
, ':': undefined
, '=': undefined
, '<=': undefined
, '>=': undefined
, '==': undefined
, '!=': undefined
, '++': undefined
, '--': undefined
, '<<': undefined
, '>>': undefined
, '&&': undefined
, '||': undefined
, '+=': undefined
, '-=': undefined
, '*=': undefined
, '%=': undefined
, '&=': undefined
, '|=': undefined
, '^=': undefined
, '/=': undefined
, '=>': undefined
, '===': undefined
, '!==': undefined
, '>>>': undefined
, '<<=': undefined
, '>>=': undefined
, '...': undefined
, '>>>=': undefined
, _default: colors.brightYellow
}
// line comment
, Line: {
_default: colors.brightBlack
}
/* block comment */
, Block: {
_default: colors.brightBlack
}
, _default: undefined
};
var colors = require('ansicolors');
// mimics [jq](https://stedolan.github.io/jq/) highlighting for json files
// mainly in the fact that the keys are a clearly different color than the strings
// However improvements to this theme are highly welcome! :)
// Change the below definitions in order to tweak the color theme.
module.exports = {
'Boolean': {
'true' : undefined
, 'false' : undefined
, _default : colors.brightRed
}
, 'Identifier': {
'undefined' : colors.brightBlack
, 'self' : colors.brightRed
, 'console' : colors.blue
, 'log' : colors.blue
, 'warn' : colors.red
, 'error' : colors.brightRed
, _default : colors.white
}
, 'Null': {
_default: colors.brightBlack
}
, 'Numeric': {
_default: colors.blue
}
, 'String': {
_default: function (s, info) {
var nextToken = info.tokens[info.tokenIndex + 1];
// show keys of object literals and json in different color
return (nextToken && nextToken.type === 'Punctuator' && nextToken.value === ':')
? colors.brightBlue(s)
: colors.brightGreen(s);
}
}
, 'Keyword': {
'break' : undefined
, 'case' : undefined
, 'catch' : colors.cyan
, 'class' : undefined
, 'const' : undefined
, 'continue' : undefined
, 'debugger' : undefined
, 'default' : undefined
, 'delete' : colors.red
, 'do' : undefined
, 'else' : undefined
, 'enum' : undefined
, 'export' : undefined
, 'extends' : undefined
, 'finally' : colors.cyan
, 'for' : undefined
, 'function' : undefined
, 'if' : undefined
, 'implements' : undefined
, 'import' : undefined
, 'in' : undefined
, 'instanceof' : undefined
, 'let' : undefined
, 'new' : colors.red
, 'package' : undefined
, 'private' : undefined
, 'protected' : undefined
, 'public' : undefined
, 'return' : colors.red
, 'static' : undefined
, 'super' : undefined
, 'switch' : undefined
, 'this' : colors.brightRed
, 'throw' : undefined
, 'try' : colors.cyan
, 'typeof' : undefined
, 'var' : colors.green
, 'void' : undefined
, 'while' : undefined
, 'with' : undefined
, 'yield' : undefined
, _default : colors.brightBlue
}
, 'Punctuator': {
';': colors.brightBlack
, '.': colors.green
, ',': colors.green
, '{': colors.brightWhite
, '}': colors.brightWhite
, '(': colors.brightBlack
, ')': colors.brightBlack
, '[': colors.brightWhite
, ']': colors.brightWhite
, '<': undefined
, '>': undefined
, '+': undefined
, '-': undefined
, '*': undefined
, '%': undefined
, '&': undefined
, '|': undefined
, '^': undefined
, '!': undefined
, '~': undefined
, '?': undefined
, ':': undefined
, '=': undefined
, '<=': undefined
, '>=': undefined
, '==': undefined
, '!=': undefined
, '++': undefined
, '--': undefined
, '<<': undefined
, '>>': undefined
, '&&': undefined
, '||': undefined
, '+=': undefined
, '-=': undefined
, '*=': undefined
, '%=': undefined
, '&=': undefined
, '|=': undefined
, '^=': undefined
, '/=': undefined
, '=>': undefined
, '===': undefined
, '!==': undefined
, '>>>': undefined
, '<<=': undefined
, '>>=': undefined
, '...': undefined
, '>>>=': undefined
, _default: colors.brightYellow
}
// line comment
, Line: {
_default: colors.brightBlack
}
/* block comment */
, Block: {
_default: colors.brightBlack
}
, _default: undefined
};
var colors = require('ansicolors');
// Change the below definitions in order to tweak the color theme.
module.exports = {
'Boolean': {
'true' : undefined
, 'false' : undefined
, _default : colors.yellow
}
, 'Identifier': {
'undefined' : colors.yellow
, 'self' : colors.yellow
, 'type' : colors.yellow
, 'value' : colors.yellow
, 'console' : undefined
, 'log' : colors.blue
, 'warn' : colors.blue
, 'error' : colors.blue
, 'join' : colors.blue
, _default : function (s, info) {
var prevToken = info.tokens[info.tokenIndex - 1];
var nextToken = info.tokens[info.tokenIndex + 1];
return (nextToken
&& nextToken.type === 'Punctuator'
&& nextToken.value === '('
&& prevToken
&& prevToken.type === 'Keyword'
&& prevToken.value === 'function'
) ? colors.blue(s) : colors.white(s);
}
}
, 'Null': {
_default: colors.yellow
}
, 'Numeric': {
_default: colors.yellow
}
, 'String': {
_default: function (s, info) {
var nextToken = info.tokens[info.tokenIndex + 1];
// show keys of object literals and json in different color
return (nextToken && nextToken.type === 'Punctuator' && nextToken.value === ':')
? colors.green(s)
: colors.brightGreen(s);
}
}
, 'Keyword': {
'break' : colors.magenta
, 'case' : colors.magenta
, 'catch' : colors.magenta
, 'class' : undefined
, 'const' : undefined
, 'continue' : colors.magenta
, 'debugger' : colors.magenta
, 'default' : colors.magenta
, 'delete' : colors.red
, 'do' : colors.magenta
, 'else' : colors.magenta
, 'enum' : undefined
, 'export' : undefined
, 'extends' : undefined
, 'finally' : colors.magenta
, 'for' : colors.magenta
, 'function' : colors.magenta
, 'if' : colors.magenta
, 'implements' : undefined
, 'import' : undefined
, 'in' : colors.cyan
, 'instanceof' : colors.cyan
, 'let' : undefined
, 'new' : colors.cyan
, 'package' : undefined
, 'private' : undefined
, 'protected' : undefined
, 'public' : undefined
, 'return' : colors.magenta
, 'static' : undefined
, 'super' : undefined
, 'switch' : colors.magenta
, 'this' : colors.red
, 'throw' : colors.magenta
, 'try' : colors.magenta
, 'typeof' : colors.cyan
, 'var' : colors.magenta
, 'void' : colors.magenta
, 'while' : colors.magenta
, 'with' : colors.cyan
, 'yield' : undefined
, _default : colors.white
}
, 'Punctuator': {
';': colors.white
, '.': colors.white
, ',': colors.white
, '{': colors.white
, '}': colors.white
, '(': colors.white
, ')': colors.white
, '[': colors.white
, ']': colors.white
, '<': undefined
, '>': undefined
, '+': undefined
, '-': undefined
, '*': undefined
, '%': undefined
, '&': undefined
, '|': colors.white
, '^': undefined
, '!': undefined
, '~': undefined
, '?': colors.white
, ':': colors.white
, '=': undefined
, '<=': undefined
, '>=': undefined
, '==': undefined
, '!=': undefined
, '++': undefined
, '--': undefined
, '<<': undefined
, '>>': undefined
, '&&': undefined
, '||': undefined
, '+=': undefined
, '-=': undefined
, '*=': undefined
, '%=': undefined
, '&=': undefined
, '|=': undefined
, '^=': undefined
, '/=': undefined
, '=>': undefined
, '===': undefined
, '!==': undefined
, '>>>': undefined
, '<<=': undefined
, '>>=': undefined
, '...': undefined
, '>>>=': undefined
, _default: colors.cyan
}
// line comment
, Line: {
_default: colors.brightBlack
}
/* block comment */
, Block: {
_default: colors.brightBlack
}
, _default: undefined
};
var util = require('util');
module.exports.isPath = function (s) {
return (/[\/\\]/).test(s);
};
module.exports.inspect = function(obj, depth) {
console.log(util.inspect(obj, false, depth || 5, true));
};
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
/dist
/lib
################################################
############### .gitignore ##################
################################################
#
# This file is only relevant if you are using git.
#
# Files which match the splat patterns below will
# be ignored by git. This keeps random crap and
# sensitive credentials from being uploaded to
# your repository. It allows you to configure your
# app for your machine without accidentally
# committing settings which will smash the local
# settings of other developers on your team.
#
# Some reasonable defaults are included below,
# but, of course, you should modify/extend/prune
# to fit your needs!
################################################
################################################
# Local Configuration
#
# Explicitly ignore files which contain:
#
# 1. Sensitive information you'd rather not push to
# your git repository.
# e.g., your personal API keys or passwords.
#
# 2. Environment-specific configuration
# Basically, anything that would be annoying
# to have to change every time you do a
# `git pull`
# e.g., your local development database, or
# the S3 bucket you're using for file uploads
# development.
#
################################################
config/local.js
################################################
# Dependencies
#
# When releasing a production app, you may
# consider including your node_modules and
# bower_components directory in your git repo,
# but during development, its best to exclude it,
# since different developers may be working on
# different kernels, where dependencies would
# need to be recompiled anyway.
#
# More on that here about node_modules dir:
# http://www.futurealoof.com/posts/nodemodules-in-git.html
# (credit Mikeal Rogers, @mikeal)
#
# About bower_components dir, you can see this:
# http://addyosmani.com/blog/checking-in-front-end-dependencies/
# (credit Addy Osmani, @addyosmani)
#
################################################
node_modules
bower_components
################################################
# Sails.js / Waterline / Grunt
#
# Files generated by Sails and Grunt, or related
# tasks and adapters.
################################################
.tmp
dump.rdb
################################################
# Node.js / NPM
#
# Common files generated by Node, NPM, and the
# related ecosystem.
################################################
lib-cov
*.seed
*.log
*.out
*.pid
npm-debug.log
################################################
# Miscellaneous
#
# Common files generated by text editors,
# operating systems, file systems, etc.
################################################
*~
*#
.DS_STORE
.netbeans
nbproject
.idea
.node_history
# Coverage directory used by tools like istanbul
coverage
Mon Aug 14 2017 15:01:50 GMT+0800 (CST)
\ No newline at end of file
language: node_js
node_js:
- '0.10'
- '0.12'
- '4'
- '5'
- '6'
- '7'
- '8'
script:
- npm run test
env:
- CXX=g++-4.8
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- g++-4.8
code_climate:
repo_token: 4cee2f60edbf31acac6ddff823f0b93e2e9882c3e5c55130049e0fd878549f84
after_success:
- npm run coveralls
# DENQUE
[![Coverage Status](https://coveralls.io/repos/github/invertase/denque/badge.svg?branch=master)](https://coveralls.io/github/invertase/denque?branch=master)
[![build](https://travis-ci.org/invertase/denque.svg)](https://travis-ci.org/invertase/denque)
[![npm version](https://img.shields.io/npm/v/denque.svg)](https://www.npmjs.com/package/denque)
[![License](https://img.shields.io/npm/l/denque.svg)](/LICENSE)
[![Donate](https://img.shields.io/badge/Donate-Patreon-green.svg)](https://www.patreon.com/invertase)
Extremely fast and lightweight [double-ended queue](http://en.wikipedia.org/wiki/Double-ended_queue) implementation with zero dependencies.
Double-ended queues can also be used as a:
- [Stack](http://en.wikipedia.org/wiki/Stack_\(abstract_data_type\))
- [Queue](http://en.wikipedia.org/wiki/Queue_\(data_structure\))
This implementation is currently the fastest available, even faster than `double-ended-queue`, see the [benchmarks](#benchmarks)
Every queue operation is done at a constant `O(1)` - including random access from `.peekAt(index)`.
**Works on all node versions >= v0.10**
# Quick Start
npm install denque
```js
const Denque = require("denque");
const denque = new Denque([1,2,3,4]);
denque.shift(); // 1
denque.pop(); // 4
```
# API
- [`new Denque()`](#new-denque---denque)
- [`new Denque(Array items)`](#new-denquearray-items---denque)
- [`push(item)`](#pushitem---int)
- [`unshift(item)`](#unshiftitem---int)
- [`pop()`](#pop---dynamic)
- [`shift()`](#shift---dynamic)
- [`toArray()`](#toarray---array)
- [`peekBack()`](#peekback---dynamic)
- [`peekFront()`](#peekfront---dynamic)
- [`peekAt(int index)`](#peekAtint-index---dynamic)
- [`remove(int index, int count)`](#remove)
- [`removeOne(int index)`](#removeOne)
- [`splice(int index, int count, item1, item2, ...)`](#splice)
- [`isEmpty()`](#isempty---boolean)
- [`clear()`](#clear---void)
#### `new Denque()` -> `Denque`
Creates an empty double-ended queue with initial capacity of 4.
```js
var denque = new Denque();
denque.push(1, 2, 3);
denque.shift(); //1
denque.pop(); //3
```
<hr>
#### `new Denque(Array items)` -> `Denque`
Creates a double-ended queue from `items`.
```js
var denque = new Denque([1,2,3,4]);
denque.shift(); // 1
denque.pop(); // 4
```
<hr>
#### `push(item)` -> `int`
Push an item to the back of this queue. Returns the amount of items currently in the queue after the operation.
```js
var denque = new Denque();
denque.push(1);
denque.pop(); // 1
denque.push(2);
denque.push(3);
denque.shift(); // 2
denque.shift(); // 3
```
<hr>
#### `unshift(item)` -> `int`
Unshift an item to the front of this queue. Returns the amount of items currently in the queue after the operation.
```js
var denque = new Denque([2,3]);
denque.unshift(1);
denque.toString(); // "1,2,3"
denque.unshift(-2);
denque.toString(); // "-2,-1,0,1,2,3"
```
<hr>
#### `pop()` -> `dynamic`
Pop off the item at the back of this queue.
Note: The item will be removed from the queue. If you simply want to see what's at the back of the queue use [`peekBack()`](#peekback---dynamic) or [`.peekAt(-1)`](#peekAtint-index---dynamic).
If the queue is empty, `undefined` is returned. If you need to differentiate between `undefined` values in the queue and `pop()` return value -
check the queue `.length` before popping.
```js
var denque = new Denque([1,2,3]);
denque.pop(); // 3
denque.pop(); // 2
denque.pop(); // 1
denque.pop(); // undefined
```
**Aliases:** `removeBack`
<hr>
#### `shift()` -> `dynamic`
Shifts off the item at the front of this queue.
Note: The item will be removed from the queue. If you simply want to see what's at the front of the queue use [`peekFront()`](#peekfront---dynamic) or [`.peekAt(0)`](#peekAtint-index---dynamic).
If the queue is empty, `undefined` is returned. If you need to differentiate between `undefined` values in the queue and `shift()` return value -
check the queue `.length` before shifting.
```js
var denque = new Denque([1,2,3]);
denque.shift(); // 1
denque.shift(); // 2
denque.shift(); // 3
denque.shift(); // undefined
```
<hr>
#### `toArray()` -> `Array`
Returns the items in the queue as an array. Starting from the item in the front of the queue and ending to the item at the back of the queue.
```js
var denque = new Denque([1,2,3]);
denque.push(4);
denque.unshift(0);
denque.toArray(); // [0,1,2,3,4]
```
<hr>
#### `peekBack()` -> `dynamic`
Returns the item that is at the back of this queue without removing it.
If the queue is empty, `undefined` is returned.
```js
var denque = new Denque([1,2,3]);
denque.push(4);
denque.peekBack(); // 4
```
<hr>
#### `peekFront()` -> `dynamic`
Returns the item that is at the front of this queue without removing it.
If the queue is empty, `undefined` is returned.
```js
var denque = new Denque([1,2,3]);
denque.push(4);
denque.peekFront(); // 1
```
<hr>
#### `peekAt(int index)` -> `dynamic`
Returns the item that is at the given `index` of this queue without removing it.
The index is zero-based, so `.peekAt(0)` will return the item that is at the front, `.peekAt(1)` will return
the item that comes after and so on.
The index can be negative to read items at the back of the queue. `.peekAt(-1)` returns the item that is at the back of the queue,
`.peekAt(-2)` will return the item that comes before and so on.
Returns `undefined` if `index` is not a valid index into the queue.
```js
var denque = new Denque([1,2,3]);
denque.peekAt(0); //1
denque.peekAt(1); //2
denque.peekAt(2); //3
denque.peekAt(-1); // 3
denque.peekAt(-2); // 2
denque.peekAt(-3); // 1
```
**Note**: The implementation has O(1) random access using `.peekAt()`.
**Aliases:** `get`
<hr>
#### `remove(int index, int count)` -> `array`
Remove number of items from the specified index from the list.
Returns array of removed items.
Returns undefined if the list is empty.
```js
var denque = new Denque([1,2,3,4,5,6,7]);
denque.remove(0,3); //[1,2,3]
denque.remove(1,2); //[5,6]
var denque1 = new Denque([1,2,3,4,5,6,7]);
denque1.remove(4, 100); //[5,6,7]
```
### 100000 items in queue performance
denque.remove x 649,195 ops/sec ±1.33% (83 runs sampled)
native array splice x 54,461 ops/sec ±164.33% (11 runs sampled)
<hr>
#### `removeOne(int index)` -> `dynamic`
Remove and return the item at the specified index from the list.
Returns undefined if the list is empty.
```js
var denque = new Denque([1,2,3,4,5,6,7]);
denque.removeOne(4); // 5
denque.removeOne(3); // 4
denque1.removeOne(1); // 2
```
### 100000 items in queue performance
denque.removeOne x 487,168 ops/sec ±0.94% (85 runs sampled)
native array splice x 39,082 ops/sec ±0.87% (88 runs sampled)
<hr>
#### `splice(int index, int count, item1, item2, ...)` -> `array`
Native splice implementation.
Remove number of items from the specified index from the list and/or add new elements.
Returns array of removed items or empty array if count == 0.
Returns undefined if the list is empty.
```js
var denque = new Denque([1,2,3,4,5,6,7]);
denque.splice(denque.length, 0, 8, 9, 10); // []
denque.toArray() // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
denque.splice(3, 3, 44, 55, 66); // [4,5,6]
denque.splice(5,4, 666,667,668,669); // [ 66, 7, 8, 9 ]
denque.toArray() // [ 1, 2, 3, 44, 55, 666, 667, 668, 669, 10 ]
```
### 100000 items in queue performance
denque.splice x 178,198 ops/sec ±8.68% (61 runs sampled)
native array splice x 3,639 ops/sec ±4.39% (65 runs sampled)
<hr>
#### `isEmpty()` -> `boolean`
Return `true` if this queue is empty, `false` otherwise.
```js
var denque = new Denque();
denque.isEmpty(); // true
denque.push(1);
denque.isEmpty(); // false
```
<hr>
#### `clear()` -> `void`
Remove all items from this queue. Does not change the queue's capacity.
```js
var denque = new Denque([1,2,3]);
denque.toString(); // "1,2,3"
denque.clear();
denque.toString(); // ""
```
<hr>
## Benchmarks
#### Platform info:
```
Darwin 16.5.0 x64
Node.JS 8.1.2
V8 5.8.283.41
Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz × 8
```
#### 1000 items in queue (3x shift + 3x push ops per 'op')
(3x shift + 3x push ops per 'op')
denque x 26,076,776 ops/sec ±0.76% (90 runs sampled)
double-ended-queue x 15,347,410 ops/sec ±2.02% (87 runs sampled)
#### 2 million items in queue
(3x shift + 3x push ops per 'op')
denque x 23,267,668 ops/sec ±0.77% (88 runs sampled)
double-ended-queue x 14,990,494 ops/sec ±1.18% (88 runs sampled)
#### Splice
denque.splice x 288,034 ops/sec ±111.88% (76 runs sampled)
native array splice x 6,112 ops/sec ±6.80% (54 runs sampled)
#### Remove
denque.remove x 1,433,848 ops/sec ±0.54% (89 runs sampled)
native array splice x 17,843 ops/sec ±58.22% (10 runs sampled)
#### Remove One
denque.removeOne x 973,777 ops/sec ±1.19% (84 runs sampled)
native array splice x 70,916 ops/sec ±1.66% (84 runs sampled)
'use strict';
console.log("Platform info:");
var os = require("os");
var v8 = process.versions.v8;
var node = process.versions.node;
var plat = os.type() + " " + os.release() + " " + os.arch() + "\nNode.JS " + node + "\nV8 " + v8;
var cpus = os.cpus().map(function (cpu) {
return cpu.model;
}).reduce(function (o, model) {
if (!o[model]) o[model] = 0;
o[model]++;
return o;
}, {});
cpus = Object.keys(cpus).map(function (key) {
return key + " \u00d7 " + cpus[key];
}).join("\n");
console.log(plat + "\n" + cpus + "\n");
module.exports = {};
'use strict';
require('./print');
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite();
var Denque = require('./../');
var denque = new Denque();
var array = []
var l = 100000;
while (--l) {
denque.push(l);
array.push(l);
}
suite
.add('denque.remove', function () {
denque.remove(111, 10);
denque.push(11);
denque.push(11);
denque.push(11);
denque.push(11);
denque.push(11);
denque.push(11);
denque.push(11);
denque.push(11);
denque.push(11);
denque.push(11);
})
.add('native array splice', function () {
array.splice(111, 10);
denque.push(11);
denque.push(11);
denque.push(11);
denque.push(11);
denque.push(11);
denque.push(11);
denque.push(11);
denque.push(11);
denque.push(11);
denque.push(11);
})
.on('cycle', function (e) {
console.log('' + e.target);
})
.run();
'use strict';
require('./print');
var Denque = require('./../');
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite();
var denque = new Denque();
var array = []
var l = 5000;
while (--l) {
denque.push(l);
array.push(l);
}
suite
.add('denque.removeOne', function () {
var a = denque.removeOne(5);
var b = denque.removeOne(50);
var c = denque.removeOne(500);
denque.push(a);
denque.push(b);
denque.push(c);
})
.add('native array splice', function () {
var a = array.splice(5, 1)[0];
var b = array.splice(50, 1)[0];
var c = array.splice(500, 1)[0];
array.push(a);
array.push(b);
array.push(c);
})
.on('cycle', function (e) {
console.log('' + e.target);
})
.run();
'use strict';
require('./print');
var Benchmark = require('benchmark');
var Denque = require('./../');
var suite = new Benchmark.Suite();
var denque = new Denque();
var array = []
var l = 100000;
while (--l) {
denque.push(l);
array.push(l);
}
suite
.add('denque.splice', function () {
denque.splice(111, 1, 11, 12, 13, 14, 15, 16);
})
.add('native array splice', function () {
array.splice(111, 1, 11, 12, 13, 14, 15, 16);
})
.on('cycle', function (e) {
console.log('' + e.target);
})
.run();
'use strict';
require('./print');
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite();
var Denque = require('./../');
var DoubleEndedQueue = require('double-ended-queue');
var denque = new Denque();
var doubleEndedQueue = new DoubleEndedQueue();
var l = 1000;
while (--l) {
denque.push(l);
doubleEndedQueue.push(l);
}
suite
.add('denque', function () {
var a = denque.shift();
var b = denque.shift();
var c = denque.shift();
denque.push(a);
denque.push(b);
denque.push(c);
})
.add('double-ended-queue', function () {
var a = doubleEndedQueue.shift();
var b = doubleEndedQueue.shift();
var c = doubleEndedQueue.shift();
doubleEndedQueue.push(a);
doubleEndedQueue.push(b);
doubleEndedQueue.push(c);
})
.on('cycle', function (e) {
console.log('' + e.target);
})
.run();
'use strict';
require('./print');
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite();
var Denque = require('./../');
var DoubleEndedQueue = require('double-ended-queue');
var denque = new Denque();
var doubleEndedQueue = new DoubleEndedQueue();
var l = 2000000;
while (--l) {
denque.push(l);
doubleEndedQueue.push(l);
}
suite
.add('denque', function () {
var a = denque.shift();
var b = denque.shift();
var c = denque.shift();
denque.push(a);
denque.push(b);
denque.push(c);
})
.add('double-ended-queue', function () {
var a = doubleEndedQueue.shift();
var b = doubleEndedQueue.shift();
var c = doubleEndedQueue.shift();
doubleEndedQueue.push(a);
doubleEndedQueue.push(b);
doubleEndedQueue.push(c);
})
.on('cycle', function (e) {
console.log('' + e.target);
})
.run();
{
"name": "denque",
"version": "1.2.1",
"description": "The fastest javascript implementation of a double-ended queue. Maintains compatability with deque.",
"main": "index.js",
"engines": {
"node": ">=0.10"
},
"keywords": [
"data-structure",
"data-structures",
"queue",
"double",
"end",
"ended",
"deque",
"denque",
"double-ended-queue"
],
"scripts": {
"test": "istanbul cover --report lcov _mocha",
"coveralls": "cat ./coverage/lcov.info | coveralls",
"benchmark_thousand": "node benchmark/thousand",
"benchmark_2mil": "node benchmark/two_million",
"benchmark_splice": "node benchmark/splice",
"benchmark_remove": "node benchmark/remove",
"benchmark_removeOne": "node benchmark/removeOne"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Salakar/denque.git"
},
"author": {
"name": "Mike Diarmid",
"email": "mike.diarmid@teamfa.com",
"url": "http://github.com/Salakar/"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/Salakar/denque/issues"
},
"homepage": "https://github.com/Salakar/denque#readme",
"devDependencies": {
"benchmark": "^2.1.0",
"coveralls": "^2.11.9",
"double-ended-queue": "^2.1.0-0",
"istanbul": "^0.4.4",
"mocha": "^2.5.3"
},
"_from": "denque@1.2.1",
"_resolved": "http://registry.npm.taobao.org/denque/download/denque-1.2.1.tgz"
}
\ No newline at end of file
Mon Aug 14 2017 15:01:52 GMT+0800 (CST)
\ No newline at end of file
2016-09-03: Version 3.0.0
* Support ES2016 exponentiation expression (issue 1490)
* Support JSX syntax (issue 1467)
* Use the latest Unicode 8.0 (issue 1475)
* Add the support for syntax node delegate (issue 1435)
* Fix ESTree compatibility on meta property (issue 1338)
* Fix ESTree compatibility on default parameter value (issue 1081)
* Fix ESTree compatibility on try handler (issue 1030)
2016-08-23: Version 2.7.3
* Fix tokenizer confusion with a comment (issue 1493, 1516)
2016-02-02: Version 2.7.2
* Fix out-of-bound error location in an invalid string literal (issue 1457)
* Fix shorthand object destructuring defaults in variable declarations (issue 1459)
2015-12-10: Version 2.7.1
* Do not allow trailing comma in a variable declaration (issue 1360)
* Fix assignment to `let` in non-strict mode (issue 1376)
* Fix missing delegate property in YieldExpression (issue 1407)
2015-10-22: Version 2.7.0
* Fix the handling of semicolon in a break statement (issue 1044)
* Run the test suite with major web browsers (issue 1259, 1317)
* Allow `let` as an identifier in non-strict mode (issue 1289)
* Attach orphaned comments as `innerComments` (issue 1328)
* Add the support for token delegator (issue 1332)
2015-09-01: Version 2.6.0
* Properly allow or prohibit `let` in a binding identifier/pattern (issue 1048, 1098)
* Add sourceType field for Program node (issue 1159)
* Ensure that strict mode reserved word binding throw an error (issue 1171)
* Run the test suite with Node.js and IE 11 on Windows (issue 1294)
* Allow binding pattern with no initializer in a for statement (issue 1301)
2015-07-31: Version 2.5.0
* Run the test suite in a browser environment (issue 1004)
* Ensure a comma between imported default binding and named imports (issue 1046)
* Distinguish `yield` as a keyword vs an identifier (issue 1186)
* Support ES6 meta property `new.target` (issue 1203)
* Fix the syntax node for yield with expression (issue 1223)
* Fix the check of duplicated proto in property names (issue 1225)
* Fix ES6 Unicode escape in identifier name (issue 1229)
* Support ES6 IdentifierStart and IdentifierPart (issue 1232)
* Treat await as a reserved word when parsing as a module (issue 1234)
* Recognize identifier characters from Unicode SMP (issue 1244)
* Ensure that export and import can be followed by a comma (issue 1250)
* Fix yield operator precedence (issue 1262)
2015-07-01: Version 2.4.1
* Fix some cases of comment attachment (issue 1071, 1175)
* Fix the handling of destructuring in function arguments (issue 1193)
* Fix invalid ranges in assignment expression (issue 1201)
2015-06-26: Version 2.4.0
* Support ES6 for-of iteration (issue 1047)
* Support ES6 spread arguments (issue 1169)
* Minimize npm payload (issue 1191)
2015-06-16: Version 2.3.0
* Support ES6 generator (issue 1033)
* Improve parsing of regular expressions with `u` flag (issue 1179)
2015-04-17: Version 2.2.0
* Support ES6 import and export declarations (issue 1000)
* Fix line terminator before arrow not recognized as error (issue 1009)
* Support ES6 destructuring (issue 1045)
* Support ES6 template literal (issue 1074)
* Fix the handling of invalid/incomplete string escape sequences (issue 1106)
* Fix ES3 static member access restriction (issue 1120)
* Support for `super` in ES6 class (issue 1147)
2015-03-09: Version 2.1.0
* Support ES6 class (issue 1001)
* Support ES6 rest parameter (issue 1011)
* Expand the location of property getter, setter, and methods (issue 1029)
* Enable TryStatement transition to a single handler (issue 1031)
* Support ES6 computed property name (issue 1037)
* Tolerate unclosed block comment (issue 1041)
* Support ES6 lexical declaration (issue 1065)
2015-02-06: Version 2.0.0
* Support ES6 arrow function (issue 517)
* Support ES6 Unicode code point escape (issue 521)
* Improve the speed and accuracy of comment attachment (issue 522)
* Support ES6 default parameter (issue 519)
* Support ES6 regular expression flags (issue 557)
* Fix scanning of implicit octal literals (issue 565)
* Fix the handling of automatic semicolon insertion (issue 574)
* Support ES6 method definition (issue 620)
* Support ES6 octal integer literal (issue 621)
* Support ES6 binary integer literal (issue 622)
* Support ES6 object literal property value shorthand (issue 624)
2015-03-03: Version 1.2.5
* Fix scanning of implicit octal literals (issue 565)
2015-02-05: Version 1.2.4
* Fix parsing of LeftHandSideExpression in ForInStatement (issue 560)
* Fix the handling of automatic semicolon insertion (issue 574)
2015-01-18: Version 1.2.3
* Fix division by this (issue 616)
2014-05-18: Version 1.2.2
* Fix duplicated tokens when collecting comments (issue 537)
2014-05-04: Version 1.2.1
* Ensure that Program node may still have leading comments (issue 536)
2014-04-29: Version 1.2.0
* Fix semicolon handling for expression statement (issue 462, 533)
* Disallow escaped characters in regular expression flags (issue 503)
* Performance improvement for location tracking (issue 520)
* Improve the speed of comment attachment (issue 522)
2014-03-26: Version 1.1.1
* Fix token handling of forward slash after an array literal (issue 512)
2014-03-23: Version 1.1.0
* Optionally attach comments to the owning syntax nodes (issue 197)
* Simplify binary parsing with stack-based shift reduce (issue 352)
* Always include the raw source of literals (issue 376)
* Add optional input source information (issue 386)
* Tokenizer API for pure lexical scanning (issue 398)
* Improve the web site and its online demos (issue 337, 400, 404)
* Performance improvement for location tracking (issue 417, 424)
* Support HTML comment syntax (issue 451)
* Drop support for legacy browsers (issue 474)
2013-08-27: Version 1.0.4
* Minimize the payload for packages (issue 362)
* Fix missing cases on an empty switch statement (issue 436)
* Support escaped ] in regexp literal character classes (issue 442)
* Tolerate invalid left-hand side expression (issue 130)
2013-05-17: Version 1.0.3
* Variable declaration needs at least one declarator (issue 391)
* Fix benchmark's variance unit conversion (issue 397)
* IE < 9: \v should be treated as vertical tab (issue 405)
* Unary expressions should always have prefix: true (issue 418)
* Catch clause should only accept an identifier (issue 423)
* Tolerate setters without parameter (issue 426)
2012-11-02: Version 1.0.2
Improvement:
* Fix esvalidate JUnit output upon a syntax error (issue 374)
2012-10-28: Version 1.0.1
Improvements:
* esvalidate understands shebang in a Unix shell script (issue 361)
* esvalidate treats fatal parsing failure as an error (issue 361)
* Reduce Node.js package via .npmignore (issue 362)
2012-10-22: Version 1.0.0
Initial release.
Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[![NPM version](https://img.shields.io/npm/v/esprima.svg)](https://www.npmjs.com/package/esprima)
[![npm download](https://img.shields.io/npm/dm/esprima.svg)](https://www.npmjs.com/package/esprima)
[![Build Status](https://img.shields.io/travis/jquery/esprima/master.svg)](https://travis-ci.org/jquery/esprima)
[![Coverage Status](https://img.shields.io/codecov/c/github/jquery/esprima/master.svg)](https://codecov.io/github/jquery/esprima)
**Esprima** ([esprima.org](http://esprima.org), BSD license) is a high performance,
standard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm)
parser written in ECMAScript (also popularly known as
[JavaScript](https://en.wikipedia.org/wiki/JavaScript)).
Esprima is created and maintained by [Ariya Hidayat](https://twitter.com/ariyahidayat),
with the help of [many contributors](https://github.com/jquery/esprima/contributors).
### Features
- Full support for ECMAScript 2016 ([ECMA-262 7th Edition](http://www.ecma-international.org/publications/standards/Ecma-262.htm))
- Sensible [syntax tree format](https://github.com/estree/estree/blob/master/es5.md) as standardized by [ESTree project](https://github.com/estree/estree)
- Experimental support for [JSX](https://facebook.github.io/jsx/), a syntax extension for [React](https://facebook.github.io/react/)
- Optional tracking of syntax node location (index-based and line-column)
- [Heavily tested](http://esprima.org/test/ci.html) (~1300 [unit tests](https://github.com/jquery/esprima/tree/master/test/fixtures) with [full code coverage](https://codecov.io/github/jquery/esprima))
### API
Esprima can be used to perform [lexical analysis](https://en.wikipedia.org/wiki/Lexical_analysis) (tokenization) or [syntactic analysis](https://en.wikipedia.org/wiki/Parsing) (parsing) of a JavaScript programs.
A simple example:
```javascript
var esprima = require('esprima');
var code = 'const answer = 42';
var tokens = esprima.tokenize(code);
var ast = esprima.parse(code);
```
which gives a list of [tokens](https://en.wikipedia.org/wiki/Lexical_analysis#Token):
```javascript
[ { type: 'Keyword', value: 'const' },
{ type: 'Identifier', value: 'answer' },
{ type: 'Punctuator', value: '=' },
{ type: 'Numeric', value: '42' } ]
```
and an [abstract syntax tree](https://en.wikipedia.org/wiki/Abstract_syntax_tree):
```javascript
{ type: 'Program',
body:
[ { type: 'VariableDeclaration',
declarations: [Object],
kind: 'const' } ],
sourceType: 'script' }
```
#!/usr/bin/env node
/*
Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint sloppy:true node:true rhino:true */
var fs, esprima, fname, forceFile, content, options, syntax;
if (typeof require === 'function') {
fs = require('fs');
try {
esprima = require('esprima');
} catch (e) {
esprima = require('../');
}
} else if (typeof load === 'function') {
try {
load('esprima.js');
} catch (e) {
load('../esprima.js');
}
}
// Shims to Node.js objects when running under Rhino.
if (typeof console === 'undefined' && typeof process === 'undefined') {
console = { log: print };
fs = { readFileSync: readFile };
process = { argv: arguments, exit: quit };
process.argv.unshift('esparse.js');
process.argv.unshift('rhino');
}
function showUsage() {
console.log('Usage:');
console.log(' esparse [options] [file.js]');
console.log();
console.log('Available options:');
console.log();
console.log(' --comment Gather all line and block comments in an array');
console.log(' --loc Include line-column location info for each syntax node');
console.log(' --range Include index-based range for each syntax node');
console.log(' --raw Display the raw value of literals');
console.log(' --tokens List all tokens in an array');
console.log(' --tolerant Tolerate errors on a best-effort basis (experimental)');
console.log(' -v, --version Shows program version');
console.log();
process.exit(1);
}
options = {};
process.argv.splice(2).forEach(function (entry) {
if (forceFile || entry === '-' || entry.slice(0, 1) !== '-') {
if (typeof fname === 'string') {
console.log('Error: more than one input file.');
process.exit(1);
} else {
fname = entry;
}
} else if (entry === '-h' || entry === '--help') {
showUsage();
} else if (entry === '-v' || entry === '--version') {
console.log('ECMAScript Parser (using Esprima version', esprima.version, ')');
console.log();
process.exit(0);
} else if (entry === '--comment') {
options.comment = true;
} else if (entry === '--loc') {
options.loc = true;
} else if (entry === '--range') {
options.range = true;
} else if (entry === '--raw') {
options.raw = true;
} else if (entry === '--tokens') {
options.tokens = true;
} else if (entry === '--tolerant') {
options.tolerant = true;
} else if (entry === '--') {
forceFile = true;
} else {
console.log('Error: unknown option ' + entry + '.');
process.exit(1);
}
});
// Special handling for regular expression literal since we need to
// convert it to a string literal, otherwise it will be decoded
// as object "{}" and the regular expression would be lost.
function adjustRegexLiteral(key, value) {
if (key === 'value' && value instanceof RegExp) {
value = value.toString();
}
return value;
}
function run(content) {
syntax = esprima.parse(content, options);
console.log(JSON.stringify(syntax, adjustRegexLiteral, 4));
}
try {
if (fname && (fname !== '-' || forceFile)) {
run(fs.readFileSync(fname, 'utf-8'));
} else {
var content = '';
process.stdin.resume();
process.stdin.on('data', function(chunk) {
content += chunk;
});
process.stdin.on('end', function() {
run(content);
});
}
} catch (e) {
console.log('Error: ' + e.message);
process.exit(1);
}
#!/usr/bin/env node
/*
Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint sloppy:true plusplus:true node:true rhino:true */
/*global phantom:true */
var fs, system, esprima, options, fnames, forceFile, count;
if (typeof esprima === 'undefined') {
// PhantomJS can only require() relative files
if (typeof phantom === 'object') {
fs = require('fs');
system = require('system');
esprima = require('./esprima');
} else if (typeof require === 'function') {
fs = require('fs');
try {
esprima = require('esprima');
} catch (e) {
esprima = require('../');
}
} else if (typeof load === 'function') {
try {
load('esprima.js');
} catch (e) {
load('../esprima.js');
}
}
}
// Shims to Node.js objects when running under PhantomJS 1.7+.
if (typeof phantom === 'object') {
fs.readFileSync = fs.read;
process = {
argv: [].slice.call(system.args),
exit: phantom.exit,
on: function (evt, callback) {
callback();
}
};
process.argv.unshift('phantomjs');
}
// Shims to Node.js objects when running under Rhino.
if (typeof console === 'undefined' && typeof process === 'undefined') {
console = { log: print };
fs = { readFileSync: readFile };
process = {
argv: arguments,
exit: quit,
on: function (evt, callback) {
callback();
}
};
process.argv.unshift('esvalidate.js');
process.argv.unshift('rhino');
}
function showUsage() {
console.log('Usage:');
console.log(' esvalidate [options] [file.js...]');
console.log();
console.log('Available options:');
console.log();
console.log(' --format=type Set the report format, plain (default) or junit');
console.log(' -v, --version Print program version');
console.log();
process.exit(1);
}
options = {
format: 'plain'
};
fnames = [];
process.argv.splice(2).forEach(function (entry) {
if (forceFile || entry === '-' || entry.slice(0, 1) !== '-') {
fnames.push(entry);
} else if (entry === '-h' || entry === '--help') {
showUsage();
} else if (entry === '-v' || entry === '--version') {
console.log('ECMAScript Validator (using Esprima version', esprima.version, ')');
console.log();
process.exit(0);
} else if (entry.slice(0, 9) === '--format=') {
options.format = entry.slice(9);
if (options.format !== 'plain' && options.format !== 'junit') {
console.log('Error: unknown report format ' + options.format + '.');
process.exit(1);
}
} else if (entry === '--') {
forceFile = true;
} else {
console.log('Error: unknown option ' + entry + '.');
process.exit(1);
}
});
if (fnames.length === 0) {
fnames.push('');
}
if (options.format === 'junit') {
console.log('<?xml version="1.0" encoding="UTF-8"?>');
console.log('<testsuites>');
}
count = 0;
function run(fname, content) {
var timestamp, syntax, name;
try {
if (typeof content !== 'string') {
throw content;
}
if (content[0] === '#' && content[1] === '!') {
content = '//' + content.substr(2, content.length);
}
timestamp = Date.now();
syntax = esprima.parse(content, { tolerant: true });
if (options.format === 'junit') {
name = fname;
if (name.lastIndexOf('/') >= 0) {
name = name.slice(name.lastIndexOf('/') + 1);
}
console.log('<testsuite name="' + fname + '" errors="0" ' +
' failures="' + syntax.errors.length + '" ' +
' tests="' + syntax.errors.length + '" ' +
' time="' + Math.round((Date.now() - timestamp) / 1000) +
'">');
syntax.errors.forEach(function (error) {
var msg = error.message;
msg = msg.replace(/^Line\ [0-9]*\:\ /, '');
console.log(' <testcase name="Line ' + error.lineNumber + ': ' + msg + '" ' +
' time="0">');
console.log(' <error type="SyntaxError" message="' + error.message + '">' +
error.message + '(' + name + ':' + error.lineNumber + ')' +
'</error>');
console.log(' </testcase>');
});
console.log('</testsuite>');
} else if (options.format === 'plain') {
syntax.errors.forEach(function (error) {
var msg = error.message;
msg = msg.replace(/^Line\ [0-9]*\:\ /, '');
msg = fname + ':' + error.lineNumber + ': ' + msg;
console.log(msg);
++count;
});
}
} catch (e) {
++count;
if (options.format === 'junit') {
console.log('<testsuite name="' + fname + '" errors="1" failures="0" tests="1" ' +
' time="' + Math.round((Date.now() - timestamp) / 1000) + '">');
console.log(' <testcase name="' + e.message + '" ' + ' time="0">');
console.log(' <error type="ParseError" message="' + e.message + '">' +
e.message + '(' + fname + ((e.lineNumber) ? ':' + e.lineNumber : '') +
')</error>');
console.log(' </testcase>');
console.log('</testsuite>');
} else {
console.log('Error: ' + e.message);
}
}
}
fnames.forEach(function (fname) {
var content = '';
try {
if (fname && (fname !== '-' || forceFile)) {
content = fs.readFileSync(fname, 'utf-8');
} else {
fname = '';
process.stdin.resume();
process.stdin.on('data', function(chunk) {
content += chunk;
});
process.stdin.on('end', function() {
run(fname, content);
});
return;
}
} catch (e) {
content = e;
}
run(fname, content);
});
process.on('exit', function () {
if (options.format === 'junit') {
console.log('</testsuites>');
}
if (count > 0) {
process.exit(1);
}
if (count === 0 && typeof phantom === 'object') {
process.exit(0);
}
});
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "esprima",
"description": "ECMAScript parsing infrastructure for multipurpose analysis",
"homepage": "http://esprima.org",
"main": "dist/esprima.js",
"bin": {
"esparse": "./bin/esparse.js",
"esvalidate": "./bin/esvalidate.js"
},
"version": "3.0.0",
"files": [
"bin",
"dist/esprima.js"
],
"engines": {
"node": ">=0.10.0"
},
"author": {
"name": "Ariya Hidayat",
"email": "ariya.hidayat@gmail.com"
},
"maintainers": [
{
"name": "Ariya Hidayat",
"email": "ariya.hidayat@gmail.com",
"web": "http://ariya.ofilabs.com"
}
],
"repository": {
"type": "git",
"url": "https://github.com/jquery/esprima.git"
},
"bugs": {
"url": "https://github.com/jquery/esprima/issues"
},
"license": "BSD-2-Clause",
"devDependencies": {
"codecov.io": "~0.1.6",
"escomplex-js": "1.2.0",
"everything.js": "~1.0.3",
"glob": "~7.0.0",
"istanbul": "~0.4.0",
"jscs": "~3.0.3",
"json-diff": "~0.3.1",
"karma": "~1.2.0",
"karma-chrome-launcher": "~2.0.0",
"karma-detect-browsers": "~2.1.0",
"karma-firefox-launcher": "~1.0.0",
"karma-ie-launcher": "~1.0.0",
"karma-mocha": "~1.1.1",
"karma-safari-launcher": "~1.0.0",
"karma-sauce-launcher": "~1.0.0",
"lodash": "~3.10.1",
"mocha": "~3.0.2",
"node-tick-processor": "~0.0.2",
"regenerate": "~1.3.1",
"temp": "~0.8.3",
"tslint": "~3.15.1",
"typescript": "~1.8.10",
"typescript-formatter": "~1.2.0",
"unicode-8.0.0": "~0.7.0",
"webpack": "~1.13.2"
},
"keywords": [
"ast",
"ecmascript",
"esprima",
"javascript",
"parser",
"syntax"
],
"scripts": {
"check-version": "node test/check-version.js",
"tslint": "tslint src/*.ts",
"code-style": "tsfmt --verify src/*.ts && jscs -p crockford test/*.js",
"format-code": "tsfmt -r src/*.ts",
"complexity": "node test/check-complexity.js",
"static-analysis": "npm run check-version && npm run tslint && npm run code-style && npm run complexity",
"hostile-env-tests": "node test/hostile-environment-tests.js",
"unit-tests": "node test/unit-tests.js",
"api-tests": "mocha -R dot test/api-tests.js",
"grammar-tests": "node test/grammar-tests.js",
"regression-tests": "node test/regression-tests.js",
"all-tests": "npm run generate-fixtures && npm run unit-tests && npm run api-tests && npm run grammar-tests && npm run regression-tests && npm run hostile-env-tests",
"generate-fixtures": "node tools/generate-fixtures.js",
"browser-tests": "npm run compile && npm run generate-fixtures && cd test && karma start --single-run",
"saucelabs-evergreen": "cd test && karma start saucelabs-evergreen.conf.js",
"saucelabs-safari": "cd test && karma start saucelabs-safari.conf.js",
"saucelabs-ie": "cd test && karma start saucelabs-ie.conf.js",
"analyze-coverage": "istanbul cover test/unit-tests.js",
"check-coverage": "istanbul check-coverage --statement 100 --branch 100 --function 100",
"dynamic-analysis": "npm run analyze-coverage && npm run check-coverage",
"compile": "tsc -p src/ && webpack && node tools/fixupbundle.js",
"test": "npm run compile && npm run all-tests && npm run static-analysis && npm run dynamic-analysis",
"prepublish": "npm run compile",
"profile": "node --prof test/profile.js && mv isolate*.log v8.log && node-tick-processor",
"benchmark-parser": "node -expose_gc test/benchmark-parser.js",
"benchmark-tokenizer": "node --expose_gc test/benchmark-tokenizer.js",
"benchmark": "npm run benchmark-parser && npm run benchmark-tokenizer",
"codecov": "istanbul report cobertura && codecov < ./coverage/cobertura-coverage.xml",
"downstream": "node test/downstream.js",
"travis": "npm test",
"circleci": "npm test && npm run codecov && npm run downstream",
"appveyor": "npm run compile && npm run all-tests && npm run browser-tests",
"droneio": "npm test && npm run saucelabs-evergreen && npm run saucelabs-ie && npm run saucelabs-safari",
"generate-regex": "node tools/generate-identifier-regex.js",
"generate-xhtml-entities": "node tools/generate-xhtml-entities.js"
},
"_from": "esprima@3.0.0",
"_resolved": "http://registry.npm.taobao.org/esprima/download/esprima-3.0.0.tgz"
}
\ No newline at end of file
*~
*sublime-*
generation
test
wiki
coverage
Mon Aug 14 2017 15:01:51 GMT+0800 (CST)
\ No newline at end of file
sudo: false
language: node_js
node_js:
- "0.10"
- "0.11"
- "0.12"
- "iojs"
- "4"
- "6"
- "8"
- "node"
env:
- CXX=g++-4.8
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- gcc-4.8
- g++-4.8
# 0.4.18 / 2017-06-13
* Fixed CESU-8 regression in Node v8.
# 0.4.17 / 2017-04-22
* Updated typescript definition file to support Angular 2 AoT mode (#153 by @larssn)
# 0.4.16 / 2017-04-22
* Added support for React Native (#150)
* Changed iso8859-1 encoding to usine internal 'binary' encoding, as it's the same thing (#147 by @mscdex)
* Fixed typo in Readme (#138 by @jiangzhuo)
* Fixed build for Node v6.10+ by making correct version comparison
* Added a warning if iconv-lite is loaded not as utf-8 (see #142)
# 0.4.15 / 2016-11-21
* Fixed typescript type definition (#137)
# 0.4.14 / 2016-11-20
* Preparation for v1.0
* Added Node v6 and latest Node versions to Travis CI test rig
* Deprecated Node v0.8 support
* Typescript typings (@larssn)
* Fix encoding of Euro character in GB 18030 (inspired by @lygstate)
* Add ms prefix to dbcs windows encodings (@rokoroku)
# 0.4.13 / 2015-10-01
* Fix silly mistake in deprecation notice.
# 0.4.12 / 2015-09-26
* Node v4 support:
* Added CESU-8 decoding (#106)
* Added deprecation notice for `extendNodeEncodings`
* Added Travis tests for Node v4 and io.js latest (#105 by @Mithgol)
# 0.4.11 / 2015-07-03
* Added CESU-8 encoding.
# 0.4.10 / 2015-05-26
* Changed UTF-16 endianness heuristic to take into account any ASCII chars, not
just spaces. This should minimize the importance of "default" endianness.
# 0.4.9 / 2015-05-24
* Streamlined BOM handling: strip BOM by default, add BOM when encoding if
addBOM: true. Added docs to Readme.
* UTF16 now uses UTF16-LE by default.
* Fixed minor issue with big5 encoding.
* Added io.js testing on Travis; updated node-iconv version to test against.
Now we just skip testing SBCS encodings that node-iconv doesn't support.
* (internal refactoring) Updated codec interface to use classes.
* Use strict mode in all files.
# 0.4.8 / 2015-04-14
* added alias UNICODE-1-1-UTF-7 for UTF-7 encoding (#94)
# 0.4.7 / 2015-02-05
* stop official support of Node.js v0.8. Should still work, but no guarantees.
reason: Packages needed for testing are hard to get on Travis CI.
* work in environment where Object.prototype is monkey patched with enumerable
props (#89).
# 0.4.6 / 2015-01-12
* fix rare aliases of single-byte encodings (thanks @mscdex)
* double the timeout for dbcs tests to make them less flaky on travis
# 0.4.5 / 2014-11-20
* fix windows-31j and x-sjis encoding support (@nleush)
* minor fix: undefined variable reference when internal error happens
# 0.4.4 / 2014-07-16
* added encodings UTF-7 (RFC2152) and UTF-7-IMAP (RFC3501 Section 5.1.3)
* fixed streaming base64 encoding
# 0.4.3 / 2014-06-14
* added encodings UTF-16BE and UTF-16 with BOM
# 0.4.2 / 2014-06-12
* don't throw exception if `extendNodeEncodings()` is called more than once
# 0.4.1 / 2014-06-11
* codepage 808 added
# 0.4.0 / 2014-06-10
* code is rewritten from scratch
* all widespread encodings are supported
* streaming interface added
* browserify compatibility added
* (optional) extend core primitive encodings to make usage even simpler
* moved from vows to mocha as the testing framework
Copyright (c) 2011 Alexander Shtuchkin
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## Pure JS character encoding conversion [![Build Status](https://travis-ci.org/ashtuchkin/iconv-lite.svg?branch=master)](https://travis-ci.org/ashtuchkin/iconv-lite)
* Doesn't need native code compilation. Works on Windows and in sandboxed environments like [Cloud9](http://c9.io).
* Used in popular projects like [Express.js (body_parser)](https://github.com/expressjs/body-parser),
[Grunt](http://gruntjs.com/), [Nodemailer](http://www.nodemailer.com/), [Yeoman](http://yeoman.io/) and others.
* Faster than [node-iconv](https://github.com/bnoordhuis/node-iconv) (see below for performance comparison).
* Intuitive encode/decode API
* Streaming support for Node v0.10+
* [Deprecated] Can extend Node.js primitives (buffers, streams) to support all iconv-lite encodings.
* In-browser usage via [Browserify](https://github.com/substack/node-browserify) (~180k gzip compressed with Buffer shim included).
* Typescript [type definition file](https://github.com/ashtuchkin/iconv-lite/blob/master/lib/index.d.ts) included.
* React Native is supported (need to explicitly `npm install` two more modules: `buffer` and `stream`).
* License: MIT.
[![NPM Stats](https://nodei.co/npm/iconv-lite.png?downloads=true&downloadRank=true)](https://npmjs.org/packages/iconv-lite/)
## Usage
### Basic API
```javascript
var iconv = require('iconv-lite');
// Convert from an encoded buffer to js string.
str = iconv.decode(new Buffer([0x68, 0x65, 0x6c, 0x6c, 0x6f]), 'win1251');
// Convert from js string to an encoded buffer.
buf = iconv.encode("Sample input string", 'win1251');
// Check if encoding is supported
iconv.encodingExists("us-ascii")
```
### Streaming API (Node v0.10+)
```javascript
// Decode stream (from binary stream to js strings)
http.createServer(function(req, res) {
var converterStream = iconv.decodeStream('win1251');
req.pipe(converterStream);
converterStream.on('data', function(str) {
console.log(str); // Do something with decoded strings, chunk-by-chunk.
});
});
// Convert encoding streaming example
fs.createReadStream('file-in-win1251.txt')
.pipe(iconv.decodeStream('win1251'))
.pipe(iconv.encodeStream('ucs2'))
.pipe(fs.createWriteStream('file-in-ucs2.txt'));
// Sugar: all encode/decode streams have .collect(cb) method to accumulate data.
http.createServer(function(req, res) {
req.pipe(iconv.decodeStream('win1251')).collect(function(err, body) {
assert(typeof body == 'string');
console.log(body); // full request body string
});
});
```
### [Deprecated] Extend Node.js own encodings
> NOTE: This doesn't work on latest Node versions. See [details](https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility).
```javascript
// After this call all Node basic primitives will understand iconv-lite encodings.
iconv.extendNodeEncodings();
// Examples:
buf = new Buffer(str, 'win1251');
buf.write(str, 'gbk');
str = buf.toString('latin1');
assert(Buffer.isEncoding('iso-8859-15'));
Buffer.byteLength(str, 'us-ascii');
http.createServer(function(req, res) {
req.setEncoding('big5');
req.collect(function(err, body) {
console.log(body);
});
});
fs.createReadStream("file.txt", "shift_jis");
// External modules are also supported (if they use Node primitives, which they probably do).
request = require('request');
request({
url: "http://github.com/",
encoding: "cp932"
});
// To remove extensions
iconv.undoExtendNodeEncodings();
```
## Supported encodings
* All node.js native encodings: utf8, ucs2 / utf16-le, ascii, binary, base64, hex.
* Additional unicode encodings: utf16, utf16-be, utf-7, utf-7-imap.
* All widespread singlebyte encodings: Windows 125x family, ISO-8859 family,
IBM/DOS codepages, Macintosh family, KOI8 family, all others supported by iconv library.
Aliases like 'latin1', 'us-ascii' also supported.
* All widespread multibyte encodings: CP932, CP936, CP949, CP950, GB2312, GBK, GB18030, Big5, Shift_JIS, EUC-JP.
See [all supported encodings on wiki](https://github.com/ashtuchkin/iconv-lite/wiki/Supported-Encodings).
Most singlebyte encodings are generated automatically from [node-iconv](https://github.com/bnoordhuis/node-iconv). Thank you Ben Noordhuis and libiconv authors!
Multibyte encodings are generated from [Unicode.org mappings](http://www.unicode.org/Public/MAPPINGS/) and [WHATWG Encoding Standard mappings](http://encoding.spec.whatwg.org/). Thank you, respective authors!
## Encoding/decoding speed
Comparison with node-iconv module (1000x256kb, on MacBook Pro, Core i5/2.6 GHz, Node v0.12.0).
Note: your results may vary, so please always check on your hardware.
operation iconv@2.1.4 iconv-lite@0.4.7
----------------------------------------------------------
encode('win1251') ~96 Mb/s ~320 Mb/s
decode('win1251') ~95 Mb/s ~246 Mb/s
## BOM handling
* Decoding: BOM is stripped by default, unless overridden by passing `stripBOM: false` in options
(f.ex. `iconv.decode(buf, enc, {stripBOM: false})`).
A callback might also be given as a `stripBOM` parameter - it'll be called if BOM character was actually found.
* If you want to detect UTF-8 BOM when decoding other encodings, use [node-autodetect-decoder-stream](https://github.com/danielgindi/node-autodetect-decoder-stream) module.
* Encoding: No BOM added, unless overridden by `addBOM: true` option.
## UTF-16 Encodings
This library supports UTF-16LE, UTF-16BE and UTF-16 encodings. First two are straightforward, but UTF-16 is trying to be
smart about endianness in the following ways:
* Decoding: uses BOM and 'spaces heuristic' to determine input endianness. Default is UTF-16LE, but can be
overridden with `defaultEncoding: 'utf-16be'` option. Strips BOM unless `stripBOM: false`.
* Encoding: uses UTF-16LE and writes BOM by default. Use `addBOM: false` to override.
## Other notes
When decoding, be sure to supply a Buffer to decode() method, otherwise [bad things usually happen](https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding).
Untranslatable characters are set to � or ?. No transliteration is currently supported.
Node versions 0.10.31 and 0.11.13 are buggy, don't use them (see #65, #77).
## Testing
```bash
$ git clone git@github.com:ashtuchkin/iconv-lite.git
$ cd iconv-lite
$ npm install
$ npm test
$ # To view performance:
$ node test/performance.js
$ # To view test coverage:
$ npm run coverage
$ open coverage/lcov-report/index.html
```
## Adoption
[![NPM](https://nodei.co/npm-dl/iconv-lite.png)](https://nodei.co/npm/iconv-lite/)
[![Codeship Status for ashtuchkin/iconv-lite](https://www.codeship.com/projects/81670840-fa72-0131-4520-4a01a6c01acc/status)](https://www.codeship.com/projects/29053)
"use strict";
// Description of supported double byte encodings and aliases.
// Tables are not require()-d until they are needed to speed up library load.
// require()-s are direct to support Browserify.
module.exports = {
// == Japanese/ShiftJIS ====================================================
// All japanese encodings are based on JIS X set of standards:
// JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF.
// JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes.
// Has several variations in 1978, 1983, 1990 and 1997.
// JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead.
// JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233.
// 2 planes, first is superset of 0208, second - revised 0212.
// Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx)
// Byte encodings are:
// * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte
// encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC.
// Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI.
// * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes.
// 0x00-0x7F - lower part of 0201
// 0x8E, 0xA1-0xDF - upper part of 0201
// (0xA1-0xFE)x2 - 0208 plane (94x94).
// 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94).
// * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon.
// Used as-is in ISO2022 family.
// * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII,
// 0201-1976 Roman, 0208-1978, 0208-1983.
// * ISO2022-JP-1: Adds esc seq for 0212-1990.
// * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7.
// * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2.
// * ISO2022-JP-2004: Adds 0213-2004 Plane 1.
//
// After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes.
//
// Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html
'shiftjis': {
type: '_dbcs',
table: function() { return require('./tables/shiftjis.json') },
encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
encodeSkipVals: [{from: 0xED40, to: 0xF940}],
},
'csshiftjis': 'shiftjis',
'mskanji': 'shiftjis',
'sjis': 'shiftjis',
'windows31j': 'shiftjis',
'ms31j': 'shiftjis',
'xsjis': 'shiftjis',
'windows932': 'shiftjis',
'ms932': 'shiftjis',
'932': 'shiftjis',
'cp932': 'shiftjis',
'eucjp': {
type: '_dbcs',
table: function() { return require('./tables/eucjp.json') },
encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
},
// TODO: KDDI extension to Shift_JIS
// TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes.
// TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars.
// == Chinese/GBK ==========================================================
// http://en.wikipedia.org/wiki/GBK
// We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder
// Oldest GB2312 (1981, ~7600 chars) is a subset of CP936
'gb2312': 'cp936',
'gb231280': 'cp936',
'gb23121980': 'cp936',
'csgb2312': 'cp936',
'csiso58gb231280': 'cp936',
'euccn': 'cp936',
// Microsoft's CP936 is a subset and approximation of GBK.
'windows936': 'cp936',
'ms936': 'cp936',
'936': 'cp936',
'cp936': {
type: '_dbcs',
table: function() { return require('./tables/cp936.json') },
},
// GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other.
'gbk': {
type: '_dbcs',
table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) },
},
'xgbk': 'gbk',
'isoir58': 'gbk',
// GB18030 is an algorithmic extension of GBK.
// Main source: https://www.w3.org/TR/encoding/#gbk-encoder
// http://icu-project.org/docs/papers/gb18030.html
// http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml
// http://www.khngai.com/chinese/charmap/tblgbk.php?page=0
'gb18030': {
type: '_dbcs',
table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) },
gb18030: function() { return require('./tables/gb18030-ranges.json') },
encodeSkipVals: [0x80],
encodeAdd: {'€': 0xA2E3},
},
'chinese': 'gb18030',
// == Korean ===============================================================
// EUC-KR, KS_C_5601 and KS X 1001 are exactly the same.
'windows949': 'cp949',
'ms949': 'cp949',
'949': 'cp949',
'cp949': {
type: '_dbcs',
table: function() { return require('./tables/cp949.json') },
},
'cseuckr': 'cp949',
'csksc56011987': 'cp949',
'euckr': 'cp949',
'isoir149': 'cp949',
'korean': 'cp949',
'ksc56011987': 'cp949',
'ksc56011989': 'cp949',
'ksc5601': 'cp949',
// == Big5/Taiwan/Hong Kong ================================================
// There are lots of tables for Big5 and cp950. Please see the following links for history:
// http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html
// Variations, in roughly number of defined chars:
// * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT
// * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/
// * Big5-2003 (Taiwan standard) almost superset of cp950.
// * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers.
// * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard.
// many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years.
// Plus, it has 4 combining sequences.
// Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299
// because big5-hkscs is the only encoding to include astral characters in non-algorithmic way.
// Implementations are not consistent within browsers; sometimes labeled as just big5.
// MS Internet Explorer switches from big5 to big5-hkscs when a patch applied.
// Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31
// In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s.
// Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt
// http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt
//
// Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder
// Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong.
'windows950': 'cp950',
'ms950': 'cp950',
'950': 'cp950',
'cp950': {
type: '_dbcs',
table: function() { return require('./tables/cp950.json') },
},
// Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus.
'big5': 'big5hkscs',
'big5hkscs': {
type: '_dbcs',
table: function() { return require('./tables/cp950.json').concat(require('./tables/big5-added.json')) },
encodeSkipVals: [0xa2cc],
},
'cnbig5': 'big5hkscs',
'csbig5': 'big5hkscs',
'xxbig5': 'big5hkscs',
};
"use strict";
// Update this array if you add/rename/remove files in this directory.
// We support Browserify by skipping automatic module discovery and requiring modules directly.
var modules = [
require("./internal"),
require("./utf16"),
require("./utf7"),
require("./sbcs-codec"),
require("./sbcs-data"),
require("./sbcs-data-generated"),
require("./dbcs-codec"),
require("./dbcs-data"),
];
// Put all encoding/alias/codec definitions to single object and export it.
for (var i = 0; i < modules.length; i++) {
var module = modules[i];
for (var enc in module)
if (Object.prototype.hasOwnProperty.call(module, enc))
exports[enc] = module[enc];
}
"use strict";
var Buffer = require("buffer").Buffer;
// Export Node.js internal encodings.
module.exports = {
// Encodings
utf8: { type: "_internal", bomAware: true},
cesu8: { type: "_internal", bomAware: true},
unicode11utf8: "utf8",
ucs2: { type: "_internal", bomAware: true},
utf16le: "ucs2",
binary: { type: "_internal" },
iso88591: "binary",
base64: { type: "_internal" },
hex: { type: "_internal" },
// Codec.
_internal: InternalCodec,
};
//------------------------------------------------------------------------------
function InternalCodec(codecOptions, iconv) {
this.enc = codecOptions.encodingName;
this.bomAware = codecOptions.bomAware;
if (this.enc === "base64")
this.encoder = InternalEncoderBase64;
else if (this.enc === "cesu8") {
this.enc = "utf8"; // Use utf8 for decoding.
this.encoder = InternalEncoderCesu8;
// Add decoder for versions of Node not supporting CESU-8
if (new Buffer('eda0bdedb2a9', 'hex').toString() !== '💩') {
this.decoder = InternalDecoderCesu8;
this.defaultCharUnicode = iconv.defaultCharUnicode;
}
}
}
InternalCodec.prototype.encoder = InternalEncoder;
InternalCodec.prototype.decoder = InternalDecoder;
//------------------------------------------------------------------------------
// We use node.js internal decoder. Its signature is the same as ours.
var StringDecoder = require('string_decoder').StringDecoder;
if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method.
StringDecoder.prototype.end = function() {};
function InternalDecoder(options, codec) {
StringDecoder.call(this, codec.enc);
}
InternalDecoder.prototype = StringDecoder.prototype;
//------------------------------------------------------------------------------
// Encoder is mostly trivial
function InternalEncoder(options, codec) {
this.enc = codec.enc;
}
InternalEncoder.prototype.write = function(str) {
return new Buffer(str, this.enc);
}
InternalEncoder.prototype.end = function() {
}
//------------------------------------------------------------------------------
// Except base64 encoder, which must keep its state.
function InternalEncoderBase64(options, codec) {
this.prevStr = '';
}
InternalEncoderBase64.prototype.write = function(str) {
str = this.prevStr + str;
var completeQuads = str.length - (str.length % 4);
this.prevStr = str.slice(completeQuads);
str = str.slice(0, completeQuads);
return new Buffer(str, "base64");
}
InternalEncoderBase64.prototype.end = function() {
return new Buffer(this.prevStr, "base64");
}
//------------------------------------------------------------------------------
// CESU-8 encoder is also special.
function InternalEncoderCesu8(options, codec) {
}
InternalEncoderCesu8.prototype.write = function(str) {
var buf = new Buffer(str.length * 3), bufIdx = 0;
for (var i = 0; i < str.length; i++) {
var charCode = str.charCodeAt(i);
// Naive implementation, but it works because CESU-8 is especially easy
// to convert from UTF-16 (which all JS strings are encoded in).
if (charCode < 0x80)
buf[bufIdx++] = charCode;
else if (charCode < 0x800) {
buf[bufIdx++] = 0xC0 + (charCode >>> 6);
buf[bufIdx++] = 0x80 + (charCode & 0x3f);
}
else { // charCode will always be < 0x10000 in javascript.
buf[bufIdx++] = 0xE0 + (charCode >>> 12);
buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f);
buf[bufIdx++] = 0x80 + (charCode & 0x3f);
}
}
return buf.slice(0, bufIdx);
}
InternalEncoderCesu8.prototype.end = function() {
}
//------------------------------------------------------------------------------
// CESU-8 decoder is not implemented in Node v4.0+
function InternalDecoderCesu8(options, codec) {
this.acc = 0;
this.contBytes = 0;
this.accBytes = 0;
this.defaultCharUnicode = codec.defaultCharUnicode;
}
InternalDecoderCesu8.prototype.write = function(buf) {
var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes,
res = '';
for (var i = 0; i < buf.length; i++) {
var curByte = buf[i];
if ((curByte & 0xC0) !== 0x80) { // Leading byte
if (contBytes > 0) { // Previous code is invalid
res += this.defaultCharUnicode;
contBytes = 0;
}
if (curByte < 0x80) { // Single-byte code
res += String.fromCharCode(curByte);
} else if (curByte < 0xE0) { // Two-byte code
acc = curByte & 0x1F;
contBytes = 1; accBytes = 1;
} else if (curByte < 0xF0) { // Three-byte code
acc = curByte & 0x0F;
contBytes = 2; accBytes = 1;
} else { // Four or more are not supported for CESU-8.
res += this.defaultCharUnicode;
}
} else { // Continuation byte
if (contBytes > 0) { // We're waiting for it.
acc = (acc << 6) | (curByte & 0x3f);
contBytes--; accBytes++;
if (contBytes === 0) {
// Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80)
if (accBytes === 2 && acc < 0x80 && acc > 0)
res += this.defaultCharUnicode;
else if (accBytes === 3 && acc < 0x800)
res += this.defaultCharUnicode;
else
// Actually add character.
res += String.fromCharCode(acc);
}
} else { // Unexpected continuation byte
res += this.defaultCharUnicode;
}
}
}
this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes;
return res;
}
InternalDecoderCesu8.prototype.end = function() {
var res = 0;
if (this.contBytes > 0)
res += this.defaultCharUnicode;
return res;
}
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment