This commit is contained in:
Iliyan Angelov
2025-09-14 23:24:25 +03:00
commit c67067a2a4
71311 changed files with 6800714 additions and 0 deletions

4
frontend/node_modules/static-eval/.travis.yml generated vendored Normal file
View File

@@ -0,0 +1,4 @@
language: node_js
node_js:
- "0.8"
- "0.10"

18
frontend/node_modules/static-eval/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,18 @@
This software is released under the MIT license:
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.

7
frontend/node_modules/static-eval/example/eval.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
var evaluate = require('static-eval');
var parse = require('esprima').parse;
var src = process.argv.slice(2).join(' ');
var ast = parse(src).body[0].expression;
console.log(evaluate(ast));

11
frontend/node_modules/static-eval/example/vars.js generated vendored Normal file
View File

@@ -0,0 +1,11 @@
var evaluate = require('../');
var parse = require('esprima').parse;
var src = '[1,2,3+4*10+n,foo(3+5),obj[""+"x"].y]';
var ast = parse(src).body[0].expression;
console.log(evaluate(ast, {
n: 6,
foo: function (x) { return x * 100 },
obj: { x: { y: 555 } }
}));

178
frontend/node_modules/static-eval/index.js generated vendored Normal file
View File

@@ -0,0 +1,178 @@
var unparse = require('escodegen').generate;
module.exports = function (ast, vars) {
if (!vars) vars = {};
var FAIL = {};
var result = (function walk (node, scopeVars) {
if (node.type === 'Literal') {
return node.value;
}
else if (node.type === 'UnaryExpression'){
var val = walk(node.argument)
if (node.operator === '+') return +val
if (node.operator === '-') return -val
if (node.operator === '~') return ~val
if (node.operator === '!') return !val
return FAIL
}
else if (node.type === 'ArrayExpression') {
var xs = [];
for (var i = 0, l = node.elements.length; i < l; i++) {
var x = walk(node.elements[i]);
if (x === FAIL) return FAIL;
xs.push(x);
}
return xs;
}
else if (node.type === 'ObjectExpression') {
var obj = {};
for (var i = 0; i < node.properties.length; i++) {
var prop = node.properties[i];
var value = prop.value === null
? prop.value
: walk(prop.value)
;
if (value === FAIL) return FAIL;
obj[prop.key.value || prop.key.name] = value;
}
return obj;
}
else if (node.type === 'BinaryExpression' ||
node.type === 'LogicalExpression') {
var l = walk(node.left);
if (l === FAIL) return FAIL;
var r = walk(node.right);
if (r === FAIL) return FAIL;
var op = node.operator;
if (op === '==') return l == r;
if (op === '===') return l === r;
if (op === '!=') return l != r;
if (op === '!==') return l !== r;
if (op === '+') return l + r;
if (op === '-') return l - r;
if (op === '*') return l * r;
if (op === '/') return l / r;
if (op === '%') return l % r;
if (op === '<') return l < r;
if (op === '<=') return l <= r;
if (op === '>') return l > r;
if (op === '>=') return l >= r;
if (op === '|') return l | r;
if (op === '&') return l & r;
if (op === '^') return l ^ r;
if (op === '&&') return l && r;
if (op === '||') return l || r;
return FAIL;
}
else if (node.type === 'Identifier') {
if ({}.hasOwnProperty.call(vars, node.name)) {
return vars[node.name];
}
else return FAIL;
}
else if (node.type === 'ThisExpression') {
if ({}.hasOwnProperty.call(vars, 'this')) {
return vars['this'];
}
else return FAIL;
}
else if (node.type === 'CallExpression') {
var callee = walk(node.callee);
if (callee === FAIL) return FAIL;
if (typeof callee !== 'function') return FAIL;
var ctx = node.callee.object ? walk(node.callee.object) : FAIL;
if (ctx === FAIL) ctx = null;
var args = [];
for (var i = 0, l = node.arguments.length; i < l; i++) {
var x = walk(node.arguments[i]);
if (x === FAIL) return FAIL;
args.push(x);
}
return callee.apply(ctx, args);
}
else if (node.type === 'MemberExpression') {
var obj = walk(node.object);
// do not allow access to methods on Function
if((obj === FAIL) || (typeof obj == 'function')){
return FAIL;
}
if (node.property.type === 'Identifier') {
return obj[node.property.name];
}
var prop = walk(node.property);
if (prop === FAIL) return FAIL;
return obj[prop];
}
else if (node.type === 'ConditionalExpression') {
var val = walk(node.test)
if (val === FAIL) return FAIL;
return val ? walk(node.consequent) : walk(node.alternate)
}
else if (node.type === 'ExpressionStatement') {
var val = walk(node.expression)
if (val === FAIL) return FAIL;
return val;
}
else if (node.type === 'ReturnStatement') {
return walk(node.argument)
}
else if (node.type === 'FunctionExpression') {
var bodies = node.body.body;
// Create a "scope" for our arguments
var oldVars = {};
Object.keys(vars).forEach(function(element){
oldVars[element] = vars[element];
})
for(var i=0; i<node.params.length; i++){
var key = node.params[i];
if(key.type == 'Identifier'){
vars[key.name] = null;
}
else return FAIL;
}
for(var i in bodies){
if(walk(bodies[i]) === FAIL){
return FAIL;
}
}
// restore the vars and scope after we walk
vars = oldVars;
var keys = Object.keys(vars);
var vals = keys.map(function(key) {
return vars[key];
});
return Function(keys.join(', '), 'return ' + unparse(node)).apply(null, vals);
}
else if (node.type === 'TemplateLiteral') {
var str = '';
for (var i = 0; i < node.expressions.length; i++) {
str += walk(node.quasis[i]);
str += walk(node.expressions[i]);
}
str += walk(node.quasis[i]);
return str;
}
else if (node.type === 'TaggedTemplateExpression') {
var tag = walk(node.tag);
var quasi = node.quasi;
var strings = quasi.quasis.map(walk);
var values = quasi.expressions.map(walk);
return tag.apply(null, [strings].concat(values));
}
else if (node.type === 'TemplateElement') {
return node.value.cooked;
}
else return FAIL;
})(ast);
return result === FAIL ? undefined : result;
};

View File

@@ -0,0 +1 @@
../escodegen/bin/escodegen.js

View File

@@ -0,0 +1 @@
../escodegen/bin/esgenerate.js

View File

@@ -0,0 +1,21 @@
Copyright (C) 2012 Yusuke Suzuki (twitter: @Constellation) and other contributors.
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.

View File

@@ -0,0 +1,84 @@
## Escodegen
[![npm version](https://badge.fury.io/js/escodegen.svg)](http://badge.fury.io/js/escodegen)
[![Build Status](https://secure.travis-ci.org/estools/escodegen.svg)](http://travis-ci.org/estools/escodegen)
[![Dependency Status](https://david-dm.org/estools/escodegen.svg)](https://david-dm.org/estools/escodegen)
[![devDependency Status](https://david-dm.org/estools/escodegen/dev-status.svg)](https://david-dm.org/estools/escodegen#info=devDependencies)
Escodegen ([escodegen](http://github.com/estools/escodegen)) is an
[ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm)
(also popularly known as [JavaScript](http://en.wikipedia.org/wiki/JavaScript))
code generator from [Mozilla's Parser API](https://developer.mozilla.org/en/SpiderMonkey/Parser_API)
AST. See the [online generator](https://estools.github.io/escodegen/demo/index.html)
for a demo.
### Install
Escodegen can be used in a web browser:
<script src="escodegen.browser.js"></script>
escodegen.browser.js can be found in tagged revisions on GitHub.
Or in a Node.js application via npm:
npm install escodegen
### Usage
A simple example: the program
escodegen.generate({
type: 'BinaryExpression',
operator: '+',
left: { type: 'Literal', value: 40 },
right: { type: 'Literal', value: 2 }
});
produces the string `'40 + 2'`.
See the [API page](https://github.com/estools/escodegen/wiki/API) for
options. To run the tests, execute `npm test` in the root directory.
### Building browser bundle / minified browser bundle
At first, execute `npm install` to install the all dev dependencies.
After that,
npm run-script build
will generate `escodegen.browser.js`, which can be used in browser environments.
And,
npm run-script build-min
will generate the minified file `escodegen.browser.min.js`.
### License
#### Escodegen
Copyright (C) 2012 [Yusuke Suzuki](http://github.com/Constellation)
(twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors.
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.

View File

@@ -0,0 +1,77 @@
#!/usr/bin/env node
/*
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
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 */
var fs = require('fs'),
path = require('path'),
root = path.join(path.dirname(fs.realpathSync(__filename)), '..'),
esprima = require('esprima'),
escodegen = require(root),
optionator = require('optionator')({
prepend: 'Usage: escodegen [options] file...',
options: [
{
option: 'config',
alias: 'c',
type: 'String',
description: 'configuration json for escodegen'
}
]
}),
args = optionator.parse(process.argv),
files = args._,
options,
esprimaOptions = {
raw: true,
tokens: true,
range: true,
comment: true
};
if (files.length === 0) {
console.log(optionator.generateHelp());
process.exit(1);
}
if (args.config) {
try {
options = JSON.parse(fs.readFileSync(args.config, 'utf-8'));
} catch (err) {
console.error('Error parsing config: ', err);
}
}
files.forEach(function (filename) {
var content = fs.readFileSync(filename, 'utf-8'),
syntax = esprima.parse(content, esprimaOptions);
if (options.comment) {
escodegen.attachComments(syntax, syntax.comments, syntax.tokens);
}
console.log(escodegen.generate(syntax, options));
});
/* vim: set sw=4 ts=4 et tw=80 : */

View File

@@ -0,0 +1,64 @@
#!/usr/bin/env node
/*
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
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 */
var fs = require('fs'),
path = require('path'),
root = path.join(path.dirname(fs.realpathSync(__filename)), '..'),
escodegen = require(root),
optionator = require('optionator')({
prepend: 'Usage: esgenerate [options] file.json ...',
options: [
{
option: 'config',
alias: 'c',
type: 'String',
description: 'configuration json for escodegen'
}
]
}),
args = optionator.parse(process.argv),
files = args._,
options;
if (files.length === 0) {
console.log(optionator.generateHelp());
process.exit(1);
}
if (args.config) {
try {
options = JSON.parse(fs.readFileSync(args.config, 'utf-8'))
} catch (err) {
console.error('Error parsing config: ', err);
}
}
files.forEach(function (filename) {
var content = fs.readFileSync(filename, 'utf-8');
console.log(escodegen.generate(JSON.parse(content), options));
});
/* vim: set sw=4 ts=4 et tw=80 : */

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,61 @@
{
"name": "escodegen",
"description": "ECMAScript code generator",
"homepage": "http://github.com/estools/escodegen",
"main": "escodegen.js",
"bin": {
"esgenerate": "./bin/esgenerate.js",
"escodegen": "./bin/escodegen.js"
},
"files": [
"LICENSE.BSD",
"README.md",
"bin",
"escodegen.js",
"package.json"
],
"version": "1.14.3",
"engines": {
"node": ">=4.0"
},
"maintainers": [
{
"name": "Yusuke Suzuki",
"email": "utatane.tea@gmail.com",
"web": "http://github.com/Constellation"
}
],
"repository": {
"type": "git",
"url": "http://github.com/estools/escodegen.git"
},
"dependencies": {
"estraverse": "^4.2.0",
"esutils": "^2.0.2",
"esprima": "^4.0.1",
"optionator": "^0.8.1"
},
"optionalDependencies": {
"source-map": "~0.6.1"
},
"devDependencies": {
"acorn": "^7.1.0",
"bluebird": "^3.4.7",
"bower-registry-client": "^1.0.0",
"chai": "^3.5.0",
"commonjs-everywhere": "^0.9.7",
"gulp": "^3.8.10",
"gulp-eslint": "^3.0.1",
"gulp-mocha": "^3.0.1",
"semver": "^5.1.0"
},
"license": "BSD-2-Clause",
"scripts": {
"test": "gulp travis",
"unit-test": "gulp test",
"lint": "gulp lint",
"release": "node tools/release.js",
"build-min": "./node_modules/.bin/cjsify -ma path: tools/entry-point.js > escodegen.browser.min.js",
"build": "./node_modules/.bin/cjsify -a path: tools/entry-point.js > escodegen.browser.js"
}
}

View File

@@ -0,0 +1,16 @@
{
"curly": true,
"eqeqeq": true,
"immed": true,
"eqnull": true,
"latedef": true,
"noarg": true,
"noempty": true,
"quotmark": "single",
"undef": true,
"unused": true,
"strict": true,
"trailing": true,
"node": true
}

View File

@@ -0,0 +1,19 @@
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.

View File

@@ -0,0 +1,153 @@
### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse)
Estraverse ([estraverse](http://github.com/estools/estraverse)) is
[ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm)
traversal functions from [esmangle project](http://github.com/estools/esmangle).
### Documentation
You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage).
### Example Usage
The following code will output all variables declared at the root of a file.
```javascript
estraverse.traverse(ast, {
enter: function (node, parent) {
if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration')
return estraverse.VisitorOption.Skip;
},
leave: function (node, parent) {
if (node.type == 'VariableDeclarator')
console.log(node.id.name);
}
});
```
We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break.
```javascript
estraverse.traverse(ast, {
enter: function (node) {
this.break();
}
});
```
And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it.
```javascript
result = estraverse.replace(tree, {
enter: function (node) {
// Replace it with replaced.
if (node.type === 'Literal')
return replaced;
}
});
```
By passing `visitor.keys` mapping, we can extend estraverse traversing functionality.
```javascript
// This tree contains a user-defined `TestExpression` node.
var tree = {
type: 'TestExpression',
// This 'argument' is the property containing the other **node**.
argument: {
type: 'Literal',
value: 20
},
// This 'extended' is the property not containing the other **node**.
extended: true
};
estraverse.traverse(tree, {
enter: function (node) { },
// Extending the existing traversing rules.
keys: {
// TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ]
TestExpression: ['argument']
}
});
```
By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes.
```javascript
// This tree contains a user-defined `TestExpression` node.
var tree = {
type: 'TestExpression',
// This 'argument' is the property containing the other **node**.
argument: {
type: 'Literal',
value: 20
},
// This 'extended' is the property not containing the other **node**.
extended: true
};
estraverse.traverse(tree, {
enter: function (node) { },
// Iterating the child **nodes** of unknown nodes.
fallback: 'iteration'
});
```
When `visitor.fallback` is a function, we can determine which keys to visit on each node.
```javascript
// This tree contains a user-defined `TestExpression` node.
var tree = {
type: 'TestExpression',
// This 'argument' is the property containing the other **node**.
argument: {
type: 'Literal',
value: 20
},
// This 'extended' is the property not containing the other **node**.
extended: true
};
estraverse.traverse(tree, {
enter: function (node) { },
// Skip the `argument` property of each node
fallback: function(node) {
return Object.keys(node).filter(function(key) {
return key !== 'argument';
});
}
});
```
### License
Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation)
(twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors.
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.

View File

@@ -0,0 +1,782 @@
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
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 vars:false, bitwise:true*/
/*jshint indent:4*/
/*global exports:true*/
(function clone(exports) {
'use strict';
var Syntax,
VisitorOption,
VisitorKeys,
BREAK,
SKIP,
REMOVE;
function deepCopy(obj) {
var ret = {}, key, val;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
val = obj[key];
if (typeof val === 'object' && val !== null) {
ret[key] = deepCopy(val);
} else {
ret[key] = val;
}
}
}
return ret;
}
// based on LLVM libc++ upper_bound / lower_bound
// MIT License
function upperBound(array, func) {
var diff, len, i, current;
len = array.length;
i = 0;
while (len) {
diff = len >>> 1;
current = i + diff;
if (func(array[current])) {
len = diff;
} else {
i = current + 1;
len -= diff + 1;
}
}
return i;
}
Syntax = {
AssignmentExpression: 'AssignmentExpression',
AssignmentPattern: 'AssignmentPattern',
ArrayExpression: 'ArrayExpression',
ArrayPattern: 'ArrayPattern',
ArrowFunctionExpression: 'ArrowFunctionExpression',
AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7.
BlockStatement: 'BlockStatement',
BinaryExpression: 'BinaryExpression',
BreakStatement: 'BreakStatement',
CallExpression: 'CallExpression',
CatchClause: 'CatchClause',
ClassBody: 'ClassBody',
ClassDeclaration: 'ClassDeclaration',
ClassExpression: 'ClassExpression',
ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7.
ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7.
ConditionalExpression: 'ConditionalExpression',
ContinueStatement: 'ContinueStatement',
DebuggerStatement: 'DebuggerStatement',
DirectiveStatement: 'DirectiveStatement',
DoWhileStatement: 'DoWhileStatement',
EmptyStatement: 'EmptyStatement',
ExportAllDeclaration: 'ExportAllDeclaration',
ExportDefaultDeclaration: 'ExportDefaultDeclaration',
ExportNamedDeclaration: 'ExportNamedDeclaration',
ExportSpecifier: 'ExportSpecifier',
ExpressionStatement: 'ExpressionStatement',
ForStatement: 'ForStatement',
ForInStatement: 'ForInStatement',
ForOfStatement: 'ForOfStatement',
FunctionDeclaration: 'FunctionDeclaration',
FunctionExpression: 'FunctionExpression',
GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7.
Identifier: 'Identifier',
IfStatement: 'IfStatement',
ImportExpression: 'ImportExpression',
ImportDeclaration: 'ImportDeclaration',
ImportDefaultSpecifier: 'ImportDefaultSpecifier',
ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
ImportSpecifier: 'ImportSpecifier',
Literal: 'Literal',
LabeledStatement: 'LabeledStatement',
LogicalExpression: 'LogicalExpression',
MemberExpression: 'MemberExpression',
MetaProperty: 'MetaProperty',
MethodDefinition: 'MethodDefinition',
ModuleSpecifier: 'ModuleSpecifier',
NewExpression: 'NewExpression',
ObjectExpression: 'ObjectExpression',
ObjectPattern: 'ObjectPattern',
Program: 'Program',
Property: 'Property',
RestElement: 'RestElement',
ReturnStatement: 'ReturnStatement',
SequenceExpression: 'SequenceExpression',
SpreadElement: 'SpreadElement',
Super: 'Super',
SwitchStatement: 'SwitchStatement',
SwitchCase: 'SwitchCase',
TaggedTemplateExpression: 'TaggedTemplateExpression',
TemplateElement: 'TemplateElement',
TemplateLiteral: 'TemplateLiteral',
ThisExpression: 'ThisExpression',
ThrowStatement: 'ThrowStatement',
TryStatement: 'TryStatement',
UnaryExpression: 'UnaryExpression',
UpdateExpression: 'UpdateExpression',
VariableDeclaration: 'VariableDeclaration',
VariableDeclarator: 'VariableDeclarator',
WhileStatement: 'WhileStatement',
WithStatement: 'WithStatement',
YieldExpression: 'YieldExpression'
};
VisitorKeys = {
AssignmentExpression: ['left', 'right'],
AssignmentPattern: ['left', 'right'],
ArrayExpression: ['elements'],
ArrayPattern: ['elements'],
ArrowFunctionExpression: ['params', 'body'],
AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7.
BlockStatement: ['body'],
BinaryExpression: ['left', 'right'],
BreakStatement: ['label'],
CallExpression: ['callee', 'arguments'],
CatchClause: ['param', 'body'],
ClassBody: ['body'],
ClassDeclaration: ['id', 'superClass', 'body'],
ClassExpression: ['id', 'superClass', 'body'],
ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7.
ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.
ConditionalExpression: ['test', 'consequent', 'alternate'],
ContinueStatement: ['label'],
DebuggerStatement: [],
DirectiveStatement: [],
DoWhileStatement: ['body', 'test'],
EmptyStatement: [],
ExportAllDeclaration: ['source'],
ExportDefaultDeclaration: ['declaration'],
ExportNamedDeclaration: ['declaration', 'specifiers', 'source'],
ExportSpecifier: ['exported', 'local'],
ExpressionStatement: ['expression'],
ForStatement: ['init', 'test', 'update', 'body'],
ForInStatement: ['left', 'right', 'body'],
ForOfStatement: ['left', 'right', 'body'],
FunctionDeclaration: ['id', 'params', 'body'],
FunctionExpression: ['id', 'params', 'body'],
GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.
Identifier: [],
IfStatement: ['test', 'consequent', 'alternate'],
ImportExpression: ['source'],
ImportDeclaration: ['specifiers', 'source'],
ImportDefaultSpecifier: ['local'],
ImportNamespaceSpecifier: ['local'],
ImportSpecifier: ['imported', 'local'],
Literal: [],
LabeledStatement: ['label', 'body'],
LogicalExpression: ['left', 'right'],
MemberExpression: ['object', 'property'],
MetaProperty: ['meta', 'property'],
MethodDefinition: ['key', 'value'],
ModuleSpecifier: [],
NewExpression: ['callee', 'arguments'],
ObjectExpression: ['properties'],
ObjectPattern: ['properties'],
Program: ['body'],
Property: ['key', 'value'],
RestElement: [ 'argument' ],
ReturnStatement: ['argument'],
SequenceExpression: ['expressions'],
SpreadElement: ['argument'],
Super: [],
SwitchStatement: ['discriminant', 'cases'],
SwitchCase: ['test', 'consequent'],
TaggedTemplateExpression: ['tag', 'quasi'],
TemplateElement: [],
TemplateLiteral: ['quasis', 'expressions'],
ThisExpression: [],
ThrowStatement: ['argument'],
TryStatement: ['block', 'handler', 'finalizer'],
UnaryExpression: ['argument'],
UpdateExpression: ['argument'],
VariableDeclaration: ['declarations'],
VariableDeclarator: ['id', 'init'],
WhileStatement: ['test', 'body'],
WithStatement: ['object', 'body'],
YieldExpression: ['argument']
};
// unique id
BREAK = {};
SKIP = {};
REMOVE = {};
VisitorOption = {
Break: BREAK,
Skip: SKIP,
Remove: REMOVE
};
function Reference(parent, key) {
this.parent = parent;
this.key = key;
}
Reference.prototype.replace = function replace(node) {
this.parent[this.key] = node;
};
Reference.prototype.remove = function remove() {
if (Array.isArray(this.parent)) {
this.parent.splice(this.key, 1);
return true;
} else {
this.replace(null);
return false;
}
};
function Element(node, path, wrap, ref) {
this.node = node;
this.path = path;
this.wrap = wrap;
this.ref = ref;
}
function Controller() { }
// API:
// return property path array from root to current node
Controller.prototype.path = function path() {
var i, iz, j, jz, result, element;
function addToPath(result, path) {
if (Array.isArray(path)) {
for (j = 0, jz = path.length; j < jz; ++j) {
result.push(path[j]);
}
} else {
result.push(path);
}
}
// root node
if (!this.__current.path) {
return null;
}
// first node is sentinel, second node is root element
result = [];
for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {
element = this.__leavelist[i];
addToPath(result, element.path);
}
addToPath(result, this.__current.path);
return result;
};
// API:
// return type of current node
Controller.prototype.type = function () {
var node = this.current();
return node.type || this.__current.wrap;
};
// API:
// return array of parent elements
Controller.prototype.parents = function parents() {
var i, iz, result;
// first node is sentinel
result = [];
for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {
result.push(this.__leavelist[i].node);
}
return result;
};
// API:
// return current node
Controller.prototype.current = function current() {
return this.__current.node;
};
Controller.prototype.__execute = function __execute(callback, element) {
var previous, result;
result = undefined;
previous = this.__current;
this.__current = element;
this.__state = null;
if (callback) {
result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);
}
this.__current = previous;
return result;
};
// API:
// notify control skip / break
Controller.prototype.notify = function notify(flag) {
this.__state = flag;
};
// API:
// skip child nodes of current node
Controller.prototype.skip = function () {
this.notify(SKIP);
};
// API:
// break traversals
Controller.prototype['break'] = function () {
this.notify(BREAK);
};
// API:
// remove node
Controller.prototype.remove = function () {
this.notify(REMOVE);
};
Controller.prototype.__initialize = function(root, visitor) {
this.visitor = visitor;
this.root = root;
this.__worklist = [];
this.__leavelist = [];
this.__current = null;
this.__state = null;
this.__fallback = null;
if (visitor.fallback === 'iteration') {
this.__fallback = Object.keys;
} else if (typeof visitor.fallback === 'function') {
this.__fallback = visitor.fallback;
}
this.__keys = VisitorKeys;
if (visitor.keys) {
this.__keys = Object.assign(Object.create(this.__keys), visitor.keys);
}
};
function isNode(node) {
if (node == null) {
return false;
}
return typeof node === 'object' && typeof node.type === 'string';
}
function isProperty(nodeType, key) {
return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key;
}
Controller.prototype.traverse = function traverse(root, visitor) {
var worklist,
leavelist,
element,
node,
nodeType,
ret,
key,
current,
current2,
candidates,
candidate,
sentinel;
this.__initialize(root, visitor);
sentinel = {};
// reference
worklist = this.__worklist;
leavelist = this.__leavelist;
// initialize
worklist.push(new Element(root, null, null, null));
leavelist.push(new Element(null, null, null, null));
while (worklist.length) {
element = worklist.pop();
if (element === sentinel) {
element = leavelist.pop();
ret = this.__execute(visitor.leave, element);
if (this.__state === BREAK || ret === BREAK) {
return;
}
continue;
}
if (element.node) {
ret = this.__execute(visitor.enter, element);
if (this.__state === BREAK || ret === BREAK) {
return;
}
worklist.push(sentinel);
leavelist.push(element);
if (this.__state === SKIP || ret === SKIP) {
continue;
}
node = element.node;
nodeType = node.type || element.wrap;
candidates = this.__keys[nodeType];
if (!candidates) {
if (this.__fallback) {
candidates = this.__fallback(node);
} else {
throw new Error('Unknown node type ' + nodeType + '.');
}
}
current = candidates.length;
while ((current -= 1) >= 0) {
key = candidates[current];
candidate = node[key];
if (!candidate) {
continue;
}
if (Array.isArray(candidate)) {
current2 = candidate.length;
while ((current2 -= 1) >= 0) {
if (!candidate[current2]) {
continue;
}
if (isProperty(nodeType, candidates[current])) {
element = new Element(candidate[current2], [key, current2], 'Property', null);
} else if (isNode(candidate[current2])) {
element = new Element(candidate[current2], [key, current2], null, null);
} else {
continue;
}
worklist.push(element);
}
} else if (isNode(candidate)) {
worklist.push(new Element(candidate, key, null, null));
}
}
}
}
};
Controller.prototype.replace = function replace(root, visitor) {
var worklist,
leavelist,
node,
nodeType,
target,
element,
current,
current2,
candidates,
candidate,
sentinel,
outer,
key;
function removeElem(element) {
var i,
key,
nextElem,
parent;
if (element.ref.remove()) {
// When the reference is an element of an array.
key = element.ref.key;
parent = element.ref.parent;
// If removed from array, then decrease following items' keys.
i = worklist.length;
while (i--) {
nextElem = worklist[i];
if (nextElem.ref && nextElem.ref.parent === parent) {
if (nextElem.ref.key < key) {
break;
}
--nextElem.ref.key;
}
}
}
}
this.__initialize(root, visitor);
sentinel = {};
// reference
worklist = this.__worklist;
leavelist = this.__leavelist;
// initialize
outer = {
root: root
};
element = new Element(root, null, null, new Reference(outer, 'root'));
worklist.push(element);
leavelist.push(element);
while (worklist.length) {
element = worklist.pop();
if (element === sentinel) {
element = leavelist.pop();
target = this.__execute(visitor.leave, element);
// node may be replaced with null,
// so distinguish between undefined and null in this place
if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
// replace
element.ref.replace(target);
}
if (this.__state === REMOVE || target === REMOVE) {
removeElem(element);
}
if (this.__state === BREAK || target === BREAK) {
return outer.root;
}
continue;
}
target = this.__execute(visitor.enter, element);
// node may be replaced with null,
// so distinguish between undefined and null in this place
if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
// replace
element.ref.replace(target);
element.node = target;
}
if (this.__state === REMOVE || target === REMOVE) {
removeElem(element);
element.node = null;
}
if (this.__state === BREAK || target === BREAK) {
return outer.root;
}
// node may be null
node = element.node;
if (!node) {
continue;
}
worklist.push(sentinel);
leavelist.push(element);
if (this.__state === SKIP || target === SKIP) {
continue;
}
nodeType = node.type || element.wrap;
candidates = this.__keys[nodeType];
if (!candidates) {
if (this.__fallback) {
candidates = this.__fallback(node);
} else {
throw new Error('Unknown node type ' + nodeType + '.');
}
}
current = candidates.length;
while ((current -= 1) >= 0) {
key = candidates[current];
candidate = node[key];
if (!candidate) {
continue;
}
if (Array.isArray(candidate)) {
current2 = candidate.length;
while ((current2 -= 1) >= 0) {
if (!candidate[current2]) {
continue;
}
if (isProperty(nodeType, candidates[current])) {
element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2));
} else if (isNode(candidate[current2])) {
element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2));
} else {
continue;
}
worklist.push(element);
}
} else if (isNode(candidate)) {
worklist.push(new Element(candidate, key, null, new Reference(node, key)));
}
}
}
return outer.root;
};
function traverse(root, visitor) {
var controller = new Controller();
return controller.traverse(root, visitor);
}
function replace(root, visitor) {
var controller = new Controller();
return controller.replace(root, visitor);
}
function extendCommentRange(comment, tokens) {
var target;
target = upperBound(tokens, function search(token) {
return token.range[0] > comment.range[0];
});
comment.extendedRange = [comment.range[0], comment.range[1]];
if (target !== tokens.length) {
comment.extendedRange[1] = tokens[target].range[0];
}
target -= 1;
if (target >= 0) {
comment.extendedRange[0] = tokens[target].range[1];
}
return comment;
}
function attachComments(tree, providedComments, tokens) {
// At first, we should calculate extended comment ranges.
var comments = [], comment, len, i, cursor;
if (!tree.range) {
throw new Error('attachComments needs range information');
}
// tokens array is empty, we attach comments to tree as 'leadingComments'
if (!tokens.length) {
if (providedComments.length) {
for (i = 0, len = providedComments.length; i < len; i += 1) {
comment = deepCopy(providedComments[i]);
comment.extendedRange = [0, tree.range[0]];
comments.push(comment);
}
tree.leadingComments = comments;
}
return tree;
}
for (i = 0, len = providedComments.length; i < len; i += 1) {
comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));
}
// This is based on John Freeman's implementation.
cursor = 0;
traverse(tree, {
enter: function (node) {
var comment;
while (cursor < comments.length) {
comment = comments[cursor];
if (comment.extendedRange[1] > node.range[0]) {
break;
}
if (comment.extendedRange[1] === node.range[0]) {
if (!node.leadingComments) {
node.leadingComments = [];
}
node.leadingComments.push(comment);
comments.splice(cursor, 1);
} else {
cursor += 1;
}
}
// already out of owned node
if (cursor === comments.length) {
return VisitorOption.Break;
}
if (comments[cursor].extendedRange[0] > node.range[1]) {
return VisitorOption.Skip;
}
}
});
cursor = 0;
traverse(tree, {
leave: function (node) {
var comment;
while (cursor < comments.length) {
comment = comments[cursor];
if (node.range[1] < comment.extendedRange[0]) {
break;
}
if (node.range[1] === comment.extendedRange[0]) {
if (!node.trailingComments) {
node.trailingComments = [];
}
node.trailingComments.push(comment);
comments.splice(cursor, 1);
} else {
cursor += 1;
}
}
// already out of owned node
if (cursor === comments.length) {
return VisitorOption.Break;
}
if (comments[cursor].extendedRange[0] > node.range[1]) {
return VisitorOption.Skip;
}
}
});
return tree;
}
exports.version = require('./package.json').version;
exports.Syntax = Syntax;
exports.traverse = traverse;
exports.replace = replace;
exports.attachComments = attachComments;
exports.VisitorKeys = VisitorKeys;
exports.VisitorOption = VisitorOption;
exports.Controller = Controller;
exports.cloneEnvironment = function () { return clone({}); };
return exports;
}(exports));
/* vim: set sw=4 ts=4 et tw=80 : */

View File

@@ -0,0 +1,70 @@
/*
Copyright (C) 2014 Yusuke Suzuki <utatane.tea@gmail.com>
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.
*/
'use strict';
var gulp = require('gulp'),
git = require('gulp-git'),
bump = require('gulp-bump'),
filter = require('gulp-filter'),
tagVersion = require('gulp-tag-version');
var TEST = [ 'test/*.js' ];
var POWERED = [ 'powered-test/*.js' ];
var SOURCE = [ 'src/**/*.js' ];
/**
* Bumping version number and tagging the repository with it.
* Please read http://semver.org/
*
* You can use the commands
*
* gulp patch # makes v0.1.0 -> v0.1.1
* gulp feature # makes v0.1.1 -> v0.2.0
* gulp release # makes v0.2.1 -> v1.0.0
*
* To bump the version numbers accordingly after you did a patch,
* introduced a feature or made a backwards-incompatible release.
*/
function inc(importance) {
// get all the files to bump version in
return gulp.src(['./package.json'])
// bump the version number in those files
.pipe(bump({type: importance}))
// save it back to filesystem
.pipe(gulp.dest('./'))
// commit the changed version number
.pipe(git.commit('Bumps package version'))
// read only one file to get the version number
.pipe(filter('package.json'))
// **tag it in the repository**
.pipe(tagVersion({
prefix: ''
}));
}
gulp.task('patch', [ ], function () { return inc('patch'); })
gulp.task('minor', [ ], function () { return inc('minor'); })
gulp.task('major', [ ], function () { return inc('major'); })

View File

@@ -0,0 +1,40 @@
{
"name": "estraverse",
"description": "ECMAScript JS AST traversal functions",
"homepage": "https://github.com/estools/estraverse",
"main": "estraverse.js",
"version": "4.3.0",
"engines": {
"node": ">=4.0"
},
"maintainers": [
{
"name": "Yusuke Suzuki",
"email": "utatane.tea@gmail.com",
"web": "http://github.com/Constellation"
}
],
"repository": {
"type": "git",
"url": "http://github.com/estools/estraverse.git"
},
"devDependencies": {
"babel-preset-env": "^1.6.1",
"babel-register": "^6.3.13",
"chai": "^2.1.1",
"espree": "^1.11.0",
"gulp": "^3.8.10",
"gulp-bump": "^0.2.2",
"gulp-filter": "^2.0.0",
"gulp-git": "^1.0.1",
"gulp-tag-version": "^1.3.0",
"jshint": "^2.5.6",
"mocha": "^2.1.0"
},
"license": "BSD-2-Clause",
"scripts": {
"test": "npm run-script lint && npm run-script unit-test",
"lint": "jshint estraverse.js",
"unit-test": "mocha --compilers js:babel-register"
}
}

View File

@@ -0,0 +1,22 @@
Copyright (c) George Zahariev
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.

View File

@@ -0,0 +1,196 @@
# levn [![Build Status](https://travis-ci.org/gkz/levn.png)](https://travis-ci.org/gkz/levn) <a name="levn" />
__Light ECMAScript (JavaScript) Value Notation__
Levn is a library which allows you to parse a string into a JavaScript value based on an expected type. It is meant for short amounts of human entered data (eg. config files, command line arguments).
Levn aims to concisely describe JavaScript values in text, and allow for the extraction and validation of those values. Levn uses [type-check](https://github.com/gkz/type-check) for its type format, and to validate the results. MIT license. Version 0.3.0.
__How is this different than JSON?__ levn is meant to be written by humans only, is (due to the previous point) much more concise, can be validated against supplied types, has regex and date literals, and can easily be extended with custom types. On the other hand, it is probably slower and thus less efficient at transporting large amounts of data, which is fine since this is not its purpose.
npm install levn
For updates on levn, [follow me on twitter](https://twitter.com/gkzahariev).
## Quick Examples
```js
var parse = require('levn').parse;
parse('Number', '2'); // 2
parse('String', '2'); // '2'
parse('String', 'levn'); // 'levn'
parse('String', 'a b'); // 'a b'
parse('Boolean', 'true'); // true
parse('Date', '#2011-11-11#'); // (Date object)
parse('Date', '2011-11-11'); // (Date object)
parse('RegExp', '/[a-z]/gi'); // /[a-z]/gi
parse('RegExp', 're'); // /re/
parse('Int', '2'); // 2
parse('Number | String', 'str'); // 'str'
parse('Number | String', '2'); // 2
parse('[Number]', '[1,2,3]'); // [1,2,3]
parse('(String, Boolean)', '(hi, false)'); // ['hi', false]
parse('{a: String, b: Number}', '{a: str, b: 2}'); // {a: 'str', b: 2}
// at the top level, you can ommit surrounding delimiters
parse('[Number]', '1,2,3'); // [1,2,3]
parse('(String, Boolean)', 'hi, false'); // ['hi', false]
parse('{a: String, b: Number}', 'a: str, b: 2'); // {a: 'str', b: 2}
// wildcard - auto choose type
parse('*', '[hi,(null,[42]),{k: true}]'); // ['hi', [null, [42]], {k: true}]
```
## Usage
`require('levn');` returns an object that exposes three properties. `VERSION` is the current version of the library as a string. `parse` and `parsedTypeParse` are functions.
```js
// parse(type, input, options);
parse('[Number]', '1,2,3'); // [1, 2, 3]
// parsedTypeParse(parsedType, input, options);
var parsedType = require('type-check').parseType('[Number]');
parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3]
```
### parse(type, input, options)
`parse` casts the string `input` into a JavaScript value according to the specified `type` in the [type format](https://github.com/gkz/type-check#type-format) (and taking account the optional `options`) and returns the resulting JavaScript value.
##### arguments
* type - `String` - the type written in the [type format](https://github.com/gkz/type-check#type-format) which to check against
* input - `String` - the value written in the [levn format](#levn-format)
* options - `Maybe Object` - an optional parameter specifying additional [options](#options)
##### returns
`*` - the resulting JavaScript value
##### example
```js
parse('[Number]', '1,2,3'); // [1, 2, 3]
```
### parsedTypeParse(parsedType, input, options)
`parsedTypeParse` casts the string `input` into a JavaScript value according to the specified `type` which has already been parsed (and taking account the optional `options`) and returns the resulting JavaScript value. You can parse a type using the [type-check](https://github.com/gkz/type-check) library's `parseType` function.
##### arguments
* type - `Object` - the type in the parsed type format which to check against
* input - `String` - the value written in the [levn format](#levn-format)
* options - `Maybe Object` - an optional parameter specifying additional [options](#options)
##### returns
`*` - the resulting JavaScript value
##### example
```js
var parsedType = require('type-check').parseType('[Number]');
parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3]
```
## Levn Format
Levn can use the type information you provide to choose the appropriate value to produce from the input. For the same input, it will choose a different output value depending on the type provided. For example, `parse('Number', '2')` will produce the number `2`, but `parse('String', '2')` will produce the string `"2"`.
If you do not provide type information, and simply use `*`, levn will parse the input according the unambiguous "explicit" mode, which we will now detail - you can also set the `explicit` option to true manually in the [options](#options).
* `"string"`, `'string'` are parsed as a String, eg. `"a msg"` is `"a msg"`
* `#date#` is parsed as a Date, eg. `#2011-11-11#` is `new Date('2011-11-11')`
* `/regexp/flags` is parsed as a RegExp, eg. `/re/gi` is `/re/gi`
* `undefined`, `null`, `NaN`, `true`, and `false` are all their JavaScript equivalents
* `[element1, element2, etc]` is an Array, and the casting procedure is recursively applied to each element. Eg. `[1,2,3]` is `[1,2,3]`.
* `(element1, element2, etc)` is an tuple, and the casting procedure is recursively applied to each element. Eg. `(1, a)` is `(1, a)` (is `[1, 'a']`).
* `{key1: val1, key2: val2, ...}` is an Object, and the casting procedure is recursively applied to each property. Eg. `{a: 1, b: 2}` is `{a: 1, b: 2}`.
* Any test which does not fall under the above, and which does not contain special characters (`[``]``(``)``{``}``:``,`) is a string, eg. `$12- blah` is `"$12- blah"`.
If you do provide type information, you can make your input more concise as the program already has some information about what it expects. Please see the [type format](https://github.com/gkz/type-check#type-format) section of [type-check](https://github.com/gkz/type-check) for more information about how to specify types. There are some rules about what levn can do with the information:
* If a String is expected, and only a String, all characters of the input (including any special ones) will become part of the output. Eg. `[({})]` is `"[({})]"`, and `"hi"` is `'"hi"'`.
* If a Date is expected, the surrounding `#` can be omitted from date literals. Eg. `2011-11-11` is `new Date('2011-11-11')`.
* If a RegExp is expected, no flags need to be specified, and the regex is not using any of the special characters,the opening and closing `/` can be omitted - this will have the affect of setting the source of the regex to the input. Eg. `regex` is `/regex/`.
* If an Array is expected, and it is the root node (at the top level), the opening `[` and closing `]` can be omitted. Eg. `1,2,3` is `[1,2,3]`.
* If a tuple is expected, and it is the root node (at the top level), the opening `(` and closing `)` can be omitted. Eg. `1, a` is `(1, a)` (is `[1, 'a']`).
* If an Object is expected, and it is the root node (at the top level), the opening `{` and closing `}` can be omitted. Eg `a: 1, b: 2` is `{a: 1, b: 2}`.
If you list multiple types (eg. `Number | String`), it will first attempt to cast to the first type and then validate - if the validation fails it will move on to the next type and so forth, left to right. You must be careful as some types will succeed with any input, such as String. Thus put String at the end of your list. In non-explicit mode, Date and RegExp will succeed with a large variety of input - also be careful with these and list them near the end if not last in your list.
Whitespace between special characters and elements is inconsequential.
## Options
Options is an object. It is an optional parameter to the `parse` and `parsedTypeParse` functions.
### Explicit
A `Boolean`. By default it is `false`.
__Example:__
```js
parse('RegExp', 're', {explicit: false}); // /re/
parse('RegExp', 're', {explicit: true}); // Error: ... does not type check...
parse('RegExp | String', 're', {explicit: true}); // 're'
```
`explicit` sets whether to be in explicit mode or not. Using `*` automatically activates explicit mode. For more information, read the [levn format](#levn-format) section.
### customTypes
An `Object`. Empty `{}` by default.
__Example:__
```js
var options = {
customTypes: {
Even: {
typeOf: 'Number',
validate: function (x) {
return x % 2 === 0;
},
cast: function (x) {
return {type: 'Just', value: parseInt(x)};
}
}
}
}
parse('Even', '2', options); // 2
parse('Even', '3', options); // Error: Value: "3" does not type check...
```
__Another Example:__
```js
function Person(name, age){
this.name = name;
this.age = age;
}
var options = {
customTypes: {
Person: {
typeOf: 'Object',
validate: function (x) {
x instanceof Person;
},
cast: function (value, options, typesCast) {
var name, age;
if ({}.toString.call(value).slice(8, -1) !== 'Object') {
return {type: 'Nothing'};
}
name = typesCast(value.name, [{type: 'String'}], options);
age = typesCast(value.age, [{type: 'Numger'}], options);
return {type: 'Just', value: new Person(name, age)};
}
}
}
parse('Person', '{name: Laura, age: 25}', options); // Person {name: 'Laura', age: 25}
```
`customTypes` is an object whose keys are the name of the types, and whose values are an object with three properties, `typeOf`, `validate`, and `cast`. For more information about `typeOf` and `validate`, please see the [custom types](https://github.com/gkz/type-check#custom-types) section of type-check.
`cast` is a function which receives three arguments, the value under question, options, and the typesCast function. In `cast`, attempt to cast the value into the specified type. If you are successful, return an object in the format `{type: 'Just', value: CAST-VALUE}`, if you know it won't work, return `{type: 'Nothing'}`. You can use the `typesCast` function to cast any child values. Remember to pass `options` to it. In your function you can also check for `options.explicit` and act accordingly.
## Technical About
`levn` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [type-check](https://github.com/gkz/type-check) to both parse types and validate values. It also uses the [prelude.ls](http://preludels.com/) library.

View File

@@ -0,0 +1,298 @@
// Generated by LiveScript 1.4.0
(function(){
var parsedTypeCheck, types, toString$ = {}.toString;
parsedTypeCheck = require('type-check').parsedTypeCheck;
types = {
'*': function(value, options){
switch (toString$.call(value).slice(8, -1)) {
case 'Array':
return typeCast(value, {
type: 'Array'
}, options);
case 'Object':
return typeCast(value, {
type: 'Object'
}, options);
default:
return {
type: 'Just',
value: typesCast(value, [
{
type: 'Undefined'
}, {
type: 'Null'
}, {
type: 'NaN'
}, {
type: 'Boolean'
}, {
type: 'Number'
}, {
type: 'Date'
}, {
type: 'RegExp'
}, {
type: 'Array'
}, {
type: 'Object'
}, {
type: 'String'
}
], (options.explicit = true, options))
};
}
},
Undefined: function(it){
if (it === 'undefined' || it === void 8) {
return {
type: 'Just',
value: void 8
};
} else {
return {
type: 'Nothing'
};
}
},
Null: function(it){
if (it === 'null') {
return {
type: 'Just',
value: null
};
} else {
return {
type: 'Nothing'
};
}
},
NaN: function(it){
if (it === 'NaN') {
return {
type: 'Just',
value: NaN
};
} else {
return {
type: 'Nothing'
};
}
},
Boolean: function(it){
if (it === 'true') {
return {
type: 'Just',
value: true
};
} else if (it === 'false') {
return {
type: 'Just',
value: false
};
} else {
return {
type: 'Nothing'
};
}
},
Number: function(it){
return {
type: 'Just',
value: +it
};
},
Int: function(it){
return {
type: 'Just',
value: +it
};
},
Float: function(it){
return {
type: 'Just',
value: +it
};
},
Date: function(value, options){
var that;
if (that = /^\#([\s\S]*)\#$/.exec(value)) {
return {
type: 'Just',
value: new Date(+that[1] || that[1])
};
} else if (options.explicit) {
return {
type: 'Nothing'
};
} else {
return {
type: 'Just',
value: new Date(+value || value)
};
}
},
RegExp: function(value, options){
var that;
if (that = /^\/([\s\S]*)\/([gimy]*)$/.exec(value)) {
return {
type: 'Just',
value: new RegExp(that[1], that[2])
};
} else if (options.explicit) {
return {
type: 'Nothing'
};
} else {
return {
type: 'Just',
value: new RegExp(value)
};
}
},
Array: function(value, options){
return castArray(value, {
of: [{
type: '*'
}]
}, options);
},
Object: function(value, options){
return castFields(value, {
of: {}
}, options);
},
String: function(it){
var that;
if (toString$.call(it).slice(8, -1) !== 'String') {
return {
type: 'Nothing'
};
}
if (that = it.match(/^'([\s\S]*)'$/)) {
return {
type: 'Just',
value: that[1].replace(/\\'/g, "'")
};
} else if (that = it.match(/^"([\s\S]*)"$/)) {
return {
type: 'Just',
value: that[1].replace(/\\"/g, '"')
};
} else {
return {
type: 'Just',
value: it
};
}
}
};
function castArray(node, type, options){
var typeOf, element;
if (toString$.call(node).slice(8, -1) !== 'Array') {
return {
type: 'Nothing'
};
}
typeOf = type.of;
return {
type: 'Just',
value: (function(){
var i$, ref$, len$, results$ = [];
for (i$ = 0, len$ = (ref$ = node).length; i$ < len$; ++i$) {
element = ref$[i$];
results$.push(typesCast(element, typeOf, options));
}
return results$;
}())
};
}
function castTuple(node, type, options){
var result, i, i$, ref$, len$, types, cast;
if (toString$.call(node).slice(8, -1) !== 'Array') {
return {
type: 'Nothing'
};
}
result = [];
i = 0;
for (i$ = 0, len$ = (ref$ = type.of).length; i$ < len$; ++i$) {
types = ref$[i$];
cast = typesCast(node[i], types, options);
if (toString$.call(cast).slice(8, -1) !== 'Undefined') {
result.push(cast);
}
i++;
}
if (node.length <= i) {
return {
type: 'Just',
value: result
};
} else {
return {
type: 'Nothing'
};
}
}
function castFields(node, type, options){
var typeOf, key, value;
if (toString$.call(node).slice(8, -1) !== 'Object') {
return {
type: 'Nothing'
};
}
typeOf = type.of;
return {
type: 'Just',
value: (function(){
var ref$, resultObj$ = {};
for (key in ref$ = node) {
value = ref$[key];
resultObj$[typesCast(key, [{
type: 'String'
}], options)] = typesCast(value, typeOf[key] || [{
type: '*'
}], options);
}
return resultObj$;
}())
};
}
function typeCast(node, typeObj, options){
var type, structure, castFunc, ref$;
type = typeObj.type, structure = typeObj.structure;
if (type) {
castFunc = ((ref$ = options.customTypes[type]) != null ? ref$.cast : void 8) || types[type];
if (!castFunc) {
throw new Error("Type not defined: " + type + ".");
}
return castFunc(node, options, typesCast);
} else {
switch (structure) {
case 'array':
return castArray(node, typeObj, options);
case 'tuple':
return castTuple(node, typeObj, options);
case 'fields':
return castFields(node, typeObj, options);
}
}
}
function typesCast(node, types, options){
var i$, len$, type, ref$, valueType, value;
for (i$ = 0, len$ = types.length; i$ < len$; ++i$) {
type = types[i$];
ref$ = typeCast(node, type, options), valueType = ref$.type, value = ref$.value;
if (valueType === 'Nothing') {
continue;
}
if (parsedTypeCheck([type], value, {
customTypes: options.customTypes
})) {
return value;
}
}
throw new Error("Value " + JSON.stringify(node) + " does not type check against " + JSON.stringify(types) + ".");
}
module.exports = typesCast;
}).call(this);

View File

@@ -0,0 +1,285 @@
// Generated by LiveScript 1.2.0
(function(){
var parsedTypeCheck, types, toString$ = {}.toString;
parsedTypeCheck = require('type-check').parsedTypeCheck;
types = {
'*': function(it){
switch (toString$.call(it).slice(8, -1)) {
case 'Array':
return coerceType(it, {
type: 'Array'
});
case 'Object':
return coerceType(it, {
type: 'Object'
});
default:
return {
type: 'Just',
value: coerceTypes(it, [
{
type: 'Undefined'
}, {
type: 'Null'
}, {
type: 'NaN'
}, {
type: 'Boolean'
}, {
type: 'Number'
}, {
type: 'Date'
}, {
type: 'RegExp'
}, {
type: 'Array'
}, {
type: 'Object'
}, {
type: 'String'
}
], {
explicit: true
})
};
}
},
Undefined: function(it){
if (it === 'undefined' || it === void 8) {
return {
type: 'Just',
value: void 8
};
} else {
return {
type: 'Nothing'
};
}
},
Null: function(it){
if (it === 'null') {
return {
type: 'Just',
value: null
};
} else {
return {
type: 'Nothing'
};
}
},
NaN: function(it){
if (it === 'NaN') {
return {
type: 'Just',
value: NaN
};
} else {
return {
type: 'Nothing'
};
}
},
Boolean: function(it){
if (it === 'true') {
return {
type: 'Just',
value: true
};
} else if (it === 'false') {
return {
type: 'Just',
value: false
};
} else {
return {
type: 'Nothing'
};
}
},
Number: function(it){
return {
type: 'Just',
value: +it
};
},
Int: function(it){
return {
type: 'Just',
value: parseInt(it)
};
},
Float: function(it){
return {
type: 'Just',
value: parseFloat(it)
};
},
Date: function(value, options){
var that;
if (that = /^\#(.*)\#$/.exec(value)) {
return {
type: 'Just',
value: new Date(+that[1] || that[1])
};
} else if (options.explicit) {
return {
type: 'Nothing'
};
} else {
return {
type: 'Just',
value: new Date(+value || value)
};
}
},
RegExp: function(value, options){
var that;
if (that = /^\/(.*)\/([gimy]*)$/.exec(value)) {
return {
type: 'Just',
value: new RegExp(that[1], that[2])
};
} else if (options.explicit) {
return {
type: 'Nothing'
};
} else {
return {
type: 'Just',
value: new RegExp(value)
};
}
},
Array: function(it){
return coerceArray(it, {
of: [{
type: '*'
}]
});
},
Object: function(it){
return coerceFields(it, {
of: {}
});
},
String: function(it){
var that;
if (toString$.call(it).slice(8, -1) !== 'String') {
return {
type: 'Nothing'
};
}
if (that = it.match(/^'(.*)'$/)) {
return {
type: 'Just',
value: that[1]
};
} else if (that = it.match(/^"(.*)"$/)) {
return {
type: 'Just',
value: that[1]
};
} else {
return {
type: 'Just',
value: it
};
}
}
};
function coerceArray(node, type){
var typeOf, element;
if (toString$.call(node).slice(8, -1) !== 'Array') {
return {
type: 'Nothing'
};
}
typeOf = type.of;
return {
type: 'Just',
value: (function(){
var i$, ref$, len$, results$ = [];
for (i$ = 0, len$ = (ref$ = node).length; i$ < len$; ++i$) {
element = ref$[i$];
results$.push(coerceTypes(element, typeOf));
}
return results$;
}())
};
}
function coerceTuple(node, type){
var result, i$, ref$, len$, i, types, that;
if (toString$.call(node).slice(8, -1) !== 'Array') {
return {
type: 'Nothing'
};
}
result = [];
for (i$ = 0, len$ = (ref$ = type.of).length; i$ < len$; ++i$) {
i = i$;
types = ref$[i$];
if (that = coerceTypes(node[i], types)) {
result.push(that);
}
}
return {
type: 'Just',
value: result
};
}
function coerceFields(node, type){
var typeOf, key, value;
if (toString$.call(node).slice(8, -1) !== 'Object') {
return {
type: 'Nothing'
};
}
typeOf = type.of;
return {
type: 'Just',
value: (function(){
var ref$, results$ = {};
for (key in ref$ = node) {
value = ref$[key];
results$[key] = coerceTypes(value, typeOf[key] || [{
type: '*'
}]);
}
return results$;
}())
};
}
function coerceType(node, typeObj, options){
var type, structure, coerceFunc;
type = typeObj.type, structure = typeObj.structure;
if (type) {
coerceFunc = types[type];
return coerceFunc(node, options);
} else {
switch (structure) {
case 'array':
return coerceArray(node, typeObj);
case 'tuple':
return coerceTuple(node, typeObj);
case 'fields':
return coerceFields(node, typeObj);
}
}
}
function coerceTypes(node, types, options){
var i$, len$, type, ref$, valueType, value;
for (i$ = 0, len$ = types.length; i$ < len$; ++i$) {
type = types[i$];
ref$ = coerceType(node, type, options), valueType = ref$.type, value = ref$.value;
if (valueType === 'Nothing') {
continue;
}
if (parsedTypeCheck([type], value)) {
return value;
}
}
throw new Error("Value " + JSON.stringify(node) + " does not type check against " + JSON.stringify(types) + ".");
}
module.exports = coerceTypes;
}).call(this);

View File

@@ -0,0 +1,22 @@
// Generated by LiveScript 1.4.0
(function(){
var parseString, cast, parseType, VERSION, parsedTypeParse, parse;
parseString = require('./parse-string');
cast = require('./cast');
parseType = require('type-check').parseType;
VERSION = '0.3.0';
parsedTypeParse = function(parsedType, string, options){
options == null && (options = {});
options.explicit == null && (options.explicit = false);
options.customTypes == null && (options.customTypes = {});
return cast(parseString(parsedType, string, options), parsedType, options);
};
parse = function(type, string, options){
return parsedTypeParse(parseType(type), string, options);
};
module.exports = {
VERSION: VERSION,
parse: parse,
parsedTypeParse: parsedTypeParse
};
}).call(this);

View File

@@ -0,0 +1,113 @@
// Generated by LiveScript 1.4.0
(function(){
var reject, special, tokenRegex;
reject = require('prelude-ls').reject;
function consumeOp(tokens, op){
if (tokens[0] === op) {
return tokens.shift();
} else {
throw new Error("Expected '" + op + "', but got '" + tokens[0] + "' instead in " + JSON.stringify(tokens) + ".");
}
}
function maybeConsumeOp(tokens, op){
if (tokens[0] === op) {
return tokens.shift();
}
}
function consumeList(tokens, arg$, hasDelimiters){
var open, close, result, untilTest;
open = arg$[0], close = arg$[1];
if (hasDelimiters) {
consumeOp(tokens, open);
}
result = [];
untilTest = "," + (hasDelimiters ? close : '');
while (tokens.length && (hasDelimiters && tokens[0] !== close)) {
result.push(consumeElement(tokens, untilTest));
maybeConsumeOp(tokens, ',');
}
if (hasDelimiters) {
consumeOp(tokens, close);
}
return result;
}
function consumeArray(tokens, hasDelimiters){
return consumeList(tokens, ['[', ']'], hasDelimiters);
}
function consumeTuple(tokens, hasDelimiters){
return consumeList(tokens, ['(', ')'], hasDelimiters);
}
function consumeFields(tokens, hasDelimiters){
var result, untilTest, key;
if (hasDelimiters) {
consumeOp(tokens, '{');
}
result = {};
untilTest = "," + (hasDelimiters ? '}' : '');
while (tokens.length && (!hasDelimiters || tokens[0] !== '}')) {
key = consumeValue(tokens, ':');
consumeOp(tokens, ':');
result[key] = consumeElement(tokens, untilTest);
maybeConsumeOp(tokens, ',');
}
if (hasDelimiters) {
consumeOp(tokens, '}');
}
return result;
}
function consumeValue(tokens, untilTest){
var out;
untilTest == null && (untilTest = '');
out = '';
while (tokens.length && -1 === untilTest.indexOf(tokens[0])) {
out += tokens.shift();
}
return out;
}
function consumeElement(tokens, untilTest){
switch (tokens[0]) {
case '[':
return consumeArray(tokens, true);
case '(':
return consumeTuple(tokens, true);
case '{':
return consumeFields(tokens, true);
default:
return consumeValue(tokens, untilTest);
}
}
function consumeTopLevel(tokens, types, options){
var ref$, type, structure, origTokens, result, finalResult, x$, y$;
ref$ = types[0], type = ref$.type, structure = ref$.structure;
origTokens = tokens.concat();
if (!options.explicit && types.length === 1 && ((!type && structure) || (type === 'Array' || type === 'Object'))) {
result = structure === 'array' || type === 'Array'
? consumeArray(tokens, tokens[0] === '[')
: structure === 'tuple'
? consumeTuple(tokens, tokens[0] === '(')
: consumeFields(tokens, tokens[0] === '{');
finalResult = tokens.length ? consumeElement(structure === 'array' || type === 'Array'
? (x$ = origTokens, x$.unshift('['), x$.push(']'), x$)
: (y$ = origTokens, y$.unshift('('), y$.push(')'), y$)) : result;
} else {
finalResult = consumeElement(tokens);
}
return finalResult;
}
special = /\[\]\(\)}{:,/.source;
tokenRegex = RegExp('("(?:\\\\"|[^"])*")|(\'(?:\\\\\'|[^\'])*\')|(/(?:\\\\/|[^/])*/[a-zA-Z]*)|(#.*#)|([' + special + '])|([^\\s' + special + '](?:\\s*[^\\s' + special + ']+)*)|\\s*');
module.exports = function(types, string, options){
var tokens, node;
options == null && (options = {});
if (!options.explicit && types.length === 1 && types[0].type === 'String') {
return "'" + string.replace(/\\'/g, "\\\\'") + "'";
}
tokens = reject(not$, string.split(tokenRegex));
node = consumeTopLevel(tokens, types, options);
if (!node) {
throw new Error("Error parsing '" + string + "'.");
}
return node;
};
function not$(x){ return !x; }
}).call(this);

View File

@@ -0,0 +1,102 @@
// Generated by LiveScript 1.2.0
(function(){
var reject, special, tokenRegex;
reject = require('prelude-ls').reject;
function consumeOp(tokens, op){
if (tokens[0] === op) {
return tokens.shift();
} else {
throw new Error("Expected '" + op + "', but got '" + tokens[0] + "' instead in " + JSON.stringify(tokens) + ".");
}
}
function maybeConsumeOp(tokens, op){
if (tokens[0] === op) {
return tokens.shift();
}
}
function consumeList(tokens, delimiters, hasDelimiters){
var result;
if (hasDelimiters) {
consumeOp(tokens, delimiters[0]);
}
result = [];
while (tokens.length && tokens[0] !== delimiters[1]) {
result.push(consumeElement(tokens));
maybeConsumeOp(tokens, ',');
}
if (hasDelimiters) {
consumeOp(tokens, delimiters[1]);
}
return result;
}
function consumeArray(tokens, hasDelimiters){
return consumeList(tokens, ['[', ']'], hasDelimiters);
}
function consumeTuple(tokens, hasDelimiters){
return consumeList(tokens, ['(', ')'], hasDelimiters);
}
function consumeFields(tokens, hasDelimiters){
var result, key;
if (hasDelimiters) {
consumeOp(tokens, '{');
}
result = {};
while (tokens.length && (!hasDelimiters || tokens[0] !== '}')) {
key = tokens.shift();
consumeOp(tokens, ':');
result[key] = consumeElement(tokens);
maybeConsumeOp(tokens, ',');
}
if (hasDelimiters) {
consumeOp(tokens, '}');
}
return result;
}
function consumeElement(tokens){
switch (tokens[0]) {
case '[':
return consumeArray(tokens, true);
case '(':
return consumeTuple(tokens, true);
case '{':
return consumeFields(tokens, true);
default:
return tokens.shift();
}
}
function consumeTopLevel(tokens, types){
var ref$, type, structure, origTokens, result, finalResult, x$, y$;
ref$ = types[0], type = ref$.type, structure = ref$.structure;
origTokens = tokens.concat();
if (types.length === 1 && (structure || (type === 'Array' || type === 'Object'))) {
result = structure === 'array' || type === 'Array'
? consumeArray(tokens, tokens[0] === '[')
: structure === 'tuple'
? consumeTuple(tokens, tokens[0] === '(')
: consumeFields(tokens, tokens[0] === '{');
finalResult = tokens.length ? consumeElement(structure === 'array' || type === 'Array'
? (x$ = origTokens, x$.unshift('['), x$.push(']'), x$)
: (y$ = origTokens, y$.unshift('('), y$.push(')'), y$)) : result;
} else {
finalResult = consumeElement(tokens);
}
if (tokens.length && origTokens.length) {
throw new Error("Unable to parse " + JSON.stringify(origTokens) + " of type " + JSON.stringify(types) + ".");
} else {
return finalResult;
}
}
special = /\[\]\(\)}{:,/.source;
tokenRegex = RegExp('("(?:[^"]|\\\\")*")|(\'(?:[^\']|\\\\\')*\')|(#.*#)|(/(?:\\\\/|[^/])*/[gimy]*)|([' + special + '])|([^\\s' + special + ']+)|\\s*');
module.exports = function(string, types){
var tokens, node;
tokens = reject(function(it){
return !it || /^\s+$/.test(it);
}, string.split(tokenRegex));
node = consumeTopLevel(tokens, types);
if (!node) {
throw new Error("Error parsing '" + string + "'.");
}
return node;
};
}).call(this);

View File

@@ -0,0 +1,47 @@
{
"name": "levn",
"version": "0.3.0",
"author": "George Zahariev <z@georgezahariev.com>",
"description": "Light ECMAScript (JavaScript) Value Notation - human written, concise, typed, flexible",
"homepage": "https://github.com/gkz/levn",
"keywords": [
"levn",
"light",
"ecmascript",
"value",
"notation",
"json",
"typed",
"human",
"concise",
"typed",
"flexible"
],
"files": [
"lib",
"README.md",
"LICENSE"
],
"main": "./lib/",
"bugs": "https://github.com/gkz/levn/issues",
"license": "MIT",
"engines": {
"node": ">= 0.8.0"
},
"repository": {
"type": "git",
"url": "git://github.com/gkz/levn.git"
},
"scripts": {
"test": "make test"
},
"dependencies": {
"prelude-ls": "~1.1.2",
"type-check": "~0.3.2"
},
"devDependencies": {
"livescript": "~1.4.0",
"mocha": "~2.3.4",
"istanbul": "~0.4.1"
}
}

View File

@@ -0,0 +1,56 @@
# 0.8.3
- changes dependency from `wordwrap` to `word-wrap` due to license issue
- update dependencies
# 0.8.2
- fix bug #18 - detect missing value when flag is last item
- update dependencies
# 0.8.1
- update `fast-levenshtein` dependency
# 0.8.0
- update `levn` dependency - supplying a float value to an option with type `Int` now throws an error, instead of silently converting to an `Int`
# 0.7.1
- fix bug with use of `defaults` and `concatRepeatedArrays` or `mergeRepeatedObjects`
# 0.7.0
- added `concatrepeatedarrays` option: `oneValuePerFlag`, only allows one array value per flag
- added `typeAliases` option
- added `parseArgv` which takes an array and parses with the first two items sliced off
- changed enum help style
- bug fixes (#12)
- use of `concatRepeatedArrays` and `mergeRepeatedObjects` at the top level is deprecated, use it as either a per-option option, or set them in the `defaults` object to set them for all objects
# 0.6.0
- added `defaults` lib-option flag, allowing one to set default properties for all options
- added `concatRepeatedArrays` and `mergeRepeatedObjects` as option level properties, allowing you to turn this feature on for specific options only
# 0.5.0
- `Boolean` flags with `default: 'true'`, and no short aliases, will by default show the `--no` version in help
# 0.4.0
- add `mergeRepeatedObjects` setting
# 0.3.0
- add `concatRepeatedArrays` setting
- add `overrideRequired` option setting
- use just Levenshtein string compare algo rather than Levenshtein Damerau to due dependency license issue
# 0.2.2
- bug fixes
# 0.2.1
- improved interpolation
- added changelog
# 0.2.0
- add dependency checks to options - added `dependsOn` as an option property
- add interpolation for `prepend` and `append` text with new `generateHelp` option, `interpolate`
# 0.1.1
- update dependencies
# 0.1.0
- initial release

View File

@@ -0,0 +1,22 @@
Copyright (c) George Zahariev
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.

View File

@@ -0,0 +1,238 @@
# Optionator
<a name="optionator" />
Optionator is a JavaScript/Node.js option parsing and help generation library used by [eslint](http://eslint.org), [Grasp](http://graspjs.com), [LiveScript](http://livescript.net), [esmangle](https://github.com/estools/esmangle), [escodegen](https://github.com/estools/escodegen), and [many more](https://www.npmjs.com/browse/depended/optionator).
For an online demo, check out the [Grasp online demo](http://www.graspjs.com/#demo).
[About](#about) &middot; [Usage](#usage) &middot; [Settings Format](#settings-format) &middot; [Argument Format](#argument-format)
## Why?
The problem with other option parsers, such as `yargs` or `minimist`, is they just accept all input, valid or not.
With Optionator, if you mistype an option, it will give you an error (with a suggestion for what you meant).
If you give the wrong type of argument for an option, it will give you an error rather than supplying the wrong input to your application.
$ cmd --halp
Invalid option '--halp' - perhaps you meant '--help'?
$ cmd --count str
Invalid value for option 'count' - expected type Int, received value: str.
Other helpful features include reformatting the help text based on the size of the console, so that it fits even if the console is narrow, and accepting not just an array (eg. process.argv), but a string or object as well, making things like testing much easier.
## About
Optionator uses [type-check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) behind the scenes to cast and verify input according the specified types.
MIT license. Version 0.8.3
npm install optionator
For updates on Optionator, [follow me on twitter](https://twitter.com/gkzahariev).
Optionator is a Node.js module, but can be used in the browser as well if packed with webpack/browserify.
## Usage
`require('optionator');` returns a function. It has one property, `VERSION`, the current version of the library as a string. This function is called with an object specifying your options and other information, see the [settings format section](#settings-format). This in turn returns an object with three properties, `parse`, `parseArgv`, `generateHelp`, and `generateHelpForOption`, which are all functions.
```js
var optionator = require('optionator')({
prepend: 'Usage: cmd [options]',
append: 'Version 1.0.0',
options: [{
option: 'help',
alias: 'h',
type: 'Boolean',
description: 'displays help'
}, {
option: 'count',
alias: 'c',
type: 'Int',
description: 'number of things',
example: 'cmd --count 2'
}]
});
var options = optionator.parseArgv(process.argv);
if (options.help) {
console.log(optionator.generateHelp());
}
...
```
### parse(input, parseOptions)
`parse` processes the `input` according to your settings, and returns an object with the results.
##### arguments
* input - `[String] | Object | String` - the input you wish to parse
* parseOptions - `{slice: Int}` - all options optional
- `slice` specifies how much to slice away from the beginning if the input is an array or string - by default `0` for string, `2` for array (works with `process.argv`)
##### returns
`Object` - the parsed options, each key is a camelCase version of the option name (specified in dash-case), and each value is the processed value for that option. Positional values are in an array under the `_` key.
##### example
```js
parse(['node', 't.js', '--count', '2', 'positional']); // {count: 2, _: ['positional']}
parse('--count 2 positional'); // {count: 2, _: ['positional']}
parse({count: 2, _:['positional']}); // {count: 2, _: ['positional']}
```
### parseArgv(input)
`parseArgv` works exactly like `parse`, but only for array input and it slices off the first two elements.
##### arguments
* input - `[String]` - the input you wish to parse
##### returns
See "returns" section in "parse"
##### example
```js
parseArgv(process.argv);
```
### generateHelp(helpOptions)
`generateHelp` produces help text based on your settings.
##### arguments
* helpOptions - `{showHidden: Boolean, interpolate: Object}` - all options optional
- `showHidden` specifies whether to show options with `hidden: true` specified, by default it is `false`
- `interpolate` specify data to be interpolated in `prepend` and `append` text, `{{key}}` is the format - eg. `generateHelp({interpolate:{version: '0.4.2'}})`, will change this `append` text: `Version {{version}}` to `Version 0.4.2`
##### returns
`String` - the generated help text
##### example
```js
generateHelp(); /*
"Usage: cmd [options] positional
-h, --help displays help
-c, --count Int number of things
Version 1.0.0
"*/
```
### generateHelpForOption(optionName)
`generateHelpForOption` produces expanded help text for the specified with `optionName` option. If an `example` was specified for the option, it will be displayed, and if a `longDescription` was specified, it will display that instead of the `description`.
##### arguments
* optionName - `String` - the name of the option to display
##### returns
`String` - the generated help text for the option
##### example
```js
generateHelpForOption('count'); /*
"-c, --count Int
description: number of things
example: cmd --count 2
"*/
```
## Settings Format
When your `require('optionator')`, you get a function that takes in a settings object. This object has the type:
{
prepend: String,
append: String,
options: [{heading: String} | {
option: String,
alias: [String] | String,
type: String,
enum: [String],
default: String,
restPositional: Boolean,
required: Boolean,
overrideRequired: Boolean,
dependsOn: [String] | String,
concatRepeatedArrays: Boolean | (Boolean, Object),
mergeRepeatedObjects: Boolean,
description: String,
longDescription: String,
example: [String] | String
}],
helpStyle: {
aliasSeparator: String,
typeSeparator: String,
descriptionSeparator: String,
initialIndent: Int,
secondaryIndent: Int,
maxPadFactor: Number
},
mutuallyExclusive: [[String | [String]]],
concatRepeatedArrays: Boolean | (Boolean, Object), // deprecated, set in defaults object
mergeRepeatedObjects: Boolean, // deprecated, set in defaults object
positionalAnywhere: Boolean,
typeAliases: Object,
defaults: Object
}
All of the properties are optional (the `Maybe` has been excluded for brevities sake), except for having either `heading: String` or `option: String` in each object in the `options` array.
### Top Level Properties
* `prepend` is an optional string to be placed before the options in the help text
* `append` is an optional string to be placed after the options in the help text
* `options` is a required array specifying your options and headings, the options and headings will be displayed in the order specified
* `helpStyle` is an optional object which enables you to change the default appearance of some aspects of the help text
* `mutuallyExclusive` is an optional array of arrays of either strings or arrays of strings. The top level array is a list of rules, each rule is a list of elements - each element can be either a string (the name of an option), or a list of strings (a group of option names) - there will be an error if more than one element is present
* `concatRepeatedArrays` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property
* `mergeRepeatedObjects` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property
* `positionalAnywhere` is an optional boolean (defaults to `true`) - when `true` it allows positional arguments anywhere, when `false`, all arguments after the first positional one are taken to be positional as well, even if they look like a flag. For example, with `positionalAnywhere: false`, the arguments `--flag --boom 12 --crack` would have two positional arguments: `12` and `--crack`
* `typeAliases` is an optional object, it allows you to set aliases for types, eg. `{Path: 'String'}` would allow you to use the type `Path` as an alias for the type `String`
* `defaults` is an optional object following the option properties format, which specifies default values for all options. A default will be overridden if manually set. For example, you can do `default: { type: "String" }` to set the default type of all options to `String`, and then override that default in an individual option by setting the `type` property
#### Heading Properties
* `heading` a required string, the name of the heading
#### Option Properties
* `option` the required name of the option - use dash-case, without the leading dashes
* `alias` is an optional string or array of strings which specify any aliases for the option
* `type` is a required string in the [type check](https://github.com/gkz/type-check) [format](https://github.com/gkz/type-check#type-format), this will be used to cast the inputted value and validate it
* `enum` is an optional array of strings, each string will be parsed by [levn](https://github.com/gkz/levn) - the argument value must be one of the resulting values - each potential value must validate against the specified `type`
* `default` is a optional string, which will be parsed by [levn](https://github.com/gkz/levn) and used as the default value if none is set - the value must validate against the specified `type`
* `restPositional` is an optional boolean - if set to `true`, everything after the option will be taken to be a positional argument, even if it looks like a named argument
* `required` is an optional boolean - if set to `true`, the option parsing will fail if the option is not defined
* `overrideRequired` is a optional boolean - if set to `true` and the option is used, and there is another option which is required but not set, it will override the need for the required option and there will be no error - this is useful if you have required options and want to use `--help` or `--version` flags
* `concatRepeatedArrays` is an optional boolean or tuple with boolean and options object (defaults to `false`) - when set to `true` and an option contains an array value and is repeated, the subsequent values for the flag will be appended rather than overwriting the original value - eg. option `g` of type `[String]`: `-g a -g b -g c,d` will result in `['a','b','c','d']`
You can supply an options object by giving the following value: `[true, options]`. The one currently supported option is `oneValuePerFlag`, this only allows one array value per flag. This is useful if your potential values contain a comma.
* `mergeRepeatedObjects` is an optional boolean (defaults to `false`) - when set to `true` and an option contains an object value and is repeated, the subsequent values for the flag will be merged rather than overwriting the original value - eg. option `g` of type `Object`: `-g a:1 -g b:2 -g c:3,d:4` will result in `{a: 1, b: 2, c: 3, d: 4}`
* `dependsOn` is an optional string or array of strings - if simply a string (the name of another option), it will make sure that that other option is set, if an array of strings, depending on whether `'and'` or `'or'` is first, it will either check whether all (`['and', 'option-a', 'option-b']`), or at least one (`['or', 'option-a', 'option-b']`) other options are set
* `description` is an optional string, which will be displayed next to the option in the help text
* `longDescription` is an optional string, it will be displayed instead of the `description` when `generateHelpForOption` is used
* `example` is an optional string or array of strings with example(s) for the option - these will be displayed when `generateHelpForOption` is used
#### Help Style Properties
* `aliasSeparator` is an optional string, separates multiple names from each other - default: ' ,'
* `typeSeparator` is an optional string, separates the type from the names - default: ' '
* `descriptionSeparator` is an optional string , separates the description from the padded name and type - default: ' '
* `initialIndent` is an optional int - the amount of indent for options - default: 2
* `secondaryIndent` is an optional int - the amount of indent if wrapped fully (in addition to the initial indent) - default: 4
* `maxPadFactor` is an optional number - affects the default level of padding for the names/type, it is multiplied by the average of the length of the names/type - default: 1.5
## Argument Format
At the highest level there are two types of arguments: named, and positional.
Name arguments of any length are prefixed with `--` (eg. `--go`), and those of one character may be prefixed with either `--` or `-` (eg. `-g`).
There are two types of named arguments: boolean flags (eg. `--problemo`, `-p`) which take no value and result in a `true` if they are present, the falsey `undefined` if they are not present, or `false` if present and explicitly prefixed with `no` (eg. `--no-problemo`). Named arguments with values (eg. `--tseries 800`, `-t 800`) are the other type. If the option has a type `Boolean` it will automatically be made into a boolean flag. Any other type results in a named argument that takes a value.
For more information about how to properly set types to get the value you want, take a look at the [type check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) pages.
You can group single character arguments that use a single `-`, however all except the last must be boolean flags (which take no value). The last may be a boolean flag, or an argument which takes a value - eg. `-ba 2` is equivalent to `-b -a 2`.
Positional arguments are all those values which do not fall under the above - they can be anywhere, not just at the end. For example, in `cmd -b one -a 2 two` where `b` is a boolean flag, and `a` has the type `Number`, there are two positional arguments, `one` and `two`.
Everything after an `--` is positional, even if it looks like a named argument.
You may optionally use `=` to separate option names from values, for example: `--count=2`.
If you specify the option `NUM`, then any argument using a single `-` followed by a number will be valid and will set the value of `NUM`. Eg. `-2` will be parsed into `NUM: 2`.
If duplicate named arguments are present, the last one will be taken.
## Technical About
`optionator` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [levn](https://github.com/gkz/levn) to cast arguments to their specified type, and uses [type-check](https://github.com/gkz/type-check) to validate values. It also uses the [prelude.ls](http://preludels.com/) library.

View File

@@ -0,0 +1,260 @@
// Generated by LiveScript 1.6.0
(function(){
var ref$, id, find, sort, min, max, map, unlines, nameToRaw, dasherize, naturalJoin, wordWrap, wordwrap, getPreText, setHelpStyleDefaults, generateHelpForOption, generateHelp;
ref$ = require('prelude-ls'), id = ref$.id, find = ref$.find, sort = ref$.sort, min = ref$.min, max = ref$.max, map = ref$.map, unlines = ref$.unlines;
ref$ = require('./util'), nameToRaw = ref$.nameToRaw, dasherize = ref$.dasherize, naturalJoin = ref$.naturalJoin;
wordWrap = require('word-wrap');
wordwrap = function(a, b){
var ref$, indent, width;
ref$ = b === undefined
? ['', a - 1]
: [repeatString$(' ', a), b - a - 1], indent = ref$[0], width = ref$[1];
return function(text){
return wordWrap(text, {
indent: indent,
width: width,
trim: true
});
};
};
getPreText = function(option, arg$, maxWidth){
var mainName, shortNames, ref$, longNames, type, description, aliasSeparator, typeSeparator, initialIndent, names, namesString, namesStringLen, typeSeparatorString, typeSeparatorStringLen, wrap;
mainName = option.option, shortNames = (ref$ = option.shortNames) != null
? ref$
: [], longNames = (ref$ = option.longNames) != null
? ref$
: [], type = option.type, description = option.description;
aliasSeparator = arg$.aliasSeparator, typeSeparator = arg$.typeSeparator, initialIndent = arg$.initialIndent;
if (option.negateName) {
mainName = "no-" + mainName;
if (longNames) {
longNames = map(function(it){
return "no-" + it;
}, longNames);
}
}
names = mainName.length === 1
? [mainName].concat(shortNames, longNames)
: shortNames.concat([mainName], longNames);
namesString = map(nameToRaw, names).join(aliasSeparator);
namesStringLen = namesString.length;
typeSeparatorString = mainName === 'NUM' ? '::' : typeSeparator;
typeSeparatorStringLen = typeSeparatorString.length;
if (maxWidth != null && !option.boolean && initialIndent + namesStringLen + typeSeparatorStringLen + type.length > maxWidth) {
wrap = wordwrap(initialIndent + namesStringLen + typeSeparatorStringLen, maxWidth);
return namesString + "" + typeSeparatorString + wrap(type).replace(/^\s+/, '');
} else {
return namesString + "" + (option.boolean
? ''
: typeSeparatorString + "" + type);
}
};
setHelpStyleDefaults = function(helpStyle){
helpStyle.aliasSeparator == null && (helpStyle.aliasSeparator = ', ');
helpStyle.typeSeparator == null && (helpStyle.typeSeparator = ' ');
helpStyle.descriptionSeparator == null && (helpStyle.descriptionSeparator = ' ');
helpStyle.initialIndent == null && (helpStyle.initialIndent = 2);
helpStyle.secondaryIndent == null && (helpStyle.secondaryIndent = 4);
helpStyle.maxPadFactor == null && (helpStyle.maxPadFactor = 1.5);
};
generateHelpForOption = function(getOption, arg$){
var stdout, helpStyle, ref$;
stdout = arg$.stdout, helpStyle = (ref$ = arg$.helpStyle) != null
? ref$
: {};
setHelpStyleDefaults(helpStyle);
return function(optionName){
var maxWidth, wrap, option, e, pre, defaultString, restPositionalString, description, fullDescription, that, preDescription, descriptionString, exampleString, examples, seperator;
maxWidth = stdout != null && stdout.isTTY ? stdout.columns - 1 : null;
wrap = maxWidth ? wordwrap(maxWidth) : id;
try {
option = getOption(dasherize(optionName));
} catch (e$) {
e = e$;
return e.message;
}
pre = getPreText(option, helpStyle);
defaultString = option['default'] && !option.negateName ? "\ndefault: " + option['default'] : '';
restPositionalString = option.restPositional ? 'Everything after this option is considered a positional argument, even if it looks like an option.' : '';
description = option.longDescription || option.description && sentencize(option.description);
fullDescription = description && restPositionalString
? description + " " + restPositionalString
: (that = description || restPositionalString) ? that : '';
preDescription = 'description:';
descriptionString = !fullDescription
? ''
: maxWidth && fullDescription.length - 1 - preDescription.length > maxWidth
? "\n" + preDescription + "\n" + wrap(fullDescription)
: "\n" + preDescription + " " + fullDescription;
exampleString = (that = option.example) ? (examples = [].concat(that), examples.length > 1
? "\nexamples:\n" + unlines(examples)
: "\nexample: " + examples[0]) : '';
seperator = defaultString || descriptionString || exampleString ? "\n" + repeatString$('=', pre.length) : '';
return pre + "" + seperator + defaultString + descriptionString + exampleString;
};
};
generateHelp = function(arg$){
var options, prepend, append, helpStyle, ref$, stdout, aliasSeparator, typeSeparator, descriptionSeparator, maxPadFactor, initialIndent, secondaryIndent;
options = arg$.options, prepend = arg$.prepend, append = arg$.append, helpStyle = (ref$ = arg$.helpStyle) != null
? ref$
: {}, stdout = arg$.stdout;
setHelpStyleDefaults(helpStyle);
aliasSeparator = helpStyle.aliasSeparator, typeSeparator = helpStyle.typeSeparator, descriptionSeparator = helpStyle.descriptionSeparator, maxPadFactor = helpStyle.maxPadFactor, initialIndent = helpStyle.initialIndent, secondaryIndent = helpStyle.secondaryIndent;
return function(arg$){
var ref$, showHidden, interpolate, maxWidth, output, out, data, optionCount, totalPreLen, preLens, i$, len$, item, that, pre, descParts, desc, preLen, sortedPreLens, maxPreLen, preLenMean, x, padAmount, descSepLen, fullWrapCount, partialWrapCount, descLen, totalLen, initialSpace, wrapAllFull, i, wrap;
ref$ = arg$ != null
? arg$
: {}, showHidden = ref$.showHidden, interpolate = ref$.interpolate;
maxWidth = stdout != null && stdout.isTTY ? stdout.columns - 1 : null;
output = [];
out = function(it){
return output.push(it != null ? it : '');
};
if (prepend) {
out(interpolate ? interp(prepend, interpolate) : prepend);
out();
}
data = [];
optionCount = 0;
totalPreLen = 0;
preLens = [];
for (i$ = 0, len$ = (ref$ = options).length; i$ < len$; ++i$) {
item = ref$[i$];
if (showHidden || !item.hidden) {
if (that = item.heading) {
data.push({
type: 'heading',
value: that
});
} else {
pre = getPreText(item, helpStyle, maxWidth);
descParts = [];
if ((that = item.description) != null) {
descParts.push(that);
}
if (that = item['enum']) {
descParts.push("either: " + naturalJoin(that));
}
if (item['default'] && !item.negateName) {
descParts.push("default: " + item['default']);
}
desc = descParts.join(' - ');
data.push({
type: 'option',
pre: pre,
desc: desc,
descLen: desc.length
});
preLen = pre.length;
optionCount++;
totalPreLen += preLen;
preLens.push(preLen);
}
}
}
sortedPreLens = sort(preLens);
maxPreLen = sortedPreLens[sortedPreLens.length - 1];
preLenMean = initialIndent + totalPreLen / optionCount;
x = optionCount > 2 ? min(preLenMean * maxPadFactor, maxPreLen) : maxPreLen;
for (i$ = sortedPreLens.length - 1; i$ >= 0; --i$) {
preLen = sortedPreLens[i$];
if (preLen <= x) {
padAmount = preLen;
break;
}
}
descSepLen = descriptionSeparator.length;
if (maxWidth != null) {
fullWrapCount = 0;
partialWrapCount = 0;
for (i$ = 0, len$ = data.length; i$ < len$; ++i$) {
item = data[i$];
if (item.type === 'option') {
pre = item.pre, desc = item.desc, descLen = item.descLen;
if (descLen === 0) {
item.wrap = 'none';
} else {
preLen = max(padAmount, pre.length) + initialIndent + descSepLen;
totalLen = preLen + descLen;
if (totalLen > maxWidth) {
if (descLen / 2.5 > maxWidth - preLen) {
fullWrapCount++;
item.wrap = 'full';
} else {
partialWrapCount++;
item.wrap = 'partial';
}
} else {
item.wrap = 'none';
}
}
}
}
}
initialSpace = repeatString$(' ', initialIndent);
wrapAllFull = optionCount > 1 && fullWrapCount + partialWrapCount * 0.5 > optionCount * 0.5;
for (i$ = 0, len$ = data.length; i$ < len$; ++i$) {
i = i$;
item = data[i$];
if (item.type === 'heading') {
if (i !== 0) {
out();
}
out(item.value + ":");
} else {
pre = item.pre, desc = item.desc, descLen = item.descLen, wrap = item.wrap;
if (maxWidth != null) {
if (wrapAllFull || wrap === 'full') {
wrap = wordwrap(initialIndent + secondaryIndent, maxWidth);
out(initialSpace + "" + pre + "\n" + wrap(desc));
continue;
} else if (wrap === 'partial') {
wrap = wordwrap(initialIndent + descSepLen + max(padAmount, pre.length), maxWidth);
out(initialSpace + "" + pad(pre, padAmount) + descriptionSeparator + wrap(desc).replace(/^\s+/, ''));
continue;
}
}
if (descLen === 0) {
out(initialSpace + "" + pre);
} else {
out(initialSpace + "" + pad(pre, padAmount) + descriptionSeparator + desc);
}
}
}
if (append) {
out();
out(interpolate ? interp(append, interpolate) : append);
}
return unlines(output);
};
};
function pad(str, num){
var len, padAmount;
len = str.length;
padAmount = num - len;
return str + "" + repeatString$(' ', padAmount > 0 ? padAmount : 0);
}
function sentencize(str){
var first, rest, period;
first = str.charAt(0).toUpperCase();
rest = str.slice(1);
period = /[\.!\?]$/.test(str) ? '' : '.';
return first + "" + rest + period;
}
function interp(string, object){
return string.replace(/{{([a-zA-Z$_][a-zA-Z$_0-9]*)}}/g, function(arg$, key){
var ref$;
return (ref$ = object[key]) != null
? ref$
: "{{" + key + "}}";
});
}
module.exports = {
generateHelp: generateHelp,
generateHelpForOption: generateHelpForOption
};
function repeatString$(str, n){
for (var r = ''; n > 0; (n >>= 1) && (str += str)) if (n & 1) r += str;
return r;
}
}).call(this);

View File

@@ -0,0 +1,465 @@
// Generated by LiveScript 1.6.0
(function(){
var VERSION, ref$, id, map, compact, any, groupBy, partition, chars, isItNaN, keys, Obj, camelize, deepIs, closestString, nameToRaw, dasherize, naturalJoin, generateHelp, generateHelpForOption, parsedTypeCheck, parseType, parseLevn, camelizeKeys, parseString, main, toString$ = {}.toString, slice$ = [].slice, arrayFrom$ = Array.from || function(x){return slice$.call(x);};
VERSION = '0.8.3';
ref$ = require('prelude-ls'), id = ref$.id, map = ref$.map, compact = ref$.compact, any = ref$.any, groupBy = ref$.groupBy, partition = ref$.partition, chars = ref$.chars, isItNaN = ref$.isItNaN, keys = ref$.keys, Obj = ref$.Obj, camelize = ref$.camelize;
deepIs = require('deep-is');
ref$ = require('./util'), closestString = ref$.closestString, nameToRaw = ref$.nameToRaw, dasherize = ref$.dasherize, naturalJoin = ref$.naturalJoin;
ref$ = require('./help'), generateHelp = ref$.generateHelp, generateHelpForOption = ref$.generateHelpForOption;
ref$ = require('type-check'), parsedTypeCheck = ref$.parsedTypeCheck, parseType = ref$.parseType;
parseLevn = require('levn').parsedTypeParse;
camelizeKeys = function(obj){
var key, value, resultObj$ = {};
for (key in obj) {
value = obj[key];
resultObj$[camelize(key)] = value;
}
return resultObj$;
};
parseString = function(string){
var assignOpt, regex, replaceRegex, result;
assignOpt = '--?[a-zA-Z][-a-z-A-Z0-9]*=';
regex = RegExp('(?:' + assignOpt + ')?(?:\'(?:\\\\\'|[^\'])+\'|"(?:\\\\"|[^"])+")|[^\'"\\s]+', 'g');
replaceRegex = RegExp('^(' + assignOpt + ')?[\'"]([\\s\\S]*)[\'"]$');
result = map(function(it){
return it.replace(replaceRegex, '$1$2');
}, string.match(regex) || []);
return result;
};
main = function(libOptions){
var opts, defaults, required, traverse, getOption, parse;
opts = {};
defaults = {};
required = [];
if (toString$.call(libOptions.stdout).slice(8, -1) === 'Undefined') {
libOptions.stdout = process.stdout;
}
libOptions.positionalAnywhere == null && (libOptions.positionalAnywhere = true);
libOptions.typeAliases == null && (libOptions.typeAliases = {});
libOptions.defaults == null && (libOptions.defaults = {});
if (libOptions.concatRepeatedArrays != null) {
libOptions.defaults.concatRepeatedArrays = libOptions.concatRepeatedArrays;
}
if (libOptions.mergeRepeatedObjects != null) {
libOptions.defaults.mergeRepeatedObjects = libOptions.mergeRepeatedObjects;
}
traverse = function(options){
var i$, len$, option, name, k, ref$, v, type, that, e, parsedPossibilities, parsedType, j$, len1$, possibility, rawDependsType, dependsOpts, dependsType, cra, alias, shortNames, longNames;
if (toString$.call(options).slice(8, -1) !== 'Array') {
throw new Error('No options defined.');
}
for (i$ = 0, len$ = options.length; i$ < len$; ++i$) {
option = options[i$];
if (option.heading == null) {
name = option.option;
if (opts[name] != null) {
throw new Error("Option '" + name + "' already defined.");
}
for (k in ref$ = libOptions.defaults) {
v = ref$[k];
option[k] == null && (option[k] = v);
}
if (option.type === 'Boolean') {
option.boolean == null && (option.boolean = true);
}
if (option.parsedType == null) {
if (!option.type) {
throw new Error("No type defined for option '" + name + "'.");
}
try {
type = (that = libOptions.typeAliases[option.type]) != null
? that
: option.type;
option.parsedType = parseType(type);
} catch (e$) {
e = e$;
throw new Error("Option '" + name + "': Error parsing type '" + option.type + "': " + e.message);
}
}
if (option['default']) {
try {
defaults[name] = parseLevn(option.parsedType, option['default']);
} catch (e$) {
e = e$;
throw new Error("Option '" + name + "': Error parsing default value '" + option['default'] + "' for type '" + option.type + "': " + e.message);
}
}
if (option['enum'] && !option.parsedPossiblities) {
parsedPossibilities = [];
parsedType = option.parsedType;
for (j$ = 0, len1$ = (ref$ = option['enum']).length; j$ < len1$; ++j$) {
possibility = ref$[j$];
try {
parsedPossibilities.push(parseLevn(parsedType, possibility));
} catch (e$) {
e = e$;
throw new Error("Option '" + name + "': Error parsing enum value '" + possibility + "' for type '" + option.type + "': " + e.message);
}
}
option.parsedPossibilities = parsedPossibilities;
}
if (that = option.dependsOn) {
if (that.length) {
ref$ = [].concat(option.dependsOn), rawDependsType = ref$[0], dependsOpts = slice$.call(ref$, 1);
dependsType = rawDependsType.toLowerCase();
if (dependsOpts.length) {
if (dependsType === 'and' || dependsType === 'or') {
option.dependsOn = [dependsType].concat(arrayFrom$(dependsOpts));
} else {
throw new Error("Option '" + name + "': If you have more than one dependency, you must specify either 'and' or 'or'");
}
} else {
if ((ref$ = dependsType.toLowerCase()) === 'and' || ref$ === 'or') {
option.dependsOn = null;
} else {
option.dependsOn = ['and', rawDependsType];
}
}
} else {
option.dependsOn = null;
}
}
if (option.required) {
required.push(name);
}
opts[name] = option;
if (option.concatRepeatedArrays != null) {
cra = option.concatRepeatedArrays;
if ('Boolean' === toString$.call(cra).slice(8, -1)) {
option.concatRepeatedArrays = [cra, {}];
} else if (cra.length === 1) {
option.concatRepeatedArrays = [cra[0], {}];
} else if (cra.length !== 2) {
throw new Error("Invalid setting for concatRepeatedArrays");
}
}
if (option.alias || option.aliases) {
if (name === 'NUM') {
throw new Error("-NUM option can't have aliases.");
}
if (option.alias) {
option.aliases == null && (option.aliases = [].concat(option.alias));
}
for (j$ = 0, len1$ = (ref$ = option.aliases).length; j$ < len1$; ++j$) {
alias = ref$[j$];
if (opts[alias] != null) {
throw new Error("Option '" + alias + "' already defined.");
}
opts[alias] = option;
}
ref$ = partition(fn$, option.aliases), shortNames = ref$[0], longNames = ref$[1];
option.shortNames == null && (option.shortNames = shortNames);
option.longNames == null && (option.longNames = longNames);
}
if ((!option.aliases || option.shortNames.length === 0) && option.type === 'Boolean' && option['default'] === 'true') {
option.negateName = true;
}
}
}
function fn$(it){
return it.length === 1;
}
};
traverse(libOptions.options);
getOption = function(name){
var opt, possiblyMeant;
opt = opts[name];
if (opt == null) {
possiblyMeant = closestString(keys(opts), name);
throw new Error("Invalid option '" + nameToRaw(name) + "'" + (possiblyMeant ? " - perhaps you meant '" + nameToRaw(possiblyMeant) + "'?" : '.'));
}
return opt;
};
parse = function(input, arg$){
var slice, obj, positional, restPositional, overrideRequired, prop, setValue, setDefaults, checkRequired, mutuallyExclusiveError, checkMutuallyExclusive, checkDependency, checkDependencies, checkProp, args, key, value, option, ref$, i$, len$, arg, that, result, short, argName, usingAssign, val, flags, len, j$, len1$, i, flag, opt, name, valPrime, negated, noedName;
slice = (arg$ != null
? arg$
: {}).slice;
obj = {};
positional = [];
restPositional = false;
overrideRequired = false;
prop = null;
setValue = function(name, value){
var opt, val, cra, e, currentType;
opt = getOption(name);
if (opt.boolean) {
val = value;
} else {
try {
cra = opt.concatRepeatedArrays;
if (cra != null && cra[0] && cra[1].oneValuePerFlag && opt.parsedType.length === 1 && opt.parsedType[0].structure === 'array') {
val = [parseLevn(opt.parsedType[0].of, value)];
} else {
val = parseLevn(opt.parsedType, value);
}
} catch (e$) {
e = e$;
throw new Error("Invalid value for option '" + name + "' - expected type " + opt.type + ", received value: " + value + ".");
}
if (opt['enum'] && !any(function(it){
return deepIs(it, val);
}, opt.parsedPossibilities)) {
throw new Error("Option " + name + ": '" + val + "' not one of " + naturalJoin(opt['enum']) + ".");
}
}
currentType = toString$.call(obj[name]).slice(8, -1);
if (obj[name] != null) {
if (opt.concatRepeatedArrays != null && opt.concatRepeatedArrays[0] && currentType === 'Array') {
obj[name] = obj[name].concat(val);
} else if (opt.mergeRepeatedObjects && currentType === 'Object') {
import$(obj[name], val);
} else {
obj[name] = val;
}
} else {
obj[name] = val;
}
if (opt.restPositional) {
restPositional = true;
}
if (opt.overrideRequired) {
overrideRequired = true;
}
};
setDefaults = function(){
var name, ref$, value;
for (name in ref$ = defaults) {
value = ref$[name];
if (obj[name] == null) {
obj[name] = value;
}
}
};
checkRequired = function(){
var i$, ref$, len$, name;
if (overrideRequired) {
return;
}
for (i$ = 0, len$ = (ref$ = required).length; i$ < len$; ++i$) {
name = ref$[i$];
if (!obj[name]) {
throw new Error("Option " + nameToRaw(name) + " is required.");
}
}
};
mutuallyExclusiveError = function(first, second){
throw new Error("The options " + nameToRaw(first) + " and " + nameToRaw(second) + " are mutually exclusive - you cannot use them at the same time.");
};
checkMutuallyExclusive = function(){
var rules, i$, len$, rule, present, j$, len1$, element, k$, len2$, opt;
rules = libOptions.mutuallyExclusive;
if (!rules) {
return;
}
for (i$ = 0, len$ = rules.length; i$ < len$; ++i$) {
rule = rules[i$];
present = null;
for (j$ = 0, len1$ = rule.length; j$ < len1$; ++j$) {
element = rule[j$];
if (toString$.call(element).slice(8, -1) === 'Array') {
for (k$ = 0, len2$ = element.length; k$ < len2$; ++k$) {
opt = element[k$];
if (opt in obj) {
if (present != null) {
mutuallyExclusiveError(present, opt);
} else {
present = opt;
break;
}
}
}
} else {
if (element in obj) {
if (present != null) {
mutuallyExclusiveError(present, element);
} else {
present = element;
}
}
}
}
}
};
checkDependency = function(option){
var dependsOn, type, targetOptionNames, i$, len$, targetOptionName, targetOption;
dependsOn = option.dependsOn;
if (!dependsOn || option.dependenciesMet) {
return true;
}
type = dependsOn[0], targetOptionNames = slice$.call(dependsOn, 1);
for (i$ = 0, len$ = targetOptionNames.length; i$ < len$; ++i$) {
targetOptionName = targetOptionNames[i$];
targetOption = obj[targetOptionName];
if (targetOption && checkDependency(targetOption)) {
if (type === 'or') {
return true;
}
} else if (type === 'and') {
throw new Error("The option '" + option.option + "' did not have its dependencies met.");
}
}
if (type === 'and') {
return true;
} else {
throw new Error("The option '" + option.option + "' did not meet any of its dependencies.");
}
};
checkDependencies = function(){
var name;
for (name in obj) {
checkDependency(opts[name]);
}
};
checkProp = function(){
if (prop) {
throw new Error("Value for '" + prop + "' of type '" + getOption(prop).type + "' required.");
}
};
switch (toString$.call(input).slice(8, -1)) {
case 'String':
args = parseString(input.slice(slice != null ? slice : 0));
break;
case 'Array':
args = input.slice(slice != null ? slice : 2);
break;
case 'Object':
obj = {};
for (key in input) {
value = input[key];
if (key !== '_') {
option = getOption(dasherize(key));
if (parsedTypeCheck(option.parsedType, value)) {
obj[option.option] = value;
} else {
throw new Error("Option '" + option.option + "': Invalid type for '" + value + "' - expected type '" + option.type + "'.");
}
}
}
checkMutuallyExclusive();
checkDependencies();
setDefaults();
checkRequired();
return ref$ = camelizeKeys(obj), ref$._ = input._ || [], ref$;
default:
throw new Error("Invalid argument to 'parse': " + input + ".");
}
for (i$ = 0, len$ = args.length; i$ < len$; ++i$) {
arg = args[i$];
if (arg === '--') {
restPositional = true;
} else if (restPositional) {
positional.push(arg);
} else {
if (that = arg.match(/^(--?)([a-zA-Z][-a-zA-Z0-9]*)(=)?(.*)?$/)) {
result = that;
checkProp();
short = result[1].length === 1;
argName = result[2];
usingAssign = result[3] != null;
val = result[4];
if (usingAssign && val == null) {
throw new Error("No value for '" + argName + "' specified.");
}
if (short) {
flags = chars(argName);
len = flags.length;
for (j$ = 0, len1$ = flags.length; j$ < len1$; ++j$) {
i = j$;
flag = flags[j$];
opt = getOption(flag);
name = opt.option;
if (restPositional) {
positional.push(flag);
} else if (i === len - 1) {
if (usingAssign) {
valPrime = opt.boolean ? parseLevn([{
type: 'Boolean'
}], val) : val;
setValue(name, valPrime);
} else if (opt.boolean) {
setValue(name, true);
} else {
prop = name;
}
} else if (opt.boolean) {
setValue(name, true);
} else {
throw new Error("Can't set argument '" + flag + "' when not last flag in a group of short flags.");
}
}
} else {
negated = false;
if (that = argName.match(/^no-(.+)$/)) {
negated = true;
noedName = that[1];
opt = getOption(noedName);
} else {
opt = getOption(argName);
}
name = opt.option;
if (opt.boolean) {
valPrime = usingAssign ? parseLevn([{
type: 'Boolean'
}], val) : true;
if (negated) {
setValue(name, !valPrime);
} else {
setValue(name, valPrime);
}
} else {
if (negated) {
throw new Error("Only use 'no-' prefix for Boolean options, not with '" + noedName + "'.");
}
if (usingAssign) {
setValue(name, val);
} else {
prop = name;
}
}
}
} else if (that = arg.match(/^-([0-9]+(?:\.[0-9]+)?)$/)) {
opt = opts.NUM;
if (!opt) {
throw new Error('No -NUM option defined.');
}
setValue(opt.option, that[1]);
} else {
if (prop) {
setValue(prop, arg);
prop = null;
} else {
positional.push(arg);
if (!libOptions.positionalAnywhere) {
restPositional = true;
}
}
}
}
}
checkProp();
checkMutuallyExclusive();
checkDependencies();
setDefaults();
checkRequired();
return ref$ = camelizeKeys(obj), ref$._ = positional, ref$;
};
return {
parse: parse,
parseArgv: function(it){
return parse(it, {
slice: 2
});
},
generateHelp: generateHelp(libOptions),
generateHelpForOption: generateHelpForOption(getOption, libOptions)
};
};
main.VERSION = VERSION;
module.exports = main;
function import$(obj, src){
var own = {}.hasOwnProperty;
for (var key in src) if (own.call(src, key)) obj[key] = src[key];
return obj;
}
}).call(this);

View File

@@ -0,0 +1,54 @@
// Generated by LiveScript 1.6.0
(function(){
var prelude, map, sortBy, fl, closestString, nameToRaw, dasherize, naturalJoin;
prelude = require('prelude-ls'), map = prelude.map, sortBy = prelude.sortBy;
fl = require('fast-levenshtein');
closestString = function(possibilities, input){
var distances, ref$, string, distance;
if (!possibilities.length) {
return;
}
distances = map(function(it){
var ref$, longer, shorter;
ref$ = input.length > it.length
? [input, it]
: [it, input], longer = ref$[0], shorter = ref$[1];
return {
string: it,
distance: fl.get(longer, shorter)
};
})(
possibilities);
ref$ = sortBy(function(it){
return it.distance;
}, distances)[0], string = ref$.string, distance = ref$.distance;
return string;
};
nameToRaw = function(name){
if (name.length === 1 || name === 'NUM') {
return "-" + name;
} else {
return "--" + name;
}
};
dasherize = function(string){
if (/^[A-Z]/.test(string)) {
return string;
} else {
return prelude.dasherize(string);
}
};
naturalJoin = function(array){
if (array.length < 3) {
return array.join(' or ');
} else {
return array.slice(0, -1).join(', ') + ", or " + array[array.length - 1];
}
};
module.exports = {
closestString: closestString,
nameToRaw: nameToRaw,
dasherize: dasherize,
naturalJoin: naturalJoin
};
}).call(this);

View File

@@ -0,0 +1,44 @@
{
"name": "optionator",
"version": "0.8.3",
"author": "George Zahariev <z@georgezahariev.com>",
"description": "option parsing and help generation",
"homepage": "https://github.com/gkz/optionator",
"keywords": [
"options",
"flags",
"option parsing",
"cli"
],
"files": [
"lib",
"README.md",
"LICENSE"
],
"main": "./lib/",
"bugs": "https://github.com/gkz/optionator/issues",
"license": "MIT",
"engines": {
"node": ">= 0.8.0"
},
"repository": {
"type": "git",
"url": "git://github.com/gkz/optionator.git"
},
"scripts": {
"test": "make test"
},
"dependencies": {
"prelude-ls": "~1.1.2",
"deep-is": "~0.1.3",
"word-wrap": "~1.2.3",
"type-check": "~0.3.2",
"levn": "~0.3.0",
"fast-levenshtein": "~2.0.6"
},
"devDependencies": {
"livescript": "~1.6.0",
"mocha": "~6.2.2",
"istanbul": "~0.4.5"
}
}

View File

@@ -0,0 +1,99 @@
# 1.1.2
- add `Func.memoize`
- fix `zip-all` and `zip-with-all` corner case (no input)
- build with LiveScript 1.4.0
# 1.1.1
- curry `unique-by`, `minimum-by`
# 1.1.0
- added `List` functions: `maximum-by`, `minimum-by`, `unique-by`
- added `List` functions: `at`, `elem-index`, `elem-indices`, `find-index`, `find-indices`
- added `Str` functions: `capitalize`, `camelize`, `dasherize`
- added `Func` function: `over` - eg. ``same-length = (==) `over` (.length)``
- exported `Str.repeat` through main `prelude` object
- fixed definition of `foldr` and `foldr1`, the new correct definition is backwards incompatible with the old, incorrect one
- fixed issue with `fix`
- improved code coverage
# 1.0.3
- build browser versions
# 1.0.2
- bug fix for `flatten` - slight change with bug fix, flattens arrays only, not array-like objects
# 1.0.1
- bug fixes for `drop-while` and `take-while`
# 1.0.0
* massive update - separated functions into separate modules
* functions do not accept multiple types anymore - use different versions in their respective modules in some cases (eg. `Obj.map`), or use `chars` or `values` in other cases to transform into a list
* objects are no longer transformed into functions, simply use `(obj.)` in LiveScript to do that
* browser version now using browserify - use `prelude = require('prelude-ls')`
* added `compact`, `split`, `flatten`, `difference`, `intersection`, `union`, `count-by`, `group-by`, `chars`, `unchars`, `apply`
* added `lists-to-obj` which takes a list of keys and list of values and zips them up into an object, and the converse `obj-to-lists`
* added `pairs-to-obj` which takes a list of pairs (2 element lists) and creates an object, and the converse `obj-to-pairs`
* removed `cons`, `append` - use the concat operator
* removed `compose` - use the compose operator
* removed `obj-to-func` - use partially applied access (eg. `(obj.)`)
* removed `length` - use `(.length)`
* `sort-by` renamed to `sort-with`
* added new `sort-by`
* removed `compare` - just use the new `sort-by`
* `break-it` renamed `break-list`, (`Str.break-str` for the string version)
* added `Str.repeat` which creates a new string by repeating the input n times
* `unfold` as alias to `unfoldr` is no longer used
* fixed up style and compiled with LiveScript 1.1.1
* use Make instead of Slake
* greatly improved tests
# 0.6.0
* fixed various bugs
* added `fix`, a fixpoint (Y combinator) for anonymous recursive functions
* added `unfoldr` (alias `unfold`)
* calling `replicate` with a string now returns a list of strings
* removed `partial`, just use native partial application in LiveScript using the `_` placeholder, or currying
* added `sort`, `sortBy`, and `compare`
# 0.5.0
* removed `lookup` - use (.prop)
* removed `call` - use (.func arg1, arg2)
* removed `pluck` - use map (.prop), xs
* fixed buys wtih `head` and `last`
* added non-minifed browser version, as `prelude-browser.js`
* renamed `prelude-min.js` to `prelude-browser-min.js`
* renamed `zip` to `zipAll`
* renamed `zipWith` to `zipAllWith`
* added `zip`, a curried zip that takes only two arguments
* added `zipWith`, a curried zipWith that takes only two arguments
# 0.4.0
* added `parition` function
* added `curry` function
* removed `elem` function (use `in`)
* removed `notElem` function (use `not in`)
# 0.3.0
* added `listToObject`
* added `unique`
* added `objToFunc`
* added support for using strings in map and the like
* added support for using objects in map and the like
* added ability to use objects instead of functions in certain cases
* removed `error` (just use throw)
* added `tau` constant
* added `join`
* added `values`
* added `keys`
* added `partial`
* renamed `log` to `ln`
* added alias to `head`: `first`
* added `installPrelude` helper
# 0.2.0
* removed functions that simply warp operators as you can now use operators as functions in LiveScript
* `min/max` are now curried and take only 2 arguments
* added `call`
# 0.1.0
* initial public release

View File

@@ -0,0 +1,22 @@
Copyright (c) George Zahariev
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.

View File

@@ -0,0 +1,15 @@
# prelude.ls [![Build Status](https://travis-ci.org/gkz/prelude-ls.png?branch=master)](https://travis-ci.org/gkz/prelude-ls)
is a functionally oriented utility library. It is powerful and flexible. Almost all of its functions are curried. It is written in, and is the recommended base library for, <a href="http://livescript.net">LiveScript</a>.
See **[the prelude.ls site](http://preludels.com)** for examples, a reference, and more.
You can install via npm `npm install prelude-ls`
### Development
`make test` to test
`make build` to build `lib` from `src`
`make build-browser` to build browser versions

View File

@@ -0,0 +1,65 @@
// Generated by LiveScript 1.4.0
var apply, curry, flip, fix, over, memoize, slice$ = [].slice, toString$ = {}.toString;
apply = curry$(function(f, list){
return f.apply(null, list);
});
curry = function(f){
return curry$(f);
};
flip = curry$(function(f, x, y){
return f(y, x);
});
fix = function(f){
return function(g){
return function(){
return f(g(g)).apply(null, arguments);
};
}(function(g){
return function(){
return f(g(g)).apply(null, arguments);
};
});
};
over = curry$(function(f, g, x, y){
return f(g(x), g(y));
});
memoize = function(f){
var memo;
memo = {};
return function(){
var args, key, arg;
args = slice$.call(arguments);
key = (function(){
var i$, ref$, len$, results$ = [];
for (i$ = 0, len$ = (ref$ = args).length; i$ < len$; ++i$) {
arg = ref$[i$];
results$.push(arg + toString$.call(arg).slice(8, -1));
}
return results$;
}()).join('');
return memo[key] = key in memo
? memo[key]
: f.apply(null, args);
};
};
module.exports = {
curry: curry,
flip: flip,
fix: fix,
apply: apply,
over: over,
memoize: memoize
};
function curry$(f, bound){
var context,
_curry = function(args) {
return f.length > 1 ? function(){
var params = args ? args.concat() : [];
context = bound ? context || this : this;
return params.push.apply(params, arguments) <
f.length && arguments.length ?
_curry.call(context, params) : f.apply(context, params);
} : f;
};
return _curry();
}

View File

@@ -0,0 +1,686 @@
// Generated by LiveScript 1.4.0
var each, map, compact, filter, reject, partition, find, head, first, tail, last, initial, empty, reverse, unique, uniqueBy, fold, foldl, fold1, foldl1, foldr, foldr1, unfoldr, concat, concatMap, flatten, difference, intersection, union, countBy, groupBy, andList, orList, any, all, sort, sortWith, sortBy, sum, product, mean, average, maximum, minimum, maximumBy, minimumBy, scan, scanl, scan1, scanl1, scanr, scanr1, slice, take, drop, splitAt, takeWhile, dropWhile, span, breakList, zip, zipWith, zipAll, zipAllWith, at, elemIndex, elemIndices, findIndex, findIndices, toString$ = {}.toString, slice$ = [].slice;
each = curry$(function(f, xs){
var i$, len$, x;
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
f(x);
}
return xs;
});
map = curry$(function(f, xs){
var i$, len$, x, results$ = [];
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
results$.push(f(x));
}
return results$;
});
compact = function(xs){
var i$, len$, x, results$ = [];
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
if (x) {
results$.push(x);
}
}
return results$;
};
filter = curry$(function(f, xs){
var i$, len$, x, results$ = [];
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
if (f(x)) {
results$.push(x);
}
}
return results$;
});
reject = curry$(function(f, xs){
var i$, len$, x, results$ = [];
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
if (!f(x)) {
results$.push(x);
}
}
return results$;
});
partition = curry$(function(f, xs){
var passed, failed, i$, len$, x;
passed = [];
failed = [];
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
(f(x) ? passed : failed).push(x);
}
return [passed, failed];
});
find = curry$(function(f, xs){
var i$, len$, x;
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
if (f(x)) {
return x;
}
}
});
head = first = function(xs){
return xs[0];
};
tail = function(xs){
if (!xs.length) {
return;
}
return xs.slice(1);
};
last = function(xs){
return xs[xs.length - 1];
};
initial = function(xs){
if (!xs.length) {
return;
}
return xs.slice(0, -1);
};
empty = function(xs){
return !xs.length;
};
reverse = function(xs){
return xs.concat().reverse();
};
unique = function(xs){
var result, i$, len$, x;
result = [];
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
if (!in$(x, result)) {
result.push(x);
}
}
return result;
};
uniqueBy = curry$(function(f, xs){
var seen, i$, len$, x, val, results$ = [];
seen = [];
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
val = f(x);
if (in$(val, seen)) {
continue;
}
seen.push(val);
results$.push(x);
}
return results$;
});
fold = foldl = curry$(function(f, memo, xs){
var i$, len$, x;
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
memo = f(memo, x);
}
return memo;
});
fold1 = foldl1 = curry$(function(f, xs){
return fold(f, xs[0], xs.slice(1));
});
foldr = curry$(function(f, memo, xs){
var i$, x;
for (i$ = xs.length - 1; i$ >= 0; --i$) {
x = xs[i$];
memo = f(x, memo);
}
return memo;
});
foldr1 = curry$(function(f, xs){
return foldr(f, xs[xs.length - 1], xs.slice(0, -1));
});
unfoldr = curry$(function(f, b){
var result, x, that;
result = [];
x = b;
while ((that = f(x)) != null) {
result.push(that[0]);
x = that[1];
}
return result;
});
concat = function(xss){
return [].concat.apply([], xss);
};
concatMap = curry$(function(f, xs){
var x;
return [].concat.apply([], (function(){
var i$, ref$, len$, results$ = [];
for (i$ = 0, len$ = (ref$ = xs).length; i$ < len$; ++i$) {
x = ref$[i$];
results$.push(f(x));
}
return results$;
}()));
});
flatten = function(xs){
var x;
return [].concat.apply([], (function(){
var i$, ref$, len$, results$ = [];
for (i$ = 0, len$ = (ref$ = xs).length; i$ < len$; ++i$) {
x = ref$[i$];
if (toString$.call(x).slice(8, -1) === 'Array') {
results$.push(flatten(x));
} else {
results$.push(x);
}
}
return results$;
}()));
};
difference = function(xs){
var yss, results, i$, len$, x, j$, len1$, ys;
yss = slice$.call(arguments, 1);
results = [];
outer: for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
for (j$ = 0, len1$ = yss.length; j$ < len1$; ++j$) {
ys = yss[j$];
if (in$(x, ys)) {
continue outer;
}
}
results.push(x);
}
return results;
};
intersection = function(xs){
var yss, results, i$, len$, x, j$, len1$, ys;
yss = slice$.call(arguments, 1);
results = [];
outer: for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
for (j$ = 0, len1$ = yss.length; j$ < len1$; ++j$) {
ys = yss[j$];
if (!in$(x, ys)) {
continue outer;
}
}
results.push(x);
}
return results;
};
union = function(){
var xss, results, i$, len$, xs, j$, len1$, x;
xss = slice$.call(arguments);
results = [];
for (i$ = 0, len$ = xss.length; i$ < len$; ++i$) {
xs = xss[i$];
for (j$ = 0, len1$ = xs.length; j$ < len1$; ++j$) {
x = xs[j$];
if (!in$(x, results)) {
results.push(x);
}
}
}
return results;
};
countBy = curry$(function(f, xs){
var results, i$, len$, x, key;
results = {};
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
key = f(x);
if (key in results) {
results[key] += 1;
} else {
results[key] = 1;
}
}
return results;
});
groupBy = curry$(function(f, xs){
var results, i$, len$, x, key;
results = {};
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
key = f(x);
if (key in results) {
results[key].push(x);
} else {
results[key] = [x];
}
}
return results;
});
andList = function(xs){
var i$, len$, x;
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
if (!x) {
return false;
}
}
return true;
};
orList = function(xs){
var i$, len$, x;
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
if (x) {
return true;
}
}
return false;
};
any = curry$(function(f, xs){
var i$, len$, x;
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
if (f(x)) {
return true;
}
}
return false;
});
all = curry$(function(f, xs){
var i$, len$, x;
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
if (!f(x)) {
return false;
}
}
return true;
});
sort = function(xs){
return xs.concat().sort(function(x, y){
if (x > y) {
return 1;
} else if (x < y) {
return -1;
} else {
return 0;
}
});
};
sortWith = curry$(function(f, xs){
return xs.concat().sort(f);
});
sortBy = curry$(function(f, xs){
return xs.concat().sort(function(x, y){
if (f(x) > f(y)) {
return 1;
} else if (f(x) < f(y)) {
return -1;
} else {
return 0;
}
});
});
sum = function(xs){
var result, i$, len$, x;
result = 0;
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
result += x;
}
return result;
};
product = function(xs){
var result, i$, len$, x;
result = 1;
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
result *= x;
}
return result;
};
mean = average = function(xs){
var sum, i$, len$, x;
sum = 0;
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
sum += x;
}
return sum / xs.length;
};
maximum = function(xs){
var max, i$, ref$, len$, x;
max = xs[0];
for (i$ = 0, len$ = (ref$ = xs.slice(1)).length; i$ < len$; ++i$) {
x = ref$[i$];
if (x > max) {
max = x;
}
}
return max;
};
minimum = function(xs){
var min, i$, ref$, len$, x;
min = xs[0];
for (i$ = 0, len$ = (ref$ = xs.slice(1)).length; i$ < len$; ++i$) {
x = ref$[i$];
if (x < min) {
min = x;
}
}
return min;
};
maximumBy = curry$(function(f, xs){
var max, i$, ref$, len$, x;
max = xs[0];
for (i$ = 0, len$ = (ref$ = xs.slice(1)).length; i$ < len$; ++i$) {
x = ref$[i$];
if (f(x) > f(max)) {
max = x;
}
}
return max;
});
minimumBy = curry$(function(f, xs){
var min, i$, ref$, len$, x;
min = xs[0];
for (i$ = 0, len$ = (ref$ = xs.slice(1)).length; i$ < len$; ++i$) {
x = ref$[i$];
if (f(x) < f(min)) {
min = x;
}
}
return min;
});
scan = scanl = curry$(function(f, memo, xs){
var last, x;
last = memo;
return [memo].concat((function(){
var i$, ref$, len$, results$ = [];
for (i$ = 0, len$ = (ref$ = xs).length; i$ < len$; ++i$) {
x = ref$[i$];
results$.push(last = f(last, x));
}
return results$;
}()));
});
scan1 = scanl1 = curry$(function(f, xs){
if (!xs.length) {
return;
}
return scan(f, xs[0], xs.slice(1));
});
scanr = curry$(function(f, memo, xs){
xs = xs.concat().reverse();
return scan(f, memo, xs).reverse();
});
scanr1 = curry$(function(f, xs){
if (!xs.length) {
return;
}
xs = xs.concat().reverse();
return scan(f, xs[0], xs.slice(1)).reverse();
});
slice = curry$(function(x, y, xs){
return xs.slice(x, y);
});
take = curry$(function(n, xs){
if (n <= 0) {
return xs.slice(0, 0);
} else {
return xs.slice(0, n);
}
});
drop = curry$(function(n, xs){
if (n <= 0) {
return xs;
} else {
return xs.slice(n);
}
});
splitAt = curry$(function(n, xs){
return [take(n, xs), drop(n, xs)];
});
takeWhile = curry$(function(p, xs){
var len, i;
len = xs.length;
if (!len) {
return xs;
}
i = 0;
while (i < len && p(xs[i])) {
i += 1;
}
return xs.slice(0, i);
});
dropWhile = curry$(function(p, xs){
var len, i;
len = xs.length;
if (!len) {
return xs;
}
i = 0;
while (i < len && p(xs[i])) {
i += 1;
}
return xs.slice(i);
});
span = curry$(function(p, xs){
return [takeWhile(p, xs), dropWhile(p, xs)];
});
breakList = curry$(function(p, xs){
return span(compose$(p, not$), xs);
});
zip = curry$(function(xs, ys){
var result, len, i$, len$, i, x;
result = [];
len = ys.length;
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
i = i$;
x = xs[i$];
if (i === len) {
break;
}
result.push([x, ys[i]]);
}
return result;
});
zipWith = curry$(function(f, xs, ys){
var result, len, i$, len$, i, x;
result = [];
len = ys.length;
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
i = i$;
x = xs[i$];
if (i === len) {
break;
}
result.push(f(x, ys[i]));
}
return result;
});
zipAll = function(){
var xss, minLength, i$, len$, xs, ref$, i, lresult$, j$, results$ = [];
xss = slice$.call(arguments);
minLength = undefined;
for (i$ = 0, len$ = xss.length; i$ < len$; ++i$) {
xs = xss[i$];
minLength <= (ref$ = xs.length) || (minLength = ref$);
}
for (i$ = 0; i$ < minLength; ++i$) {
i = i$;
lresult$ = [];
for (j$ = 0, len$ = xss.length; j$ < len$; ++j$) {
xs = xss[j$];
lresult$.push(xs[i]);
}
results$.push(lresult$);
}
return results$;
};
zipAllWith = function(f){
var xss, minLength, i$, len$, xs, ref$, i, results$ = [];
xss = slice$.call(arguments, 1);
minLength = undefined;
for (i$ = 0, len$ = xss.length; i$ < len$; ++i$) {
xs = xss[i$];
minLength <= (ref$ = xs.length) || (minLength = ref$);
}
for (i$ = 0; i$ < minLength; ++i$) {
i = i$;
results$.push(f.apply(null, (fn$())));
}
return results$;
function fn$(){
var i$, ref$, len$, results$ = [];
for (i$ = 0, len$ = (ref$ = xss).length; i$ < len$; ++i$) {
xs = ref$[i$];
results$.push(xs[i]);
}
return results$;
}
};
at = curry$(function(n, xs){
if (n < 0) {
return xs[xs.length + n];
} else {
return xs[n];
}
});
elemIndex = curry$(function(el, xs){
var i$, len$, i, x;
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
i = i$;
x = xs[i$];
if (x === el) {
return i;
}
}
});
elemIndices = curry$(function(el, xs){
var i$, len$, i, x, results$ = [];
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
i = i$;
x = xs[i$];
if (x === el) {
results$.push(i);
}
}
return results$;
});
findIndex = curry$(function(f, xs){
var i$, len$, i, x;
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
i = i$;
x = xs[i$];
if (f(x)) {
return i;
}
}
});
findIndices = curry$(function(f, xs){
var i$, len$, i, x, results$ = [];
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
i = i$;
x = xs[i$];
if (f(x)) {
results$.push(i);
}
}
return results$;
});
module.exports = {
each: each,
map: map,
filter: filter,
compact: compact,
reject: reject,
partition: partition,
find: find,
head: head,
first: first,
tail: tail,
last: last,
initial: initial,
empty: empty,
reverse: reverse,
difference: difference,
intersection: intersection,
union: union,
countBy: countBy,
groupBy: groupBy,
fold: fold,
fold1: fold1,
foldl: foldl,
foldl1: foldl1,
foldr: foldr,
foldr1: foldr1,
unfoldr: unfoldr,
andList: andList,
orList: orList,
any: any,
all: all,
unique: unique,
uniqueBy: uniqueBy,
sort: sort,
sortWith: sortWith,
sortBy: sortBy,
sum: sum,
product: product,
mean: mean,
average: average,
concat: concat,
concatMap: concatMap,
flatten: flatten,
maximum: maximum,
minimum: minimum,
maximumBy: maximumBy,
minimumBy: minimumBy,
scan: scan,
scan1: scan1,
scanl: scanl,
scanl1: scanl1,
scanr: scanr,
scanr1: scanr1,
slice: slice,
take: take,
drop: drop,
splitAt: splitAt,
takeWhile: takeWhile,
dropWhile: dropWhile,
span: span,
breakList: breakList,
zip: zip,
zipWith: zipWith,
zipAll: zipAll,
zipAllWith: zipAllWith,
at: at,
elemIndex: elemIndex,
elemIndices: elemIndices,
findIndex: findIndex,
findIndices: findIndices
};
function curry$(f, bound){
var context,
_curry = function(args) {
return f.length > 1 ? function(){
var params = args ? args.concat() : [];
context = bound ? context || this : this;
return params.push.apply(params, arguments) <
f.length && arguments.length ?
_curry.call(context, params) : f.apply(context, params);
} : f;
};
return _curry();
}
function in$(x, xs){
var i = -1, l = xs.length >>> 0;
while (++i < l) if (x === xs[i]) return true;
return false;
}
function compose$() {
var functions = arguments;
return function() {
var i, result;
result = functions[0].apply(this, arguments);
for (i = 1; i < functions.length; ++i) {
result = functions[i](result);
}
return result;
};
}
function not$(x){ return !x; }

View File

@@ -0,0 +1,130 @@
// Generated by LiveScript 1.4.0
var max, min, negate, abs, signum, quot, rem, div, mod, recip, pi, tau, exp, sqrt, ln, pow, sin, tan, cos, asin, acos, atan, atan2, truncate, round, ceiling, floor, isItNaN, even, odd, gcd, lcm;
max = curry$(function(x$, y$){
return x$ > y$ ? x$ : y$;
});
min = curry$(function(x$, y$){
return x$ < y$ ? x$ : y$;
});
negate = function(x){
return -x;
};
abs = Math.abs;
signum = function(x){
if (x < 0) {
return -1;
} else if (x > 0) {
return 1;
} else {
return 0;
}
};
quot = curry$(function(x, y){
return ~~(x / y);
});
rem = curry$(function(x$, y$){
return x$ % y$;
});
div = curry$(function(x, y){
return Math.floor(x / y);
});
mod = curry$(function(x$, y$){
var ref$;
return (((x$) % (ref$ = y$) + ref$) % ref$);
});
recip = (function(it){
return 1 / it;
});
pi = Math.PI;
tau = pi * 2;
exp = Math.exp;
sqrt = Math.sqrt;
ln = Math.log;
pow = curry$(function(x$, y$){
return Math.pow(x$, y$);
});
sin = Math.sin;
tan = Math.tan;
cos = Math.cos;
asin = Math.asin;
acos = Math.acos;
atan = Math.atan;
atan2 = curry$(function(x, y){
return Math.atan2(x, y);
});
truncate = function(x){
return ~~x;
};
round = Math.round;
ceiling = Math.ceil;
floor = Math.floor;
isItNaN = function(x){
return x !== x;
};
even = function(x){
return x % 2 === 0;
};
odd = function(x){
return x % 2 !== 0;
};
gcd = curry$(function(x, y){
var z;
x = Math.abs(x);
y = Math.abs(y);
while (y !== 0) {
z = x % y;
x = y;
y = z;
}
return x;
});
lcm = curry$(function(x, y){
return Math.abs(Math.floor(x / gcd(x, y) * y));
});
module.exports = {
max: max,
min: min,
negate: negate,
abs: abs,
signum: signum,
quot: quot,
rem: rem,
div: div,
mod: mod,
recip: recip,
pi: pi,
tau: tau,
exp: exp,
sqrt: sqrt,
ln: ln,
pow: pow,
sin: sin,
tan: tan,
cos: cos,
acos: acos,
asin: asin,
atan: atan,
atan2: atan2,
truncate: truncate,
round: round,
ceiling: ceiling,
floor: floor,
isItNaN: isItNaN,
even: even,
odd: odd,
gcd: gcd,
lcm: lcm
};
function curry$(f, bound){
var context,
_curry = function(args) {
return f.length > 1 ? function(){
var params = args ? args.concat() : [];
context = bound ? context || this : this;
return params.push.apply(params, arguments) <
f.length && arguments.length ?
_curry.call(context, params) : f.apply(context, params);
} : f;
};
return _curry();
}

View File

@@ -0,0 +1,154 @@
// Generated by LiveScript 1.4.0
var values, keys, pairsToObj, objToPairs, listsToObj, objToLists, empty, each, map, compact, filter, reject, partition, find;
values = function(object){
var i$, x, results$ = [];
for (i$ in object) {
x = object[i$];
results$.push(x);
}
return results$;
};
keys = function(object){
var x, results$ = [];
for (x in object) {
results$.push(x);
}
return results$;
};
pairsToObj = function(object){
var i$, len$, x, resultObj$ = {};
for (i$ = 0, len$ = object.length; i$ < len$; ++i$) {
x = object[i$];
resultObj$[x[0]] = x[1];
}
return resultObj$;
};
objToPairs = function(object){
var key, value, results$ = [];
for (key in object) {
value = object[key];
results$.push([key, value]);
}
return results$;
};
listsToObj = curry$(function(keys, values){
var i$, len$, i, key, resultObj$ = {};
for (i$ = 0, len$ = keys.length; i$ < len$; ++i$) {
i = i$;
key = keys[i$];
resultObj$[key] = values[i];
}
return resultObj$;
});
objToLists = function(object){
var keys, values, key, value;
keys = [];
values = [];
for (key in object) {
value = object[key];
keys.push(key);
values.push(value);
}
return [keys, values];
};
empty = function(object){
var x;
for (x in object) {
return false;
}
return true;
};
each = curry$(function(f, object){
var i$, x;
for (i$ in object) {
x = object[i$];
f(x);
}
return object;
});
map = curry$(function(f, object){
var k, x, resultObj$ = {};
for (k in object) {
x = object[k];
resultObj$[k] = f(x);
}
return resultObj$;
});
compact = function(object){
var k, x, resultObj$ = {};
for (k in object) {
x = object[k];
if (x) {
resultObj$[k] = x;
}
}
return resultObj$;
};
filter = curry$(function(f, object){
var k, x, resultObj$ = {};
for (k in object) {
x = object[k];
if (f(x)) {
resultObj$[k] = x;
}
}
return resultObj$;
});
reject = curry$(function(f, object){
var k, x, resultObj$ = {};
for (k in object) {
x = object[k];
if (!f(x)) {
resultObj$[k] = x;
}
}
return resultObj$;
});
partition = curry$(function(f, object){
var passed, failed, k, x;
passed = {};
failed = {};
for (k in object) {
x = object[k];
(f(x) ? passed : failed)[k] = x;
}
return [passed, failed];
});
find = curry$(function(f, object){
var i$, x;
for (i$ in object) {
x = object[i$];
if (f(x)) {
return x;
}
}
});
module.exports = {
values: values,
keys: keys,
pairsToObj: pairsToObj,
objToPairs: objToPairs,
listsToObj: listsToObj,
objToLists: objToLists,
empty: empty,
each: each,
map: map,
filter: filter,
compact: compact,
reject: reject,
partition: partition,
find: find
};
function curry$(f, bound){
var context,
_curry = function(args) {
return f.length > 1 ? function(){
var params = args ? args.concat() : [];
context = bound ? context || this : this;
return params.push.apply(params, arguments) <
f.length && arguments.length ?
_curry.call(context, params) : f.apply(context, params);
} : f;
};
return _curry();
}

View File

@@ -0,0 +1,92 @@
// Generated by LiveScript 1.4.0
var split, join, lines, unlines, words, unwords, chars, unchars, reverse, repeat, capitalize, camelize, dasherize;
split = curry$(function(sep, str){
return str.split(sep);
});
join = curry$(function(sep, xs){
return xs.join(sep);
});
lines = function(str){
if (!str.length) {
return [];
}
return str.split('\n');
};
unlines = function(it){
return it.join('\n');
};
words = function(str){
if (!str.length) {
return [];
}
return str.split(/[ ]+/);
};
unwords = function(it){
return it.join(' ');
};
chars = function(it){
return it.split('');
};
unchars = function(it){
return it.join('');
};
reverse = function(str){
return str.split('').reverse().join('');
};
repeat = curry$(function(n, str){
var result, i$;
result = '';
for (i$ = 0; i$ < n; ++i$) {
result += str;
}
return result;
});
capitalize = function(str){
return str.charAt(0).toUpperCase() + str.slice(1);
};
camelize = function(it){
return it.replace(/[-_]+(.)?/g, function(arg$, c){
return (c != null ? c : '').toUpperCase();
});
};
dasherize = function(str){
return str.replace(/([^-A-Z])([A-Z]+)/g, function(arg$, lower, upper){
return lower + "-" + (upper.length > 1
? upper
: upper.toLowerCase());
}).replace(/^([A-Z]+)/, function(arg$, upper){
if (upper.length > 1) {
return upper + "-";
} else {
return upper.toLowerCase();
}
});
};
module.exports = {
split: split,
join: join,
lines: lines,
unlines: unlines,
words: words,
unwords: unwords,
chars: chars,
unchars: unchars,
reverse: reverse,
repeat: repeat,
capitalize: capitalize,
camelize: camelize,
dasherize: dasherize
};
function curry$(f, bound){
var context,
_curry = function(args) {
return f.length > 1 ? function(){
var params = args ? args.concat() : [];
context = bound ? context || this : this;
return params.push.apply(params, arguments) <
f.length && arguments.length ?
_curry.call(context, params) : f.apply(context, params);
} : f;
};
return _curry();
}

View File

@@ -0,0 +1,178 @@
// Generated by LiveScript 1.4.0
var Func, List, Obj, Str, Num, id, isType, replicate, prelude, toString$ = {}.toString;
Func = require('./Func.js');
List = require('./List.js');
Obj = require('./Obj.js');
Str = require('./Str.js');
Num = require('./Num.js');
id = function(x){
return x;
};
isType = curry$(function(type, x){
return toString$.call(x).slice(8, -1) === type;
});
replicate = curry$(function(n, x){
var i$, results$ = [];
for (i$ = 0; i$ < n; ++i$) {
results$.push(x);
}
return results$;
});
Str.empty = List.empty;
Str.slice = List.slice;
Str.take = List.take;
Str.drop = List.drop;
Str.splitAt = List.splitAt;
Str.takeWhile = List.takeWhile;
Str.dropWhile = List.dropWhile;
Str.span = List.span;
Str.breakStr = List.breakList;
prelude = {
Func: Func,
List: List,
Obj: Obj,
Str: Str,
Num: Num,
id: id,
isType: isType,
replicate: replicate
};
prelude.each = List.each;
prelude.map = List.map;
prelude.filter = List.filter;
prelude.compact = List.compact;
prelude.reject = List.reject;
prelude.partition = List.partition;
prelude.find = List.find;
prelude.head = List.head;
prelude.first = List.first;
prelude.tail = List.tail;
prelude.last = List.last;
prelude.initial = List.initial;
prelude.empty = List.empty;
prelude.reverse = List.reverse;
prelude.difference = List.difference;
prelude.intersection = List.intersection;
prelude.union = List.union;
prelude.countBy = List.countBy;
prelude.groupBy = List.groupBy;
prelude.fold = List.fold;
prelude.foldl = List.foldl;
prelude.fold1 = List.fold1;
prelude.foldl1 = List.foldl1;
prelude.foldr = List.foldr;
prelude.foldr1 = List.foldr1;
prelude.unfoldr = List.unfoldr;
prelude.andList = List.andList;
prelude.orList = List.orList;
prelude.any = List.any;
prelude.all = List.all;
prelude.unique = List.unique;
prelude.uniqueBy = List.uniqueBy;
prelude.sort = List.sort;
prelude.sortWith = List.sortWith;
prelude.sortBy = List.sortBy;
prelude.sum = List.sum;
prelude.product = List.product;
prelude.mean = List.mean;
prelude.average = List.average;
prelude.concat = List.concat;
prelude.concatMap = List.concatMap;
prelude.flatten = List.flatten;
prelude.maximum = List.maximum;
prelude.minimum = List.minimum;
prelude.maximumBy = List.maximumBy;
prelude.minimumBy = List.minimumBy;
prelude.scan = List.scan;
prelude.scanl = List.scanl;
prelude.scan1 = List.scan1;
prelude.scanl1 = List.scanl1;
prelude.scanr = List.scanr;
prelude.scanr1 = List.scanr1;
prelude.slice = List.slice;
prelude.take = List.take;
prelude.drop = List.drop;
prelude.splitAt = List.splitAt;
prelude.takeWhile = List.takeWhile;
prelude.dropWhile = List.dropWhile;
prelude.span = List.span;
prelude.breakList = List.breakList;
prelude.zip = List.zip;
prelude.zipWith = List.zipWith;
prelude.zipAll = List.zipAll;
prelude.zipAllWith = List.zipAllWith;
prelude.at = List.at;
prelude.elemIndex = List.elemIndex;
prelude.elemIndices = List.elemIndices;
prelude.findIndex = List.findIndex;
prelude.findIndices = List.findIndices;
prelude.apply = Func.apply;
prelude.curry = Func.curry;
prelude.flip = Func.flip;
prelude.fix = Func.fix;
prelude.over = Func.over;
prelude.split = Str.split;
prelude.join = Str.join;
prelude.lines = Str.lines;
prelude.unlines = Str.unlines;
prelude.words = Str.words;
prelude.unwords = Str.unwords;
prelude.chars = Str.chars;
prelude.unchars = Str.unchars;
prelude.repeat = Str.repeat;
prelude.capitalize = Str.capitalize;
prelude.camelize = Str.camelize;
prelude.dasherize = Str.dasherize;
prelude.values = Obj.values;
prelude.keys = Obj.keys;
prelude.pairsToObj = Obj.pairsToObj;
prelude.objToPairs = Obj.objToPairs;
prelude.listsToObj = Obj.listsToObj;
prelude.objToLists = Obj.objToLists;
prelude.max = Num.max;
prelude.min = Num.min;
prelude.negate = Num.negate;
prelude.abs = Num.abs;
prelude.signum = Num.signum;
prelude.quot = Num.quot;
prelude.rem = Num.rem;
prelude.div = Num.div;
prelude.mod = Num.mod;
prelude.recip = Num.recip;
prelude.pi = Num.pi;
prelude.tau = Num.tau;
prelude.exp = Num.exp;
prelude.sqrt = Num.sqrt;
prelude.ln = Num.ln;
prelude.pow = Num.pow;
prelude.sin = Num.sin;
prelude.tan = Num.tan;
prelude.cos = Num.cos;
prelude.acos = Num.acos;
prelude.asin = Num.asin;
prelude.atan = Num.atan;
prelude.atan2 = Num.atan2;
prelude.truncate = Num.truncate;
prelude.round = Num.round;
prelude.ceiling = Num.ceiling;
prelude.floor = Num.floor;
prelude.isItNaN = Num.isItNaN;
prelude.even = Num.even;
prelude.odd = Num.odd;
prelude.gcd = Num.gcd;
prelude.lcm = Num.lcm;
prelude.VERSION = '1.1.2';
module.exports = prelude;
function curry$(f, bound){
var context,
_curry = function(args) {
return f.length > 1 ? function(){
var params = args ? args.concat() : [];
context = bound ? context || this : this;
return params.push.apply(params, arguments) <
f.length && arguments.length ?
_curry.call(context, params) : f.apply(context, params);
} : f;
};
return _curry();
}

View File

@@ -0,0 +1,52 @@
{
"name": "prelude-ls",
"version": "1.1.2",
"author": "George Zahariev <z@georgezahariev.com>",
"description": "prelude.ls is a functionally oriented utility library. It is powerful and flexible. Almost all of its functions are curried. It is written in, and is the recommended base library for, LiveScript.",
"keywords": [
"prelude",
"livescript",
"utility",
"ls",
"coffeescript",
"javascript",
"library",
"functional",
"array",
"list",
"object",
"string"
],
"main": "lib/",
"files": [
"lib/",
"README.md",
"LICENSE"
],
"homepage": "http://preludels.com",
"bugs": "https://github.com/gkz/prelude-ls/issues",
"licenses": [
{
"type": "MIT",
"url": "https://raw.github.com/gkz/prelude-ls/master/LICENSE"
}
],
"engines": {
"node": ">= 0.8.0"
},
"repository": {
"type": "git",
"url": "git://github.com/gkz/prelude-ls.git"
},
"scripts": {
"test": "make test"
},
"devDependencies": {
"livescript": "~1.4.0",
"uglify-js": "~2.4.12",
"mocha": "~2.2.4",
"istanbul": "~0.2.4",
"browserify": "~3.24.13",
"sinon": "~1.10.2"
}
}

View File

@@ -0,0 +1,301 @@
# Change Log
## 0.5.6
* Fix for regression when people were using numbers as names in source maps. See
#236.
## 0.5.5
* Fix "regression" of unsupported, implementation behavior that half the world
happens to have come to depend on. See #235.
* Fix regression involving function hoisting in SpiderMonkey. See #233.
## 0.5.4
* Large performance improvements to source-map serialization. See #228 and #229.
## 0.5.3
* Do not include unnecessary distribution files. See
commit ef7006f8d1647e0a83fdc60f04f5a7ca54886f86.
## 0.5.2
* Include browser distributions of the library in package.json's `files`. See
issue #212.
## 0.5.1
* Fix latent bugs in IndexedSourceMapConsumer.prototype._parseMappings. See
ff05274becc9e6e1295ed60f3ea090d31d843379.
## 0.5.0
* Node 0.8 is no longer supported.
* Use webpack instead of dryice for bundling.
* Big speedups serializing source maps. See pull request #203.
* Fix a bug with `SourceMapConsumer.prototype.sourceContentFor` and sources that
explicitly start with the source root. See issue #199.
## 0.4.4
* Fix an issue where using a `SourceMapGenerator` after having created a
`SourceMapConsumer` from it via `SourceMapConsumer.fromSourceMap` failed. See
issue #191.
* Fix an issue with where `SourceMapGenerator` would mistakenly consider
different mappings as duplicates of each other and avoid generating them. See
issue #192.
## 0.4.3
* A very large number of performance improvements, particularly when parsing
source maps. Collectively about 75% of time shaved off of the source map
parsing benchmark!
* Fix a bug in `SourceMapConsumer.prototype.allGeneratedPositionsFor` and fuzzy
searching in the presence of a column option. See issue #177.
* Fix a bug with joining a source and its source root when the source is above
the root. See issue #182.
* Add the `SourceMapConsumer.prototype.hasContentsOfAllSources` method to
determine when all sources' contents are inlined into the source map. See
issue #190.
## 0.4.2
* Add an `.npmignore` file so that the benchmarks aren't pulled down by
dependent projects. Issue #169.
* Add an optional `column` argument to
`SourceMapConsumer.prototype.allGeneratedPositionsFor` and better handle lines
with no mappings. Issues #172 and #173.
## 0.4.1
* Fix accidentally defining a global variable. #170.
## 0.4.0
* The default direction for fuzzy searching was changed back to its original
direction. See #164.
* There is now a `bias` option you can supply to `SourceMapConsumer` to control
the fuzzy searching direction. See #167.
* About an 8% speed up in parsing source maps. See #159.
* Added a benchmark for parsing and generating source maps.
## 0.3.0
* Change the default direction that searching for positions fuzzes when there is
not an exact match. See #154.
* Support for environments using json2.js for JSON serialization. See #156.
## 0.2.0
* Support for consuming "indexed" source maps which do not have any remote
sections. See pull request #127. This introduces a minor backwards
incompatibility if you are monkey patching `SourceMapConsumer.prototype`
methods.
## 0.1.43
* Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue
#148 for some discussion and issues #150, #151, and #152 for implementations.
## 0.1.42
* Fix an issue where `SourceNode`s from different versions of the source-map
library couldn't be used in conjunction with each other. See issue #142.
## 0.1.41
* Fix a bug with getting the source content of relative sources with a "./"
prefix. See issue #145 and [Bug 1090768](bugzil.la/1090768).
* Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the
column span of each mapping.
* Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find
all generated positions associated with a given original source and line.
## 0.1.40
* Performance improvements for parsing source maps in SourceMapConsumer.
## 0.1.39
* Fix a bug where setting a source's contents to null before any source content
had been set before threw a TypeError. See issue #131.
## 0.1.38
* Fix a bug where finding relative paths from an empty path were creating
absolute paths. See issue #129.
## 0.1.37
* Fix a bug where if the source root was an empty string, relative source paths
would turn into absolute source paths. Issue #124.
## 0.1.36
* Allow the `names` mapping property to be an empty string. Issue #121.
## 0.1.35
* A third optional parameter was added to `SourceNode.fromStringWithSourceMap`
to specify a path that relative sources in the second parameter should be
relative to. Issue #105.
* If no file property is given to a `SourceMapGenerator`, then the resulting
source map will no longer have a `null` file property. The property will
simply not exist. Issue #104.
* Fixed a bug where consecutive newlines were ignored in `SourceNode`s.
Issue #116.
## 0.1.34
* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103.
* Fix bug involving source contents and the
`SourceMapGenerator.prototype.applySourceMap`. Issue #100.
## 0.1.33
* Fix some edge cases surrounding path joining and URL resolution.
* Add a third parameter for relative path to
`SourceMapGenerator.prototype.applySourceMap`.
* Fix issues with mappings and EOLs.
## 0.1.32
* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns
(issue 92).
* Fixed test runner to actually report number of failed tests as its process
exit code.
* Fixed a typo when reporting bad mappings (issue 87).
## 0.1.31
* Delay parsing the mappings in SourceMapConsumer until queried for a source
location.
* Support Sass source maps (which at the time of writing deviate from the spec
in small ways) in SourceMapConsumer.
## 0.1.30
* Do not join source root with a source, when the source is a data URI.
* Extend the test runner to allow running single specific test files at a time.
* Performance improvements in `SourceNode.prototype.walk` and
`SourceMapConsumer.prototype.eachMapping`.
* Source map browser builds will now work inside Workers.
* Better error messages when attempting to add an invalid mapping to a
`SourceMapGenerator`.
## 0.1.29
* Allow duplicate entries in the `names` and `sources` arrays of source maps
(usually from TypeScript) we are parsing. Fixes github issue 72.
## 0.1.28
* Skip duplicate mappings when creating source maps from SourceNode; github
issue 75.
## 0.1.27
* Don't throw an error when the `file` property is missing in SourceMapConsumer,
we don't use it anyway.
## 0.1.26
* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70.
## 0.1.25
* Make compatible with browserify
## 0.1.24
* Fix issue with absolute paths and `file://` URIs. See
https://bugzilla.mozilla.org/show_bug.cgi?id=885597
## 0.1.23
* Fix issue with absolute paths and sourcesContent, github issue 64.
## 0.1.22
* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21.
## 0.1.21
* Fixed handling of sources that start with a slash so that they are relative to
the source root's host.
## 0.1.20
* Fixed github issue #43: absolute URLs aren't joined with the source root
anymore.
## 0.1.19
* Using Travis CI to run tests.
## 0.1.18
* Fixed a bug in the handling of sourceRoot.
## 0.1.17
* Added SourceNode.fromStringWithSourceMap.
## 0.1.16
* Added missing documentation.
* Fixed the generating of empty mappings in SourceNode.
## 0.1.15
* Added SourceMapGenerator.applySourceMap.
## 0.1.14
* The sourceRoot is now handled consistently.
## 0.1.13
* Added SourceMapGenerator.fromSourceMap.
## 0.1.12
* SourceNode now generates empty mappings too.
## 0.1.11
* Added name support to SourceNode.
## 0.1.10
* Added sourcesContent support to the customer and generator.

View File

@@ -0,0 +1,28 @@
Copyright (c) 2009-2011, Mozilla Foundation 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.
* Neither the names of the Mozilla Foundation nor the names of project
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.

View File

@@ -0,0 +1,742 @@
# Source Map
[![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map)
[![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map)
This is a library to generate and consume the source map format
[described here][format].
[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
## Use with Node
$ npm install source-map
## Use on the Web
<script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script>
--------------------------------------------------------------------------------
<!-- `npm run toc` to regenerate the Table of Contents -->
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
## Table of Contents
- [Examples](#examples)
- [Consuming a source map](#consuming-a-source-map)
- [Generating a source map](#generating-a-source-map)
- [With SourceNode (high level API)](#with-sourcenode-high-level-api)
- [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api)
- [API](#api)
- [SourceMapConsumer](#sourcemapconsumer)
- [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap)
- [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans)
- [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition)
- [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition)
- [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition)
- [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources)
- [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing)
- [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order)
- [SourceMapGenerator](#sourcemapgenerator)
- [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap)
- [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer)
- [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping)
- [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent)
- [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath)
- [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring)
- [SourceNode](#sourcenode)
- [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name)
- [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath)
- [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk)
- [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk)
- [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent)
- [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn)
- [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn)
- [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep)
- [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement)
- [SourceNode.prototype.toString()](#sourcenodeprototypetostring)
- [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Examples
### Consuming a source map
```js
var rawSourceMap = {
version: 3,
file: 'min.js',
names: ['bar', 'baz', 'n'],
sources: ['one.js', 'two.js'],
sourceRoot: 'http://example.com/www/js/',
mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
};
var smc = new SourceMapConsumer(rawSourceMap);
console.log(smc.sources);
// [ 'http://example.com/www/js/one.js',
// 'http://example.com/www/js/two.js' ]
console.log(smc.originalPositionFor({
line: 2,
column: 28
}));
// { source: 'http://example.com/www/js/two.js',
// line: 2,
// column: 10,
// name: 'n' }
console.log(smc.generatedPositionFor({
source: 'http://example.com/www/js/two.js',
line: 2,
column: 10
}));
// { line: 2, column: 28 }
smc.eachMapping(function (m) {
// ...
});
```
### Generating a source map
In depth guide:
[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/)
#### With SourceNode (high level API)
```js
function compile(ast) {
switch (ast.type) {
case 'BinaryExpression':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
[compile(ast.left), " + ", compile(ast.right)]
);
case 'Literal':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
String(ast.value)
);
// ...
default:
throw new Error("Bad AST");
}
}
var ast = parse("40 + 2", "add.js");
console.log(compile(ast).toStringWithSourceMap({
file: 'add.js'
}));
// { code: '40 + 2',
// map: [object SourceMapGenerator] }
```
#### With SourceMapGenerator (low level API)
```js
var map = new SourceMapGenerator({
file: "source-mapped.js"
});
map.addMapping({
generated: {
line: 10,
column: 35
},
source: "foo.js",
original: {
line: 33,
column: 2
},
name: "christopher"
});
console.log(map.toString());
// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}'
```
## API
Get a reference to the module:
```js
// Node.js
var sourceMap = require('source-map');
// Browser builds
var sourceMap = window.sourceMap;
// Inside Firefox
const sourceMap = require("devtools/toolkit/sourcemap/source-map.js");
```
### SourceMapConsumer
A SourceMapConsumer instance represents a parsed source map which we can query
for information about the original file positions by giving it a file position
in the generated source.
#### new SourceMapConsumer(rawSourceMap)
The only parameter is the raw source map (either as a string which can be
`JSON.parse`'d, or an object). According to the spec, source maps have the
following attributes:
* `version`: Which version of the source map spec this map is following.
* `sources`: An array of URLs to the original source files.
* `names`: An array of identifiers which can be referenced by individual
mappings.
* `sourceRoot`: Optional. The URL root from which all sources are relative.
* `sourcesContent`: Optional. An array of contents of the original source files.
* `mappings`: A string of base64 VLQs which contain the actual mappings.
* `file`: Optional. The generated filename this source map is associated with.
```js
var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData);
```
#### SourceMapConsumer.prototype.computeColumnSpans()
Compute the last column for each generated mapping. The last column is
inclusive.
```js
// Before:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1 },
// { line: 2,
// column: 10 },
// { line: 2,
// column: 20 } ]
consumer.computeColumnSpans();
// After:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1,
// lastColumn: 9 },
// { line: 2,
// column: 10,
// lastColumn: 19 },
// { line: 2,
// column: 20,
// lastColumn: Infinity } ]
```
#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)
Returns the original source, line, and column information for the generated
source's line and column positions provided. The only argument is an object with
the following properties:
* `line`: The line number in the generated source. Line numbers in
this library are 1-based (note that the underlying source map
specification uses 0-based line numbers -- this library handles the
translation).
* `column`: The column number in the generated source. Column numbers
in this library are 0-based.
* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or
`SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest
element that is smaller than or greater than the one we are searching for,
respectively, if the exact element cannot be found. Defaults to
`SourceMapConsumer.GREATEST_LOWER_BOUND`.
and an object is returned with the following properties:
* `source`: The original source file, or null if this information is not
available.
* `line`: The line number in the original source, or null if this information is
not available. The line number is 1-based.
* `column`: The column number in the original source, or null if this
information is not available. The column number is 0-based.
* `name`: The original identifier, or null if this information is not available.
```js
consumer.originalPositionFor({ line: 2, column: 10 })
// { source: 'foo.coffee',
// line: 2,
// column: 2,
// name: null }
consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 })
// { source: null,
// line: null,
// column: null,
// name: null }
```
#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)
Returns the generated line and column information for the original source,
line, and column positions provided. The only argument is an object with
the following properties:
* `source`: The filename of the original source.
* `line`: The line number in the original source. The line number is
1-based.
* `column`: The column number in the original source. The column
number is 0-based.
and an object is returned with the following properties:
* `line`: The line number in the generated source, or null. The line
number is 1-based.
* `column`: The column number in the generated source, or null. The
column number is 0-based.
```js
consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 })
// { line: 1,
// column: 56 }
```
#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)
Returns all generated line and column information for the original source, line,
and column provided. If no column is provided, returns all mappings
corresponding to a either the line we are searching for or the next closest line
that has any mappings. Otherwise, returns all mappings corresponding to the
given line and either the column we are searching for or the next closest column
that has any offsets.
The only argument is an object with the following properties:
* `source`: The filename of the original source.
* `line`: The line number in the original source. The line number is
1-based.
* `column`: Optional. The column number in the original source. The
column number is 0-based.
and an array of objects is returned, each with the following properties:
* `line`: The line number in the generated source, or null. The line
number is 1-based.
* `column`: The column number in the generated source, or null. The
column number is 0-based.
```js
consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1 },
// { line: 2,
// column: 10 },
// { line: 2,
// column: 20 } ]
```
#### SourceMapConsumer.prototype.hasContentsOfAllSources()
Return true if we have the embedded source content for every source listed in
the source map, false otherwise.
In other words, if this method returns `true`, then
`consumer.sourceContentFor(s)` will succeed for every source `s` in
`consumer.sources`.
```js
// ...
if (consumer.hasContentsOfAllSources()) {
consumerReadyCallback(consumer);
} else {
fetchSources(consumer, consumerReadyCallback);
}
// ...
```
#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])
Returns the original source content for the source provided. The only
argument is the URL of the original source file.
If the source content for the given source is not found, then an error is
thrown. Optionally, pass `true` as the second param to have `null` returned
instead.
```js
consumer.sources
// [ "my-cool-lib.clj" ]
consumer.sourceContentFor("my-cool-lib.clj")
// "..."
consumer.sourceContentFor("this is not in the source map");
// Error: "this is not in the source map" is not in the source map
consumer.sourceContentFor("this is not in the source map", true);
// null
```
#### SourceMapConsumer.prototype.eachMapping(callback, context, order)
Iterate over each mapping between an original source/line/column and a
generated line/column in this source map.
* `callback`: The function that is called with each mapping. Mappings have the
form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,
name }`
* `context`: Optional. If specified, this object will be the value of `this`
every time that `callback` is called.
* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or
`SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over
the mappings sorted by the generated file's line/column order or the
original's source/line/column order, respectively. Defaults to
`SourceMapConsumer.GENERATED_ORDER`.
```js
consumer.eachMapping(function (m) { console.log(m); })
// ...
// { source: 'illmatic.js',
// generatedLine: 1,
// generatedColumn: 0,
// originalLine: 1,
// originalColumn: 0,
// name: null }
// { source: 'illmatic.js',
// generatedLine: 2,
// generatedColumn: 0,
// originalLine: 2,
// originalColumn: 0,
// name: null }
// ...
```
### SourceMapGenerator
An instance of the SourceMapGenerator represents a source map which is being
built incrementally.
#### new SourceMapGenerator([startOfSourceMap])
You may pass an object with the following properties:
* `file`: The filename of the generated source that this source map is
associated with.
* `sourceRoot`: A root for all relative URLs in this source map.
* `skipValidation`: Optional. When `true`, disables validation of mappings as
they are added. This can improve performance but should be used with
discretion, as a last resort. Even then, one should avoid using this flag when
running tests, if possible.
```js
var generator = new sourceMap.SourceMapGenerator({
file: "my-generated-javascript-file.js",
sourceRoot: "http://example.com/app/js/"
});
```
#### SourceMapGenerator.fromSourceMap(sourceMapConsumer)
Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance.
* `sourceMapConsumer` The SourceMap.
```js
var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer);
```
#### SourceMapGenerator.prototype.addMapping(mapping)
Add a single mapping from original source line and column to the generated
source's line and column for this source map being created. The mapping object
should have the following properties:
* `generated`: An object with the generated line and column positions.
* `original`: An object with the original line and column positions.
* `source`: The original source file (relative to the sourceRoot).
* `name`: An optional original token name for this mapping.
```js
generator.addMapping({
source: "module-one.scm",
original: { line: 128, column: 0 },
generated: { line: 3, column: 456 }
})
```
#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)
Set the source content for an original source file.
* `sourceFile` the URL of the original source file.
* `sourceContent` the content of the source file.
```js
generator.setSourceContent("module-one.scm",
fs.readFileSync("path/to/module-one.scm"))
```
#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])
Applies a SourceMap for a source file to the SourceMap.
Each mapping to the supplied source file is rewritten using the
supplied SourceMap. Note: The resolution for the resulting mappings
is the minimum of this map and the supplied map.
* `sourceMapConsumer`: The SourceMap to be applied.
* `sourceFile`: Optional. The filename of the source file.
If omitted, sourceMapConsumer.file will be used, if it exists.
Otherwise an error will be thrown.
* `sourceMapPath`: Optional. The dirname of the path to the SourceMap
to be applied. If relative, it is relative to the SourceMap.
This parameter is needed when the two SourceMaps aren't in the same
directory, and the SourceMap to be applied contains relative source
paths. If so, those relative source paths need to be rewritten
relative to the SourceMap.
If omitted, it is assumed that both SourceMaps are in the same directory,
thus not needing any rewriting. (Supplying `'.'` has the same effect.)
#### SourceMapGenerator.prototype.toString()
Renders the source map being generated to a string.
```js
generator.toString()
// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}'
```
### SourceNode
SourceNodes provide a way to abstract over interpolating and/or concatenating
snippets of generated JavaScript source code, while maintaining the line and
column information associated between those snippets and the original source
code. This is useful as the final intermediate representation a compiler might
use before outputting the generated JS and source map.
#### new SourceNode([line, column, source[, chunk[, name]]])
* `line`: The original line number associated with this source node, or null if
it isn't associated with an original line. The line number is 1-based.
* `column`: The original column number associated with this source node, or null
if it isn't associated with an original column. The column number
is 0-based.
* `source`: The original source's filename; null if no filename is provided.
* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
below.
* `name`: Optional. The original identifier.
```js
var node = new SourceNode(1, 2, "a.cpp", [
new SourceNode(3, 4, "b.cpp", "extern int status;\n"),
new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"),
new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"),
]);
```
#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])
Creates a SourceNode from generated code and a SourceMapConsumer.
* `code`: The generated code
* `sourceMapConsumer` The SourceMap for the generated code
* `relativePath` The optional path that relative sources in `sourceMapConsumer`
should be relative to.
```js
var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8"));
var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"),
consumer);
```
#### SourceNode.prototype.add(chunk)
Add a chunk of generated JS to this source node.
* `chunk`: A string snippet of generated JS code, another instance of
`SourceNode`, or an array where each member is one of those things.
```js
node.add(" + ");
node.add(otherNode);
node.add([leftHandOperandNode, " + ", rightHandOperandNode]);
```
#### SourceNode.prototype.prepend(chunk)
Prepend a chunk of generated JS to this source node.
* `chunk`: A string snippet of generated JS code, another instance of
`SourceNode`, or an array where each member is one of those things.
```js
node.prepend("/** Build Id: f783haef86324gf **/\n\n");
```
#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)
Set the source content for a source file. This will be added to the
`SourceMap` in the `sourcesContent` field.
* `sourceFile`: The filename of the source file
* `sourceContent`: The content of the source file
```js
node.setSourceContent("module-one.scm",
fs.readFileSync("path/to/module-one.scm"))
```
#### SourceNode.prototype.walk(fn)
Walk over the tree of JS snippets in this node and its children. The walking
function is called once for each snippet of JS and is passed that snippet and
the its original associated source's line/column location.
* `fn`: The traversal function.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.walk(function (code, loc) { console.log("WALK:", code, loc); })
// WALK: uno { source: 'b.js', line: 3, column: 4, name: null }
// WALK: dos { source: 'a.js', line: 1, column: 2, name: null }
// WALK: tres { source: 'a.js', line: 1, column: 2, name: null }
// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null }
```
#### SourceNode.prototype.walkSourceContents(fn)
Walk over the tree of SourceNodes. The walking function is called for each
source file content and is passed the filename and source content.
* `fn`: The traversal function.
```js
var a = new SourceNode(1, 2, "a.js", "generated from a");
a.setSourceContent("a.js", "original a");
var b = new SourceNode(1, 2, "b.js", "generated from b");
b.setSourceContent("b.js", "original b");
var c = new SourceNode(1, 2, "c.js", "generated from c");
c.setSourceContent("c.js", "original c");
var node = new SourceNode(null, null, null, [a, b, c]);
node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); })
// WALK: a.js : original a
// WALK: b.js : original b
// WALK: c.js : original c
```
#### SourceNode.prototype.join(sep)
Like `Array.prototype.join` except for SourceNodes. Inserts the separator
between each of this source node's children.
* `sep`: The separator.
```js
var lhs = new SourceNode(1, 2, "a.rs", "my_copy");
var operand = new SourceNode(3, 4, "a.rs", "=");
var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()");
var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]);
var joinedNode = node.join(" ");
```
#### SourceNode.prototype.replaceRight(pattern, replacement)
Call `String.prototype.replace` on the very right-most source snippet. Useful
for trimming white space from the end of a source node, etc.
* `pattern`: The pattern to replace.
* `replacement`: The thing to replace the pattern with.
```js
// Trim trailing white space.
node.replaceRight(/\s*$/, "");
```
#### SourceNode.prototype.toString()
Return the string representation of this source node. Walks over the tree and
concatenates all the various snippets together to one string.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.toString()
// 'unodostresquatro'
```
#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])
Returns the string representation of this tree of source nodes, plus a
SourceMapGenerator which contains all the mappings between the generated and
original sources.
The arguments are the same as those to `new SourceMapGenerator`.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.toStringWithSourceMap({ file: "my-output-file.js" })
// { code: 'unodostresquatro',
// map: [object SourceMapGenerator] }
```

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,121 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var util = require('./util');
var has = Object.prototype.hasOwnProperty;
var hasNativeMap = typeof Map !== "undefined";
/**
* A data structure which is a combination of an array and a set. Adding a new
* member is O(1), testing for membership is O(1), and finding the index of an
* element is O(1). Removing elements from the set is not supported. Only
* strings are supported for membership.
*/
function ArraySet() {
this._array = [];
this._set = hasNativeMap ? new Map() : Object.create(null);
}
/**
* Static method for creating ArraySet instances from an existing array.
*/
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
var set = new ArraySet();
for (var i = 0, len = aArray.length; i < len; i++) {
set.add(aArray[i], aAllowDuplicates);
}
return set;
};
/**
* Return how many unique items are in this ArraySet. If duplicates have been
* added, than those do not count towards the size.
*
* @returns Number
*/
ArraySet.prototype.size = function ArraySet_size() {
return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
};
/**
* Add the given string to this set.
*
* @param String aStr
*/
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
var idx = this._array.length;
if (!isDuplicate || aAllowDuplicates) {
this._array.push(aStr);
}
if (!isDuplicate) {
if (hasNativeMap) {
this._set.set(aStr, idx);
} else {
this._set[sStr] = idx;
}
}
};
/**
* Is the given string a member of this set?
*
* @param String aStr
*/
ArraySet.prototype.has = function ArraySet_has(aStr) {
if (hasNativeMap) {
return this._set.has(aStr);
} else {
var sStr = util.toSetString(aStr);
return has.call(this._set, sStr);
}
};
/**
* What is the index of the given string in the array?
*
* @param String aStr
*/
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
if (hasNativeMap) {
var idx = this._set.get(aStr);
if (idx >= 0) {
return idx;
}
} else {
var sStr = util.toSetString(aStr);
if (has.call(this._set, sStr)) {
return this._set[sStr];
}
}
throw new Error('"' + aStr + '" is not in the set.');
};
/**
* What is the element at the given index?
*
* @param Number aIdx
*/
ArraySet.prototype.at = function ArraySet_at(aIdx) {
if (aIdx >= 0 && aIdx < this._array.length) {
return this._array[aIdx];
}
throw new Error('No element indexed by ' + aIdx);
};
/**
* Returns the array representation of this set (which has the proper indices
* indicated by indexOf). Note that this is a copy of the internal array used
* for storing the members so that no one can mess with internal state.
*/
ArraySet.prototype.toArray = function ArraySet_toArray() {
return this._array.slice();
};
exports.ArraySet = ArraySet;

View File

@@ -0,0 +1,140 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*
* Based on the Base 64 VLQ implementation in Closure Compiler:
* https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
*
* Copyright 2011 The Closure Compiler Authors. 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.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 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 THE COPYRIGHT
* OWNER OR CONTRIBUTORS 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.
*/
var base64 = require('./base64');
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
// Continuation
// | Sign
// | |
// V V
// 101011
var VLQ_BASE_SHIFT = 5;
// binary: 100000
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// binary: 011111
var VLQ_BASE_MASK = VLQ_BASE - 1;
// binary: 100000
var VLQ_CONTINUATION_BIT = VLQ_BASE;
/**
* Converts from a two-complement value to a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
function toVLQSigned(aValue) {
return aValue < 0
? ((-aValue) << 1) + 1
: (aValue << 1) + 0;
}
/**
* Converts to a two-complement value from a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
*/
function fromVLQSigned(aValue) {
var isNegative = (aValue & 1) === 1;
var shifted = aValue >> 1;
return isNegative
? -shifted
: shifted;
}
/**
* Returns the base 64 VLQ encoded value.
*/
exports.encode = function base64VLQ_encode(aValue) {
var encoded = "";
var digit;
var vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit |= VLQ_CONTINUATION_BIT;
}
encoded += base64.encode(digit);
} while (vlq > 0);
return encoded;
};
/**
* Decodes the next base 64 VLQ value from the given string and returns the
* value and the rest of the string via the out parameter.
*/
exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
var strLen = aStr.length;
var result = 0;
var shift = 0;
var continuation, digit;
do {
if (aIndex >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = base64.decode(aStr.charCodeAt(aIndex++));
if (digit === -1) {
throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
}
continuation = !!(digit & VLQ_CONTINUATION_BIT);
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
aOutParam.value = fromVLQSigned(result);
aOutParam.rest = aIndex;
};

View File

@@ -0,0 +1,67 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
/**
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
*/
exports.encode = function (number) {
if (0 <= number && number < intToCharMap.length) {
return intToCharMap[number];
}
throw new TypeError("Must be between 0 and 63: " + number);
};
/**
* Decode a single base 64 character code digit to an integer. Returns -1 on
* failure.
*/
exports.decode = function (charCode) {
var bigA = 65; // 'A'
var bigZ = 90; // 'Z'
var littleA = 97; // 'a'
var littleZ = 122; // 'z'
var zero = 48; // '0'
var nine = 57; // '9'
var plus = 43; // '+'
var slash = 47; // '/'
var littleOffset = 26;
var numberOffset = 52;
// 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
if (bigA <= charCode && charCode <= bigZ) {
return (charCode - bigA);
}
// 26 - 51: abcdefghijklmnopqrstuvwxyz
if (littleA <= charCode && charCode <= littleZ) {
return (charCode - littleA + littleOffset);
}
// 52 - 61: 0123456789
if (zero <= charCode && charCode <= nine) {
return (charCode - zero + numberOffset);
}
// 62: +
if (charCode == plus) {
return 62;
}
// 63: /
if (charCode == slash) {
return 63;
}
// Invalid base64 digit.
return -1;
};

View File

@@ -0,0 +1,111 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.GREATEST_LOWER_BOUND = 1;
exports.LEAST_UPPER_BOUND = 2;
/**
* Recursive implementation of binary search.
*
* @param aLow Indices here and lower do not contain the needle.
* @param aHigh Indices here and higher do not contain the needle.
* @param aNeedle The element being searched for.
* @param aHaystack The non-empty array being searched.
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
*/
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
// This function terminates when one of the following is true:
//
// 1. We find the exact element we are looking for.
//
// 2. We did not find the exact element, but we can return the index of
// the next-closest element.
//
// 3. We did not find the exact element, and there is no next-closest
// element than the one we are searching for, so we return -1.
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
var cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
// Found the element we are looking for.
return mid;
}
else if (cmp > 0) {
// Our needle is greater than aHaystack[mid].
if (aHigh - mid > 1) {
// The element is in the upper half.
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
}
// The exact needle element was not found in this haystack. Determine if
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return aHigh < aHaystack.length ? aHigh : -1;
} else {
return mid;
}
}
else {
// Our needle is less than aHaystack[mid].
if (mid - aLow > 1) {
// The element is in the lower half.
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
}
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return mid;
} else {
return aLow < 0 ? -1 : aLow;
}
}
}
/**
* This is an implementation of binary search which will always try and return
* the index of the closest element if there is no exact hit. This is because
* mappings between original and generated line/col pairs are single points,
* and there is an implicit region between each of them, so a miss just means
* that you aren't on the very start of a region.
*
* @param aNeedle The element you are looking for.
* @param aHaystack The array that is being searched.
* @param aCompare A function which takes the needle and an element in the
* array and returns -1, 0, or 1 depending on whether the needle is less
* than, equal to, or greater than the element, respectively.
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
*/
exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
if (aHaystack.length === 0) {
return -1;
}
var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
aCompare, aBias || exports.GREATEST_LOWER_BOUND);
if (index < 0) {
return -1;
}
// We have found either the exact element, or the next-closest element than
// the one we are searching for. However, there may be more than one such
// element. Make sure we always return the smallest of these.
while (index - 1 >= 0) {
if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
break;
}
--index;
}
return index;
};

View File

@@ -0,0 +1,79 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2014 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var util = require('./util');
/**
* Determine whether mappingB is after mappingA with respect to generated
* position.
*/
function generatedPositionAfter(mappingA, mappingB) {
// Optimized for most common case
var lineA = mappingA.generatedLine;
var lineB = mappingB.generatedLine;
var columnA = mappingA.generatedColumn;
var columnB = mappingB.generatedColumn;
return lineB > lineA || lineB == lineA && columnB >= columnA ||
util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
}
/**
* A data structure to provide a sorted view of accumulated mappings in a
* performance conscious manner. It trades a neglibable overhead in general
* case for a large speedup in case of mappings being added in order.
*/
function MappingList() {
this._array = [];
this._sorted = true;
// Serves as infimum
this._last = {generatedLine: -1, generatedColumn: 0};
}
/**
* Iterate through internal items. This method takes the same arguments that
* `Array.prototype.forEach` takes.
*
* NOTE: The order of the mappings is NOT guaranteed.
*/
MappingList.prototype.unsortedForEach =
function MappingList_forEach(aCallback, aThisArg) {
this._array.forEach(aCallback, aThisArg);
};
/**
* Add the given source mapping.
*
* @param Object aMapping
*/
MappingList.prototype.add = function MappingList_add(aMapping) {
if (generatedPositionAfter(this._last, aMapping)) {
this._last = aMapping;
this._array.push(aMapping);
} else {
this._sorted = false;
this._array.push(aMapping);
}
};
/**
* Returns the flat, sorted array of mappings. The mappings are sorted by
* generated position.
*
* WARNING: This method returns internal data without copying, for
* performance. The return value must NOT be mutated, and should be treated as
* an immutable borrow. If you want to take ownership, you must make your own
* copy.
*/
MappingList.prototype.toArray = function MappingList_toArray() {
if (!this._sorted) {
this._array.sort(util.compareByGeneratedPositionsInflated);
this._sorted = true;
}
return this._array;
};
exports.MappingList = MappingList;

View File

@@ -0,0 +1,114 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
// It turns out that some (most?) JavaScript engines don't self-host
// `Array.prototype.sort`. This makes sense because C++ will likely remain
// faster than JS when doing raw CPU-intensive sorting. However, when using a
// custom comparator function, calling back and forth between the VM's C++ and
// JIT'd JS is rather slow *and* loses JIT type information, resulting in
// worse generated code for the comparator function than would be optimal. In
// fact, when sorting with a comparator, these costs outweigh the benefits of
// sorting in C++. By using our own JS-implemented Quick Sort (below), we get
// a ~3500ms mean speed-up in `bench/bench.html`.
/**
* Swap the elements indexed by `x` and `y` in the array `ary`.
*
* @param {Array} ary
* The array.
* @param {Number} x
* The index of the first item.
* @param {Number} y
* The index of the second item.
*/
function swap(ary, x, y) {
var temp = ary[x];
ary[x] = ary[y];
ary[y] = temp;
}
/**
* Returns a random integer within the range `low .. high` inclusive.
*
* @param {Number} low
* The lower bound on the range.
* @param {Number} high
* The upper bound on the range.
*/
function randomIntInRange(low, high) {
return Math.round(low + (Math.random() * (high - low)));
}
/**
* The Quick Sort algorithm.
*
* @param {Array} ary
* An array to sort.
* @param {function} comparator
* Function to use to compare two items.
* @param {Number} p
* Start index of the array
* @param {Number} r
* End index of the array
*/
function doQuickSort(ary, comparator, p, r) {
// If our lower bound is less than our upper bound, we (1) partition the
// array into two pieces and (2) recurse on each half. If it is not, this is
// the empty array and our base case.
if (p < r) {
// (1) Partitioning.
//
// The partitioning chooses a pivot between `p` and `r` and moves all
// elements that are less than or equal to the pivot to the before it, and
// all the elements that are greater than it after it. The effect is that
// once partition is done, the pivot is in the exact place it will be when
// the array is put in sorted order, and it will not need to be moved
// again. This runs in O(n) time.
// Always choose a random pivot so that an input array which is reverse
// sorted does not cause O(n^2) running time.
var pivotIndex = randomIntInRange(p, r);
var i = p - 1;
swap(ary, pivotIndex, r);
var pivot = ary[r];
// Immediately after `j` is incremented in this loop, the following hold
// true:
//
// * Every element in `ary[p .. i]` is less than or equal to the pivot.
//
// * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
for (var j = p; j < r; j++) {
if (comparator(ary[j], pivot) <= 0) {
i += 1;
swap(ary, i, j);
}
}
swap(ary, i + 1, j);
var q = i + 1;
// (2) Recurse on each half.
doQuickSort(ary, comparator, p, q - 1);
doQuickSort(ary, comparator, q + 1, r);
}
}
/**
* Sort the given array in-place with the given comparator function.
*
* @param {Array} ary
* An array to sort.
* @param {function} comparator
* Function to use to compare two items.
*/
exports.quickSort = function (ary, comparator) {
doQuickSort(ary, comparator, 0, ary.length - 1);
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,425 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var base64VLQ = require('./base64-vlq');
var util = require('./util');
var ArraySet = require('./array-set').ArraySet;
var MappingList = require('./mapping-list').MappingList;
/**
* An instance of the SourceMapGenerator represents a source map which is
* being built incrementally. You may pass an object with the following
* properties:
*
* - file: The filename of the generated source.
* - sourceRoot: A root for all relative URLs in this source map.
*/
function SourceMapGenerator(aArgs) {
if (!aArgs) {
aArgs = {};
}
this._file = util.getArg(aArgs, 'file', null);
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = new MappingList();
this._sourcesContents = null;
}
SourceMapGenerator.prototype._version = 3;
/**
* Creates a new SourceMapGenerator based on a SourceMapConsumer
*
* @param aSourceMapConsumer The SourceMap.
*/
SourceMapGenerator.fromSourceMap =
function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
var sourceRoot = aSourceMapConsumer.sourceRoot;
var generator = new SourceMapGenerator({
file: aSourceMapConsumer.file,
sourceRoot: sourceRoot
});
aSourceMapConsumer.eachMapping(function (mapping) {
var newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
}
};
if (mapping.source != null) {
newMapping.source = mapping.source;
if (sourceRoot != null) {
newMapping.source = util.relative(sourceRoot, newMapping.source);
}
newMapping.original = {
line: mapping.originalLine,
column: mapping.originalColumn
};
if (mapping.name != null) {
newMapping.name = mapping.name;
}
}
generator.addMapping(newMapping);
});
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var sourceRelative = sourceFile;
if (sourceRoot !== null) {
sourceRelative = util.relative(sourceRoot, sourceFile);
}
if (!generator._sources.has(sourceRelative)) {
generator._sources.add(sourceRelative);
}
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
generator.setSourceContent(sourceFile, content);
}
});
return generator;
};
/**
* Add a single mapping from original source line and column to the generated
* source's line and column for this source map being created. The mapping
* object should have the following properties:
*
* - generated: An object with the generated line and column positions.
* - original: An object with the original line and column positions.
* - source: The original source file (relative to the sourceRoot).
* - name: An optional original token name for this mapping.
*/
SourceMapGenerator.prototype.addMapping =
function SourceMapGenerator_addMapping(aArgs) {
var generated = util.getArg(aArgs, 'generated');
var original = util.getArg(aArgs, 'original', null);
var source = util.getArg(aArgs, 'source', null);
var name = util.getArg(aArgs, 'name', null);
if (!this._skipValidation) {
this._validateMapping(generated, original, source, name);
}
if (source != null) {
source = String(source);
if (!this._sources.has(source)) {
this._sources.add(source);
}
}
if (name != null) {
name = String(name);
if (!this._names.has(name)) {
this._names.add(name);
}
}
this._mappings.add({
generatedLine: generated.line,
generatedColumn: generated.column,
originalLine: original != null && original.line,
originalColumn: original != null && original.column,
source: source,
name: name
});
};
/**
* Set the source content for a source file.
*/
SourceMapGenerator.prototype.setSourceContent =
function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
var source = aSourceFile;
if (this._sourceRoot != null) {
source = util.relative(this._sourceRoot, source);
}
if (aSourceContent != null) {
// Add the source content to the _sourcesContents map.
// Create a new _sourcesContents map if the property is null.
if (!this._sourcesContents) {
this._sourcesContents = Object.create(null);
}
this._sourcesContents[util.toSetString(source)] = aSourceContent;
} else if (this._sourcesContents) {
// Remove the source file from the _sourcesContents map.
// If the _sourcesContents map is empty, set the property to null.
delete this._sourcesContents[util.toSetString(source)];
if (Object.keys(this._sourcesContents).length === 0) {
this._sourcesContents = null;
}
}
};
/**
* Applies the mappings of a sub-source-map for a specific source file to the
* source map being generated. Each mapping to the supplied source file is
* rewritten using the supplied source map. Note: The resolution for the
* resulting mappings is the minimium of this map and the supplied map.
*
* @param aSourceMapConsumer The source map to be applied.
* @param aSourceFile Optional. The filename of the source file.
* If omitted, SourceMapConsumer's file property will be used.
* @param aSourceMapPath Optional. The dirname of the path to the source map
* to be applied. If relative, it is relative to the SourceMapConsumer.
* This parameter is needed when the two source maps aren't in the same
* directory, and the source map to be applied contains relative source
* paths. If so, those relative source paths need to be rewritten
* relative to the SourceMapGenerator.
*/
SourceMapGenerator.prototype.applySourceMap =
function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
var sourceFile = aSourceFile;
// If aSourceFile is omitted, we will use the file property of the SourceMap
if (aSourceFile == null) {
if (aSourceMapConsumer.file == null) {
throw new Error(
'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
'or the source map\'s "file" property. Both were omitted.'
);
}
sourceFile = aSourceMapConsumer.file;
}
var sourceRoot = this._sourceRoot;
// Make "sourceFile" relative if an absolute Url is passed.
if (sourceRoot != null) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
// Applying the SourceMap can add and remove items from the sources and
// the names array.
var newSources = new ArraySet();
var newNames = new ArraySet();
// Find mappings for the "sourceFile"
this._mappings.unsortedForEach(function (mapping) {
if (mapping.source === sourceFile && mapping.originalLine != null) {
// Check if it can be mapped by the source map, then update the mapping.
var original = aSourceMapConsumer.originalPositionFor({
line: mapping.originalLine,
column: mapping.originalColumn
});
if (original.source != null) {
// Copy mapping
mapping.source = original.source;
if (aSourceMapPath != null) {
mapping.source = util.join(aSourceMapPath, mapping.source)
}
if (sourceRoot != null) {
mapping.source = util.relative(sourceRoot, mapping.source);
}
mapping.originalLine = original.line;
mapping.originalColumn = original.column;
if (original.name != null) {
mapping.name = original.name;
}
}
}
var source = mapping.source;
if (source != null && !newSources.has(source)) {
newSources.add(source);
}
var name = mapping.name;
if (name != null && !newNames.has(name)) {
newNames.add(name);
}
}, this);
this._sources = newSources;
this._names = newNames;
// Copy sourcesContents of applied map.
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
if (aSourceMapPath != null) {
sourceFile = util.join(aSourceMapPath, sourceFile);
}
if (sourceRoot != null) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
this.setSourceContent(sourceFile, content);
}
}, this);
};
/**
* A mapping can have one of the three levels of data:
*
* 1. Just the generated position.
* 2. The Generated position, original position, and original source.
* 3. Generated and original position, original source, as well as a name
* token.
*
* To maintain consistency, we validate that any new mapping being added falls
* in to one of these categories.
*/
SourceMapGenerator.prototype._validateMapping =
function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
aName) {
// When aOriginal is truthy but has empty values for .line and .column,
// it is most likely a programmer error. In this case we throw a very
// specific error message to try to guide them the right way.
// For example: https://github.com/Polymer/polymer-bundler/pull/519
if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
throw new Error(
'original.line and original.column are not numbers -- you probably meant to omit ' +
'the original mapping entirely and only map the generated position. If so, pass ' +
'null for the original mapping instead of an object with empty or null values.'
);
}
if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aGenerated.line > 0 && aGenerated.column >= 0
&& !aOriginal && !aSource && !aName) {
// Case 1.
return;
}
else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aOriginal && 'line' in aOriginal && 'column' in aOriginal
&& aGenerated.line > 0 && aGenerated.column >= 0
&& aOriginal.line > 0 && aOriginal.column >= 0
&& aSource) {
// Cases 2 and 3.
return;
}
else {
throw new Error('Invalid mapping: ' + JSON.stringify({
generated: aGenerated,
source: aSource,
original: aOriginal,
name: aName
}));
}
};
/**
* Serialize the accumulated mappings in to the stream of base 64 VLQs
* specified by the source map format.
*/
SourceMapGenerator.prototype._serializeMappings =
function SourceMapGenerator_serializeMappings() {
var previousGeneratedColumn = 0;
var previousGeneratedLine = 1;
var previousOriginalColumn = 0;
var previousOriginalLine = 0;
var previousName = 0;
var previousSource = 0;
var result = '';
var next;
var mapping;
var nameIdx;
var sourceIdx;
var mappings = this._mappings.toArray();
for (var i = 0, len = mappings.length; i < len; i++) {
mapping = mappings[i];
next = ''
if (mapping.generatedLine !== previousGeneratedLine) {
previousGeneratedColumn = 0;
while (mapping.generatedLine !== previousGeneratedLine) {
next += ';';
previousGeneratedLine++;
}
}
else {
if (i > 0) {
if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
continue;
}
next += ',';
}
}
next += base64VLQ.encode(mapping.generatedColumn
- previousGeneratedColumn);
previousGeneratedColumn = mapping.generatedColumn;
if (mapping.source != null) {
sourceIdx = this._sources.indexOf(mapping.source);
next += base64VLQ.encode(sourceIdx - previousSource);
previousSource = sourceIdx;
// lines are stored 0-based in SourceMap spec version 3
next += base64VLQ.encode(mapping.originalLine - 1
- previousOriginalLine);
previousOriginalLine = mapping.originalLine - 1;
next += base64VLQ.encode(mapping.originalColumn
- previousOriginalColumn);
previousOriginalColumn = mapping.originalColumn;
if (mapping.name != null) {
nameIdx = this._names.indexOf(mapping.name);
next += base64VLQ.encode(nameIdx - previousName);
previousName = nameIdx;
}
}
result += next;
}
return result;
};
SourceMapGenerator.prototype._generateSourcesContent =
function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
return aSources.map(function (source) {
if (!this._sourcesContents) {
return null;
}
if (aSourceRoot != null) {
source = util.relative(aSourceRoot, source);
}
var key = util.toSetString(source);
return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
? this._sourcesContents[key]
: null;
}, this);
};
/**
* Externalize the source map.
*/
SourceMapGenerator.prototype.toJSON =
function SourceMapGenerator_toJSON() {
var map = {
version: this._version,
sources: this._sources.toArray(),
names: this._names.toArray(),
mappings: this._serializeMappings()
};
if (this._file != null) {
map.file = this._file;
}
if (this._sourceRoot != null) {
map.sourceRoot = this._sourceRoot;
}
if (this._sourcesContents) {
map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
}
return map;
};
/**
* Render the source map being generated to a string.
*/
SourceMapGenerator.prototype.toString =
function SourceMapGenerator_toString() {
return JSON.stringify(this.toJSON());
};
exports.SourceMapGenerator = SourceMapGenerator;

View File

@@ -0,0 +1,413 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
var util = require('./util');
// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
// operating systems these days (capturing the result).
var REGEX_NEWLINE = /(\r?\n)/;
// Newline character code for charCodeAt() comparisons
var NEWLINE_CODE = 10;
// Private symbol for identifying `SourceNode`s when multiple versions of
// the source-map library are loaded. This MUST NOT CHANGE across
// versions!
var isSourceNode = "$$$isSourceNode$$$";
/**
* SourceNodes provide a way to abstract over interpolating/concatenating
* snippets of generated JavaScript source code while maintaining the line and
* column information associated with the original source code.
*
* @param aLine The original line number.
* @param aColumn The original column number.
* @param aSource The original source's filename.
* @param aChunks Optional. An array of strings which are snippets of
* generated JS, or other SourceNodes.
* @param aName The original identifier.
*/
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
this.children = [];
this.sourceContents = {};
this.line = aLine == null ? null : aLine;
this.column = aColumn == null ? null : aColumn;
this.source = aSource == null ? null : aSource;
this.name = aName == null ? null : aName;
this[isSourceNode] = true;
if (aChunks != null) this.add(aChunks);
}
/**
* Creates a SourceNode from generated code and a SourceMapConsumer.
*
* @param aGeneratedCode The generated code
* @param aSourceMapConsumer The SourceMap for the generated code
* @param aRelativePath Optional. The path that relative sources in the
* SourceMapConsumer should be relative to.
*/
SourceNode.fromStringWithSourceMap =
function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
// The SourceNode we want to fill with the generated code
// and the SourceMap
var node = new SourceNode();
// All even indices of this array are one line of the generated code,
// while all odd indices are the newlines between two adjacent lines
// (since `REGEX_NEWLINE` captures its match).
// Processed fragments are accessed by calling `shiftNextLine`.
var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
var remainingLinesIndex = 0;
var shiftNextLine = function() {
var lineContents = getNextLine();
// The last line of a file might not have a newline.
var newLine = getNextLine() || "";
return lineContents + newLine;
function getNextLine() {
return remainingLinesIndex < remainingLines.length ?
remainingLines[remainingLinesIndex++] : undefined;
}
};
// We need to remember the position of "remainingLines"
var lastGeneratedLine = 1, lastGeneratedColumn = 0;
// The generate SourceNodes we need a code range.
// To extract it current and last mapping is used.
// Here we store the last mapping.
var lastMapping = null;
aSourceMapConsumer.eachMapping(function (mapping) {
if (lastMapping !== null) {
// We add the code from "lastMapping" to "mapping":
// First check if there is a new line in between.
if (lastGeneratedLine < mapping.generatedLine) {
// Associate first line with "lastMapping"
addMappingWithCode(lastMapping, shiftNextLine());
lastGeneratedLine++;
lastGeneratedColumn = 0;
// The remaining code is added without mapping
} else {
// There is no new line in between.
// Associate the code between "lastGeneratedColumn" and
// "mapping.generatedColumn" with "lastMapping"
var nextLine = remainingLines[remainingLinesIndex] || '';
var code = nextLine.substr(0, mapping.generatedColumn -
lastGeneratedColumn);
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
lastGeneratedColumn);
lastGeneratedColumn = mapping.generatedColumn;
addMappingWithCode(lastMapping, code);
// No more remaining code, continue
lastMapping = mapping;
return;
}
}
// We add the generated code until the first mapping
// to the SourceNode without any mapping.
// Each line is added as separate string.
while (lastGeneratedLine < mapping.generatedLine) {
node.add(shiftNextLine());
lastGeneratedLine++;
}
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[remainingLinesIndex] || '';
node.add(nextLine.substr(0, mapping.generatedColumn));
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
lastMapping = mapping;
}, this);
// We have processed all mappings.
if (remainingLinesIndex < remainingLines.length) {
if (lastMapping) {
// Associate the remaining code in the current line with "lastMapping"
addMappingWithCode(lastMapping, shiftNextLine());
}
// and add the remaining lines without any mapping
node.add(remainingLines.splice(remainingLinesIndex).join(""));
}
// Copy sourcesContent into SourceNode
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
if (aRelativePath != null) {
sourceFile = util.join(aRelativePath, sourceFile);
}
node.setSourceContent(sourceFile, content);
}
});
return node;
function addMappingWithCode(mapping, code) {
if (mapping === null || mapping.source === undefined) {
node.add(code);
} else {
var source = aRelativePath
? util.join(aRelativePath, mapping.source)
: mapping.source;
node.add(new SourceNode(mapping.originalLine,
mapping.originalColumn,
source,
code,
mapping.name));
}
}
};
/**
* Add a chunk of generated JS to this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.add = function SourceNode_add(aChunk) {
if (Array.isArray(aChunk)) {
aChunk.forEach(function (chunk) {
this.add(chunk);
}, this);
}
else if (aChunk[isSourceNode] || typeof aChunk === "string") {
if (aChunk) {
this.children.push(aChunk);
}
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Add a chunk of generated JS to the beginning of this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
if (Array.isArray(aChunk)) {
for (var i = aChunk.length-1; i >= 0; i--) {
this.prepend(aChunk[i]);
}
}
else if (aChunk[isSourceNode] || typeof aChunk === "string") {
this.children.unshift(aChunk);
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Walk over the tree of JS snippets in this node and its children. The
* walking function is called once for each snippet of JS and is passed that
* snippet and the its original associated source's line/column location.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
var chunk;
for (var i = 0, len = this.children.length; i < len; i++) {
chunk = this.children[i];
if (chunk[isSourceNode]) {
chunk.walk(aFn);
}
else {
if (chunk !== '') {
aFn(chunk, { source: this.source,
line: this.line,
column: this.column,
name: this.name });
}
}
}
};
/**
* Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
* each of `this.children`.
*
* @param aSep The separator.
*/
SourceNode.prototype.join = function SourceNode_join(aSep) {
var newChildren;
var i;
var len = this.children.length;
if (len > 0) {
newChildren = [];
for (i = 0; i < len-1; i++) {
newChildren.push(this.children[i]);
newChildren.push(aSep);
}
newChildren.push(this.children[i]);
this.children = newChildren;
}
return this;
};
/**
* Call String.prototype.replace on the very right-most source snippet. Useful
* for trimming whitespace from the end of a source node, etc.
*
* @param aPattern The pattern to replace.
* @param aReplacement The thing to replace the pattern with.
*/
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
var lastChild = this.children[this.children.length - 1];
if (lastChild[isSourceNode]) {
lastChild.replaceRight(aPattern, aReplacement);
}
else if (typeof lastChild === 'string') {
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
}
else {
this.children.push(''.replace(aPattern, aReplacement));
}
return this;
};
/**
* Set the source content for a source file. This will be added to the SourceMapGenerator
* in the sourcesContent field.
*
* @param aSourceFile The filename of the source file
* @param aSourceContent The content of the source file
*/
SourceNode.prototype.setSourceContent =
function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
};
/**
* Walk over the tree of SourceNodes. The walking function is called for each
* source file content and is passed the filename and source content.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walkSourceContents =
function SourceNode_walkSourceContents(aFn) {
for (var i = 0, len = this.children.length; i < len; i++) {
if (this.children[i][isSourceNode]) {
this.children[i].walkSourceContents(aFn);
}
}
var sources = Object.keys(this.sourceContents);
for (var i = 0, len = sources.length; i < len; i++) {
aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
}
};
/**
* Return the string representation of this source node. Walks over the tree
* and concatenates all the various snippets together to one string.
*/
SourceNode.prototype.toString = function SourceNode_toString() {
var str = "";
this.walk(function (chunk) {
str += chunk;
});
return str;
};
/**
* Returns the string representation of this source node along with a source
* map.
*/
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
var generated = {
code: "",
line: 1,
column: 0
};
var map = new SourceMapGenerator(aArgs);
var sourceMappingActive = false;
var lastOriginalSource = null;
var lastOriginalLine = null;
var lastOriginalColumn = null;
var lastOriginalName = null;
this.walk(function (chunk, original) {
generated.code += chunk;
if (original.source !== null
&& original.line !== null
&& original.column !== null) {
if(lastOriginalSource !== original.source
|| lastOriginalLine !== original.line
|| lastOriginalColumn !== original.column
|| lastOriginalName !== original.name) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
lastOriginalSource = original.source;
lastOriginalLine = original.line;
lastOriginalColumn = original.column;
lastOriginalName = original.name;
sourceMappingActive = true;
} else if (sourceMappingActive) {
map.addMapping({
generated: {
line: generated.line,
column: generated.column
}
});
lastOriginalSource = null;
sourceMappingActive = false;
}
for (var idx = 0, length = chunk.length; idx < length; idx++) {
if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
generated.line++;
generated.column = 0;
// Mappings end at eol
if (idx + 1 === length) {
lastOriginalSource = null;
sourceMappingActive = false;
} else if (sourceMappingActive) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
} else {
generated.column++;
}
}
});
this.walkSourceContents(function (sourceFile, sourceContent) {
map.setSourceContent(sourceFile, sourceContent);
});
return { code: generated.code, map: map };
};
exports.SourceNode = SourceNode;

View File

@@ -0,0 +1,488 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports.getArg = getArg;
var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
var dataUrlRegexp = /^data:.+\,.+$/;
function urlParse(aUrl) {
var match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[2],
host: match[3],
port: match[4],
path: match[5]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
var url = '';
if (aParsedUrl.scheme) {
url += aParsedUrl.scheme + ':';
}
url += '//';
if (aParsedUrl.auth) {
url += aParsedUrl.auth + '@';
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
/**
* Normalizes a path, or the path portion of a URL:
*
* - Replaces consecutive slashes with one slash.
* - Removes unnecessary '.' parts.
* - Removes unnecessary '<dir>/..' parts.
*
* Based on code in the Node.js 'path' core module.
*
* @param aPath The path or url to normalize.
*/
function normalize(aPath) {
var path = aPath;
var url = urlParse(aPath);
if (url) {
if (!url.path) {
return aPath;
}
path = url.path;
}
var isAbsolute = exports.isAbsolute(path);
var parts = path.split(/\/+/);
for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
part = parts[i];
if (part === '.') {
parts.splice(i, 1);
} else if (part === '..') {
up++;
} else if (up > 0) {
if (part === '') {
// The first part is blank if the path is absolute. Trying to go
// above the root is a no-op. Therefore we can remove all '..' parts
// directly after the root.
parts.splice(i + 1, up);
up = 0;
} else {
parts.splice(i, 2);
up--;
}
}
}
path = parts.join('/');
if (path === '') {
path = isAbsolute ? '/' : '.';
}
if (url) {
url.path = path;
return urlGenerate(url);
}
return path;
}
exports.normalize = normalize;
/**
* Joins two paths/URLs.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be joined with the root.
*
* - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
* scheme-relative URL: Then the scheme of aRoot, if any, is prepended
* first.
* - Otherwise aPath is a path. If aRoot is a URL, then its path portion
* is updated with the result and aRoot is returned. Otherwise the result
* is returned.
* - If aPath is absolute, the result is aPath.
* - Otherwise the two paths are joined with a slash.
* - Joining for example 'http://' and 'www.example.com' is also supported.
*/
function join(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
if (aPath === "") {
aPath = ".";
}
var aPathUrl = urlParse(aPath);
var aRootUrl = urlParse(aRoot);
if (aRootUrl) {
aRoot = aRootUrl.path || '/';
}
// `join(foo, '//www.example.org')`
if (aPathUrl && !aPathUrl.scheme) {
if (aRootUrl) {
aPathUrl.scheme = aRootUrl.scheme;
}
return urlGenerate(aPathUrl);
}
if (aPathUrl || aPath.match(dataUrlRegexp)) {
return aPath;
}
// `join('http://', 'www.example.com')`
if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
aRootUrl.host = aPath;
return urlGenerate(aRootUrl);
}
var joined = aPath.charAt(0) === '/'
? aPath
: normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
if (aRootUrl) {
aRootUrl.path = joined;
return urlGenerate(aRootUrl);
}
return joined;
}
exports.join = join;
exports.isAbsolute = function (aPath) {
return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
};
/**
* Make a path relative to a URL or another path.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be made relative to aRoot.
*/
function relative(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
aRoot = aRoot.replace(/\/$/, '');
// It is possible for the path to be above the root. In this case, simply
// checking whether the root is a prefix of the path won't work. Instead, we
// need to remove components from the root one by one, until either we find
// a prefix that fits, or we run out of components to remove.
var level = 0;
while (aPath.indexOf(aRoot + '/') !== 0) {
var index = aRoot.lastIndexOf("/");
if (index < 0) {
return aPath;
}
// If the only part of the root that is left is the scheme (i.e. http://,
// file:///, etc.), one or more slashes (/), or simply nothing at all, we
// have exhausted all components, so the path is not relative to the root.
aRoot = aRoot.slice(0, index);
if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
return aPath;
}
++level;
}
// Make sure we add a "../" for each component we removed from the root.
return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
}
exports.relative = relative;
var supportsNullProto = (function () {
var obj = Object.create(null);
return !('__proto__' in obj);
}());
function identity (s) {
return s;
}
/**
* Because behavior goes wacky when you set `__proto__` on objects, we
* have to prefix all the strings in our set with an arbitrary character.
*
* See https://github.com/mozilla/source-map/pull/31 and
* https://github.com/mozilla/source-map/issues/30
*
* @param String aStr
*/
function toSetString(aStr) {
if (isProtoString(aStr)) {
return '$' + aStr;
}
return aStr;
}
exports.toSetString = supportsNullProto ? identity : toSetString;
function fromSetString(aStr) {
if (isProtoString(aStr)) {
return aStr.slice(1);
}
return aStr;
}
exports.fromSetString = supportsNullProto ? identity : fromSetString;
function isProtoString(s) {
if (!s) {
return false;
}
var length = s.length;
if (length < 9 /* "__proto__".length */) {
return false;
}
if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
s.charCodeAt(length - 2) !== 95 /* '_' */ ||
s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
s.charCodeAt(length - 4) !== 116 /* 't' */ ||
s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
s.charCodeAt(length - 8) !== 95 /* '_' */ ||
s.charCodeAt(length - 9) !== 95 /* '_' */) {
return false;
}
for (var i = length - 10; i >= 0; i--) {
if (s.charCodeAt(i) !== 36 /* '$' */) {
return false;
}
}
return true;
}
/**
* Comparator between two mappings where the original positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same original source/line/column, but different generated
* line and column the same. Useful when searching for a mapping with a
* stubbed out mapping.
*/
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
var cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0 || onlyCompareOriginal) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByOriginalPositions = compareByOriginalPositions;
/**
* Comparator between two mappings with deflated source and name indices where
* the generated positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same generated line and column, but different
* source/name/original line and column the same. Useful when searching for a
* mapping with a stubbed out mapping.
*/
function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
var cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0 || onlyCompareGenerated) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
function strcmp(aStr1, aStr2) {
if (aStr1 === aStr2) {
return 0;
}
if (aStr1 === null) {
return 1; // aStr2 !== null
}
if (aStr2 === null) {
return -1; // aStr1 !== null
}
if (aStr1 > aStr2) {
return 1;
}
return -1;
}
/**
* Comparator between two mappings with inflated source and name strings where
* the generated positions are compared.
*/
function compareByGeneratedPositionsInflated(mappingA, mappingB) {
var cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
/**
* Strip any JSON XSSI avoidance prefix from the string (as documented
* in the source maps specification), and then parse the string as
* JSON.
*/
function parseSourceMapInput(str) {
return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
}
exports.parseSourceMapInput = parseSourceMapInput;
/**
* Compute the URL of a source given the the source root, the source's
* URL, and the source map's URL.
*/
function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
sourceURL = sourceURL || '';
if (sourceRoot) {
// This follows what Chrome does.
if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
sourceRoot += '/';
}
// The spec says:
// Line 4: An optional source root, useful for relocating source
// files on a server or removing repeated values in the
// “sources” entry. This value is prepended to the individual
// entries in the “source” field.
sourceURL = sourceRoot + sourceURL;
}
// Historically, SourceMapConsumer did not take the sourceMapURL as
// a parameter. This mode is still somewhat supported, which is why
// this code block is conditional. However, it's preferable to pass
// the source map URL to SourceMapConsumer, so that this function
// can implement the source URL resolution algorithm as outlined in
// the spec. This block is basically the equivalent of:
// new URL(sourceURL, sourceMapURL).toString()
// ... except it avoids using URL, which wasn't available in the
// older releases of node still supported by this library.
//
// The spec says:
// If the sources are not absolute URLs after prepending of the
// “sourceRoot”, the sources are resolved relative to the
// SourceMap (like resolving script src in a html document).
if (sourceMapURL) {
var parsed = urlParse(sourceMapURL);
if (!parsed) {
throw new Error("sourceMapURL could not be parsed");
}
if (parsed.path) {
// Strip the last path component, but keep the "/".
var index = parsed.path.lastIndexOf('/');
if (index >= 0) {
parsed.path = parsed.path.substring(0, index + 1);
}
}
sourceURL = join(urlGenerate(parsed), sourceURL);
}
return normalize(sourceURL);
}
exports.computeSourceURL = computeSourceURL;

View File

@@ -0,0 +1,73 @@
{
"name": "source-map",
"description": "Generates and consumes source maps",
"version": "0.6.1",
"homepage": "https://github.com/mozilla/source-map",
"author": "Nick Fitzgerald <nfitzgerald@mozilla.com>",
"contributors": [
"Tobias Koppers <tobias.koppers@googlemail.com>",
"Duncan Beevers <duncan@dweebd.com>",
"Stephen Crane <scrane@mozilla.com>",
"Ryan Seddon <seddon.ryan@gmail.com>",
"Miles Elam <miles.elam@deem.com>",
"Mihai Bazon <mihai.bazon@gmail.com>",
"Michael Ficarra <github.public.email@michael.ficarra.me>",
"Todd Wolfson <todd@twolfson.com>",
"Alexander Solovyov <alexander@solovyov.net>",
"Felix Gnass <fgnass@gmail.com>",
"Conrad Irwin <conrad.irwin@gmail.com>",
"usrbincc <usrbincc@yahoo.com>",
"David Glasser <glasser@davidglasser.net>",
"Chase Douglas <chase@newrelic.com>",
"Evan Wallace <evan.exe@gmail.com>",
"Heather Arthur <fayearthur@gmail.com>",
"Hugh Kennedy <hughskennedy@gmail.com>",
"David Glasser <glasser@davidglasser.net>",
"Simon Lydell <simon.lydell@gmail.com>",
"Jmeas Smith <jellyes2@gmail.com>",
"Michael Z Goddard <mzgoddard@gmail.com>",
"azu <azu@users.noreply.github.com>",
"John Gozde <john@gozde.ca>",
"Adam Kirkton <akirkton@truefitinnovation.com>",
"Chris Montgomery <christopher.montgomery@dowjones.com>",
"J. Ryan Stinnett <jryans@gmail.com>",
"Jack Herrington <jherrington@walmartlabs.com>",
"Chris Truter <jeffpalentine@gmail.com>",
"Daniel Espeset <daniel@danielespeset.com>",
"Jamie Wong <jamie.lf.wong@gmail.com>",
"Eddy Bruël <ejpbruel@mozilla.com>",
"Hawken Rives <hawkrives@gmail.com>",
"Gilad Peleg <giladp007@gmail.com>",
"djchie <djchie.dev@gmail.com>",
"Gary Ye <garysye@gmail.com>",
"Nicolas Lalevée <nicolas.lalevee@hibnet.org>"
],
"repository": {
"type": "git",
"url": "http://github.com/mozilla/source-map.git"
},
"main": "./source-map.js",
"files": [
"source-map.js",
"source-map.d.ts",
"lib/",
"dist/source-map.debug.js",
"dist/source-map.js",
"dist/source-map.min.js",
"dist/source-map.min.js.map"
],
"engines": {
"node": ">=0.10.0"
},
"license": "BSD-3-Clause",
"scripts": {
"test": "npm run build && node test/run-tests.js",
"build": "webpack --color",
"toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md"
},
"devDependencies": {
"doctoc": "^0.15.0",
"webpack": "^1.12.0"
},
"typings": "source-map"
}

View File

@@ -0,0 +1,98 @@
export interface StartOfSourceMap {
file?: string;
sourceRoot?: string;
}
export interface RawSourceMap extends StartOfSourceMap {
version: string;
sources: string[];
names: string[];
sourcesContent?: string[];
mappings: string;
}
export interface Position {
line: number;
column: number;
}
export interface LineRange extends Position {
lastColumn: number;
}
export interface FindPosition extends Position {
// SourceMapConsumer.GREATEST_LOWER_BOUND or SourceMapConsumer.LEAST_UPPER_BOUND
bias?: number;
}
export interface SourceFindPosition extends FindPosition {
source: string;
}
export interface MappedPosition extends Position {
source: string;
name?: string;
}
export interface MappingItem {
source: string;
generatedLine: number;
generatedColumn: number;
originalLine: number;
originalColumn: number;
name: string;
}
export class SourceMapConsumer {
static GENERATED_ORDER: number;
static ORIGINAL_ORDER: number;
static GREATEST_LOWER_BOUND: number;
static LEAST_UPPER_BOUND: number;
constructor(rawSourceMap: RawSourceMap);
computeColumnSpans(): void;
originalPositionFor(generatedPosition: FindPosition): MappedPosition;
generatedPositionFor(originalPosition: SourceFindPosition): LineRange;
allGeneratedPositionsFor(originalPosition: MappedPosition): Position[];
hasContentsOfAllSources(): boolean;
sourceContentFor(source: string, returnNullOnMissing?: boolean): string;
eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void;
}
export interface Mapping {
generated: Position;
original: Position;
source: string;
name?: string;
}
export class SourceMapGenerator {
constructor(startOfSourceMap?: StartOfSourceMap);
static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator;
addMapping(mapping: Mapping): void;
setSourceContent(sourceFile: string, sourceContent: string): void;
applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void;
toString(): string;
}
export interface CodeWithSourceMap {
code: string;
map: SourceMapGenerator;
}
export class SourceNode {
constructor();
constructor(line: number, column: number, source: string);
constructor(line: number, column: number, source: string, chunk?: string, name?: string);
static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode;
add(chunk: string): void;
prepend(chunk: string): void;
setSourceContent(sourceFile: string, sourceContent: string): void;
walk(fn: (chunk: string, mapping: MappedPosition) => void): void;
walkSourceContents(fn: (file: string, content: string) => void): void;
join(sep: string): SourceNode;
replaceRight(pattern: string, replacement: string): SourceNode;
toString(): string;
toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap;
}

View File

@@ -0,0 +1,8 @@
/*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;
exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;
exports.SourceNode = require('./lib/source-node').SourceNode;

View File

@@ -0,0 +1,22 @@
Copyright (c) George Zahariev
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.

View File

@@ -0,0 +1,210 @@
# type-check [![Build Status](https://travis-ci.org/gkz/type-check.png?branch=master)](https://travis-ci.org/gkz/type-check)
<a name="type-check" />
`type-check` is a library which allows you to check the types of JavaScript values at runtime with a Haskell like type syntax. It is great for checking external input, for testing, or even for adding a bit of safety to your internal code. It is a major component of [levn](https://github.com/gkz/levn). MIT license. Version 0.3.2. Check out the [demo](http://gkz.github.io/type-check/).
For updates on `type-check`, [follow me on twitter](https://twitter.com/gkzahariev).
npm install type-check
## Quick Examples
```js
// Basic types:
var typeCheck = require('type-check').typeCheck;
typeCheck('Number', 1); // true
typeCheck('Number', 'str'); // false
typeCheck('Error', new Error); // true
typeCheck('Undefined', undefined); // true
// Comment
typeCheck('count::Number', 1); // true
// One type OR another type:
typeCheck('Number | String', 2); // true
typeCheck('Number | String', 'str'); // true
// Wildcard, matches all types:
typeCheck('*', 2) // true
// Array, all elements of a single type:
typeCheck('[Number]', [1, 2, 3]); // true
typeCheck('[Number]', [1, 'str', 3]); // false
// Tuples, or fixed length arrays with elements of different types:
typeCheck('(String, Number)', ['str', 2]); // true
typeCheck('(String, Number)', ['str']); // false
typeCheck('(String, Number)', ['str', 2, 5]); // false
// Object properties:
typeCheck('{x: Number, y: Boolean}', {x: 2, y: false}); // true
typeCheck('{x: Number, y: Boolean}', {x: 2}); // false
typeCheck('{x: Number, y: Maybe Boolean}', {x: 2}); // true
typeCheck('{x: Number, y: Boolean}', {x: 2, y: false, z: 3}); // false
typeCheck('{x: Number, y: Boolean, ...}', {x: 2, y: false, z: 3}); // true
// A particular type AND object properties:
typeCheck('RegExp{source: String, ...}', /re/i); // true
typeCheck('RegExp{source: String, ...}', {source: 're'}); // false
// Custom types:
var opt = {customTypes:
{Even: { typeOf: 'Number', validate: function(x) { return x % 2 === 0; }}}};
typeCheck('Even', 2, opt); // true
// Nested:
var type = '{a: (String, [Number], {y: Array, ...}), b: Error{message: String, ...}}'
typeCheck(type, {a: ['hi', [1, 2, 3], {y: [1, 'ms']}], b: new Error('oh no')}); // true
```
Check out the [type syntax format](#syntax) and [guide](#guide).
## Usage
`require('type-check');` returns an object that exposes four properties. `VERSION` is the current version of the library as a string. `typeCheck`, `parseType`, and `parsedTypeCheck` are functions.
```js
// typeCheck(type, input, options);
typeCheck('Number', 2); // true
// parseType(type);
var parsedType = parseType('Number'); // object
// parsedTypeCheck(parsedType, input, options);
parsedTypeCheck(parsedType, 2); // true
```
### typeCheck(type, input, options)
`typeCheck` checks a JavaScript value `input` against `type` written in the [type format](#type-format) (and taking account the optional `options`) and returns whether the `input` matches the `type`.
##### arguments
* type - `String` - the type written in the [type format](#type-format) which to check against
* input - `*` - any JavaScript value, which is to be checked against the type
* options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types)
##### returns
`Boolean` - whether the input matches the type
##### example
```js
typeCheck('Number', 2); // true
```
### parseType(type)
`parseType` parses string `type` written in the [type format](#type-format) into an object representing the parsed type.
##### arguments
* type - `String` - the type written in the [type format](#type-format) which to parse
##### returns
`Object` - an object in the parsed type format representing the parsed type
##### example
```js
parseType('Number'); // [{type: 'Number'}]
```
### parsedTypeCheck(parsedType, input, options)
`parsedTypeCheck` checks a JavaScript value `input` against parsed `type` in the parsed type format (and taking account the optional `options`) and returns whether the `input` matches the `type`. Use this in conjunction with `parseType` if you are going to use a type more than once.
##### arguments
* type - `Object` - the type in the parsed type format which to check against
* input - `*` - any JavaScript value, which is to be checked against the type
* options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types)
##### returns
`Boolean` - whether the input matches the type
##### example
```js
parsedTypeCheck([{type: 'Number'}], 2); // true
var parsedType = parseType('String');
parsedTypeCheck(parsedType, 'str'); // true
```
<a name="type-format" />
## Type Format
### Syntax
White space is ignored. The root node is a __Types__.
* __Identifier__ = `[\$\w]+` - a group of any lower or upper case letters, numbers, underscores, or dollar signs - eg. `String`
* __Type__ = an `Identifier`, an `Identifier` followed by a `Structure`, just a `Structure`, or a wildcard `*` - eg. `String`, `Object{x: Number}`, `{x: Number}`, `Array{0: String, 1: Boolean, length: Number}`, `*`
* __Types__ = optionally a comment (an `Indentifier` followed by a `::`), optionally the identifier `Maybe`, one or more `Type`, separated by `|` - eg. `Number`, `String | Date`, `Maybe Number`, `Maybe Boolean | String`
* __Structure__ = `Fields`, or a `Tuple`, or an `Array` - eg. `{x: Number}`, `(String, Number)`, `[Date]`
* __Fields__ = a `{`, followed one or more `Field` separated by a comma `,` (trailing comma `,` is permitted), optionally an `...` (always preceded by a comma `,`), followed by a `}` - eg. `{x: Number, y: String}`, `{k: Function, ...}`
* __Field__ = an `Identifier`, followed by a colon `:`, followed by `Types` - eg. `x: Date | String`, `y: Boolean`
* __Tuple__ = a `(`, followed by one or more `Types` separated by a comma `,` (trailing comma `,` is permitted), followed by a `)` - eg `(Date)`, `(Number, Date)`
* __Array__ = a `[` followed by exactly one `Types` followed by a `]` - eg. `[Boolean]`, `[Boolean | Null]`
### Guide
`type-check` uses `Object.toString` to find out the basic type of a value. Specifically,
```js
{}.toString.call(VALUE).slice(8, -1)
{}.toString.call(true).slice(8, -1) // 'Boolean'
```
A basic type, eg. `Number`, uses this check. This is much more versatile than using `typeof` - for example, with `document`, `typeof` produces `'object'` which isn't that useful, and our technique produces `'HTMLDocument'`.
You may check for multiple types by separating types with a `|`. The checker proceeds from left to right, and passes if the value is any of the types - eg. `String | Boolean` first checks if the value is a string, and then if it is a boolean. If it is none of those, then it returns false.
Adding a `Maybe` in front of a list of multiple types is the same as also checking for `Null` and `Undefined` - eg. `Maybe String` is equivalent to `Undefined | Null | String`.
You may add a comment to remind you of what the type is for by following an identifier with a `::` before a type (or multiple types). The comment is simply thrown out.
The wildcard `*` matches all types.
There are three types of structures for checking the contents of a value: 'fields', 'tuple', and 'array'.
If used by itself, a 'fields' structure will pass with any type of object as long as it is an instance of `Object` and the properties pass - this allows for duck typing - eg. `{x: Boolean}`.
To check if the properties pass, and the value is of a certain type, you can specify the type - eg. `Error{message: String}`.
If you want to make a field optional, you can simply use `Maybe` - eg. `{x: Boolean, y: Maybe String}` will still pass if `y` is undefined (or null).
If you don't care if the value has properties beyond what you have specified, you can use the 'etc' operator `...` - eg. `{x: Boolean, ...}` will match an object with an `x` property that is a boolean, and with zero or more other properties.
For an array, you must specify one or more types (separated by `|`) - it will pass for something of any length as long as each element passes the types provided - eg. `[Number]`, `[Number | String]`.
A tuple checks for a fixed number of elements, each of a potentially different type. Each element is separated by a comma - eg. `(String, Number)`.
An array and tuple structure check that the value is of type `Array` by default, but if another type is specified, they will check for that instead - eg. `Int32Array[Number]`. You can use the wildcard `*` to search for any type at all.
Check out the [type precedence](https://github.com/zaboco/type-precedence) library for type-check.
## Options
Options is an object. It is an optional parameter to the `typeCheck` and `parsedTypeCheck` functions. The only current option is `customTypes`.
<a name="custom-types" />
### Custom Types
__Example:__
```js
var options = {
customTypes: {
Even: {
typeOf: 'Number',
validate: function(x) {
return x % 2 === 0;
}
}
}
};
typeCheck('Even', 2, options); // true
typeCheck('Even', 3, options); // false
```
`customTypes` allows you to set up custom types for validation. The value of this is an object. The keys of the object are the types you will be matching. Each value of the object will be an object having a `typeOf` property - a string, and `validate` property - a function.
The `typeOf` property is the type the value should be, and `validate` is a function which should return true if the value is of that type. `validate` receives one parameter, which is the value that we are checking.
## Technical About
`type-check` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It also uses the [prelude.ls](http://preludels.com/) library.

View File

@@ -0,0 +1,126 @@
// Generated by LiveScript 1.4.0
(function(){
var ref$, any, all, isItNaN, types, defaultType, customTypes, toString$ = {}.toString;
ref$ = require('prelude-ls'), any = ref$.any, all = ref$.all, isItNaN = ref$.isItNaN;
types = {
Number: {
typeOf: 'Number',
validate: function(it){
return !isItNaN(it);
}
},
NaN: {
typeOf: 'Number',
validate: isItNaN
},
Int: {
typeOf: 'Number',
validate: function(it){
return !isItNaN(it) && it % 1 === 0;
}
},
Float: {
typeOf: 'Number',
validate: function(it){
return !isItNaN(it);
}
},
Date: {
typeOf: 'Date',
validate: function(it){
return !isItNaN(it.getTime());
}
}
};
defaultType = {
array: 'Array',
tuple: 'Array'
};
function checkArray(input, type){
return all(function(it){
return checkMultiple(it, type.of);
}, input);
}
function checkTuple(input, type){
var i, i$, ref$, len$, types;
i = 0;
for (i$ = 0, len$ = (ref$ = type.of).length; i$ < len$; ++i$) {
types = ref$[i$];
if (!checkMultiple(input[i], types)) {
return false;
}
i++;
}
return input.length <= i;
}
function checkFields(input, type){
var inputKeys, numInputKeys, k, numOfKeys, key, ref$, types;
inputKeys = {};
numInputKeys = 0;
for (k in input) {
inputKeys[k] = true;
numInputKeys++;
}
numOfKeys = 0;
for (key in ref$ = type.of) {
types = ref$[key];
if (!checkMultiple(input[key], types)) {
return false;
}
if (inputKeys[key]) {
numOfKeys++;
}
}
return type.subset || numInputKeys === numOfKeys;
}
function checkStructure(input, type){
if (!(input instanceof Object)) {
return false;
}
switch (type.structure) {
case 'fields':
return checkFields(input, type);
case 'array':
return checkArray(input, type);
case 'tuple':
return checkTuple(input, type);
}
}
function check(input, typeObj){
var type, structure, setting, that;
type = typeObj.type, structure = typeObj.structure;
if (type) {
if (type === '*') {
return true;
}
setting = customTypes[type] || types[type];
if (setting) {
return setting.typeOf === toString$.call(input).slice(8, -1) && setting.validate(input);
} else {
return type === toString$.call(input).slice(8, -1) && (!structure || checkStructure(input, typeObj));
}
} else if (structure) {
if (that = defaultType[structure]) {
if (that !== toString$.call(input).slice(8, -1)) {
return false;
}
}
return checkStructure(input, typeObj);
} else {
throw new Error("No type defined. Input: " + input + ".");
}
}
function checkMultiple(input, types){
if (toString$.call(types).slice(8, -1) !== 'Array') {
throw new Error("Types must be in an array. Input: " + input + ".");
}
return any(function(it){
return check(input, it);
}, types);
}
module.exports = function(parsedType, input, options){
options == null && (options = {});
customTypes = options.customTypes || {};
return checkMultiple(input, parsedType);
};
}).call(this);

View File

@@ -0,0 +1,16 @@
// Generated by LiveScript 1.4.0
(function(){
var VERSION, parseType, parsedTypeCheck, typeCheck;
VERSION = '0.3.2';
parseType = require('./parse-type');
parsedTypeCheck = require('./check');
typeCheck = function(type, input, options){
return parsedTypeCheck(parseType(type), input, options);
};
module.exports = {
VERSION: VERSION,
typeCheck: typeCheck,
parsedTypeCheck: parsedTypeCheck,
parseType: parseType
};
}).call(this);

View File

@@ -0,0 +1,196 @@
// Generated by LiveScript 1.4.0
(function(){
var identifierRegex, tokenRegex;
identifierRegex = /[\$\w]+/;
function peek(tokens){
var token;
token = tokens[0];
if (token == null) {
throw new Error('Unexpected end of input.');
}
return token;
}
function consumeIdent(tokens){
var token;
token = peek(tokens);
if (!identifierRegex.test(token)) {
throw new Error("Expected text, got '" + token + "' instead.");
}
return tokens.shift();
}
function consumeOp(tokens, op){
var token;
token = peek(tokens);
if (token !== op) {
throw new Error("Expected '" + op + "', got '" + token + "' instead.");
}
return tokens.shift();
}
function maybeConsumeOp(tokens, op){
var token;
token = tokens[0];
if (token === op) {
return tokens.shift();
} else {
return null;
}
}
function consumeArray(tokens){
var types;
consumeOp(tokens, '[');
if (peek(tokens) === ']') {
throw new Error("Must specify type of Array - eg. [Type], got [] instead.");
}
types = consumeTypes(tokens);
consumeOp(tokens, ']');
return {
structure: 'array',
of: types
};
}
function consumeTuple(tokens){
var components;
components = [];
consumeOp(tokens, '(');
if (peek(tokens) === ')') {
throw new Error("Tuple must be of at least length 1 - eg. (Type), got () instead.");
}
for (;;) {
components.push(consumeTypes(tokens));
maybeConsumeOp(tokens, ',');
if (')' === peek(tokens)) {
break;
}
}
consumeOp(tokens, ')');
return {
structure: 'tuple',
of: components
};
}
function consumeFields(tokens){
var fields, subset, ref$, key, types;
fields = {};
consumeOp(tokens, '{');
subset = false;
for (;;) {
if (maybeConsumeOp(tokens, '...')) {
subset = true;
break;
}
ref$ = consumeField(tokens), key = ref$[0], types = ref$[1];
fields[key] = types;
maybeConsumeOp(tokens, ',');
if ('}' === peek(tokens)) {
break;
}
}
consumeOp(tokens, '}');
return {
structure: 'fields',
of: fields,
subset: subset
};
}
function consumeField(tokens){
var key, types;
key = consumeIdent(tokens);
consumeOp(tokens, ':');
types = consumeTypes(tokens);
return [key, types];
}
function maybeConsumeStructure(tokens){
switch (tokens[0]) {
case '[':
return consumeArray(tokens);
case '(':
return consumeTuple(tokens);
case '{':
return consumeFields(tokens);
}
}
function consumeType(tokens){
var token, wildcard, type, structure;
token = peek(tokens);
wildcard = token === '*';
if (wildcard || identifierRegex.test(token)) {
type = wildcard
? consumeOp(tokens, '*')
: consumeIdent(tokens);
structure = maybeConsumeStructure(tokens);
if (structure) {
return structure.type = type, structure;
} else {
return {
type: type
};
}
} else {
structure = maybeConsumeStructure(tokens);
if (!structure) {
throw new Error("Unexpected character: " + token);
}
return structure;
}
}
function consumeTypes(tokens){
var lookahead, types, typesSoFar, typeObj, type;
if ('::' === peek(tokens)) {
throw new Error("No comment before comment separator '::' found.");
}
lookahead = tokens[1];
if (lookahead != null && lookahead === '::') {
tokens.shift();
tokens.shift();
}
types = [];
typesSoFar = {};
if ('Maybe' === peek(tokens)) {
tokens.shift();
types = [
{
type: 'Undefined'
}, {
type: 'Null'
}
];
typesSoFar = {
Undefined: true,
Null: true
};
}
for (;;) {
typeObj = consumeType(tokens), type = typeObj.type;
if (!typesSoFar[type]) {
types.push(typeObj);
}
typesSoFar[type] = true;
if (!maybeConsumeOp(tokens, '|')) {
break;
}
}
return types;
}
tokenRegex = RegExp('\\.\\.\\.|::|->|' + identifierRegex.source + '|\\S', 'g');
module.exports = function(input){
var tokens, e;
if (!input.length) {
throw new Error('No type specified.');
}
tokens = input.match(tokenRegex) || [];
if (in$('->', tokens)) {
throw new Error("Function types are not supported.\ To validate that something is a function, you may use 'Function'.");
}
try {
return consumeTypes(tokens);
} catch (e$) {
e = e$;
throw new Error(e.message + " - Remaining tokens: " + JSON.stringify(tokens) + " - Initial input: '" + input + "'");
}
};
function in$(x, xs){
var i = -1, l = xs.length >>> 0;
while (++i < l) if (x === xs[i]) return true;
return false;
}
}).call(this);

View File

@@ -0,0 +1,40 @@
{
"name": "type-check",
"version": "0.3.2",
"author": "George Zahariev <z@georgezahariev.com>",
"description": "type-check allows you to check the types of JavaScript values at runtime with a Haskell like type syntax.",
"homepage": "https://github.com/gkz/type-check",
"keywords": [
"type",
"check",
"checking",
"library"
],
"files": [
"lib",
"README.md",
"LICENSE"
],
"main": "./lib/",
"bugs": "https://github.com/gkz/type-check/issues",
"license": "MIT",
"engines": {
"node": ">= 0.8.0"
},
"repository": {
"type": "git",
"url": "git://github.com/gkz/type-check.git"
},
"scripts": {
"test": "make test"
},
"dependencies": {
"prelude-ls": "~1.1.2"
},
"devDependencies": {
"livescript": "~1.4.0",
"mocha": "~2.3.4",
"istanbul": "~0.4.1",
"browserify": "~12.0.1"
}
}

48
frontend/node_modules/static-eval/package.json generated vendored Normal file
View File

@@ -0,0 +1,48 @@
{
"name": "static-eval",
"version": "2.0.2",
"description": "evaluate statically-analyzable expressions",
"main": "index.js",
"dependencies": {
"escodegen": "^1.8.1"
},
"devDependencies": {
"esprima": "^2.7.3",
"tape": "^4.6.0"
},
"scripts": {
"test": "tape test/*.js"
},
"testling": {
"files": "test/*.js",
"browsers": [
"ie/8..latest",
"ff/latest",
"chrome/latest",
"opera/latest",
"safari/latest"
]
},
"repository": {
"type": "git",
"url": "git://github.com/substack/static-eval.git"
},
"homepage": "https://github.com/substack/static-eval",
"keywords": [
"static",
"eval",
"expression",
"esprima",
"ast",
"abstract",
"syntax",
"tree",
"analysis"
],
"author": {
"name": "James Halliday",
"email": "mail@substack.net",
"url": "http://substack.net"
},
"license": "MIT"
}

87
frontend/node_modules/static-eval/readme.markdown generated vendored Normal file
View File

@@ -0,0 +1,87 @@
# static-eval
evaluate statically-analyzable expressions
[![testling badge](https://ci.testling.com/substack/static-eval.png)](https://ci.testling.com/substack/static-eval)
[![build status](https://secure.travis-ci.org/substack/static-eval.png)](http://travis-ci.org/substack/static-eval)
# security
static-eval is like `eval`. It is intended for use in build scripts and code transformations, doing some evaluation at build time—it is **NOT** suitable for handling arbitrary untrusted user input. Malicious user input _can_ execute arbitrary code.
# example
``` js
var evaluate = require('static-eval');
var parse = require('esprima').parse;
var src = process.argv[2];
var ast = parse(src).body[0].expression;
console.log(evaluate(ast));
```
If you stick to simple expressions, the result is statically analyzable:
```
$ node '7*8+9'
65
$ node eval.js '[1,2,3+4*5-(5*11)]'
[ 1, 2, -32 ]
```
but if you use statements, undeclared identifiers, or syntax, the result is no
longer statically analyzable and `evaluate()` returns `undefined`:
```
$ node eval.js '1+2+3*n'
undefined
$ node eval.js 'x=5; x*2'
undefined
$ node eval.js '5-4*3'
-7
```
You can also declare variables and functions to use in the static evaluation:
``` js
var evaluate = require('static-eval');
var parse = require('esprima').parse;
var src = '[1,2,3+4*10+n,foo(3+5),obj[""+"x"].y]';
var ast = parse(src).body[0].expression;
console.log(evaluate(ast, {
n: 6,
foo: function (x) { return x * 100 },
obj: { x: { y: 555 } }
}));
```
# methods
``` js
var evaluate = require('static-eval');
```
## evaluate(ast, vars={})
Evaluate the [esprima](https://npmjs.org/package/esprima)-parsed abstract syntax
tree object `ast` with an optional collection of variables `vars` to use in the
static expression resolution.
If the expression contained in `ast` can't be statically resolved, `evaluate()`
returns undefined.
# install
With [npm](https://npmjs.org) do:
```
npm install static-eval
```
# license
MIT

82
frontend/node_modules/static-eval/test/eval.js generated vendored Normal file
View File

@@ -0,0 +1,82 @@
var test = require('tape');
var evaluate = require('../');
var parse = require('esprima').parse;
test('resolved', function (t) {
t.plan(1);
var src = '[1,2,3+4*10+(n||6),foo(3+5),obj[""+"x"].y]';
var ast = parse(src).body[0].expression;
var res = evaluate(ast, {
n: false,
foo: function (x) { return x * 100 },
obj: { x: { y: 555 } }
});
t.deepEqual(res, [ 1, 2, 49, 800, 555 ]);
});
test('unresolved', function (t) {
t.plan(1);
var src = '[1,2,3+4*10*z+n,foo(3+5),obj[""+"x"].y]';
var ast = parse(src).body[0].expression;
var res = evaluate(ast, {
n: 6,
foo: function (x) { return x * 100 },
obj: { x: { y: 555 } }
});
t.equal(res, undefined);
});
test('boolean', function (t) {
t.plan(1);
var src = '[ 1===2+3-16/4, [2]==2, [2]!==2, [2]!==[2] ]';
var ast = parse(src).body[0].expression;
t.deepEqual(evaluate(ast), [ true, true, true, true ]);
});
test('array methods', function(t) {
t.plan(1);
var src = '[1, 2, 3].map(function(n) { return n * 2 })';
var ast = parse(src).body[0].expression;
t.deepEqual(evaluate(ast), [2, 4, 6]);
});
test('array methods with vars', function(t) {
t.plan(1);
var src = '[1, 2, 3].map(function(n) { return n * x })';
var ast = parse(src).body[0].expression;
t.deepEqual(evaluate(ast, {x: 2}), [2, 4, 6]);
});
test('evaluate this', function(t) {
t.plan(1);
var src = 'this.x + this.y.z';
var ast = parse(src).body[0].expression;
var res = evaluate(ast, {
'this': { x: 1, y: { z: 100 } }
});
t.equal(res, 101);
});
test('FunctionExpression unresolved', function(t) {
t.plan(1);
var src = '(function(){console.log("Not Good")})';
var ast = parse(src).body[0].expression;
var res = evaluate(ast, {});
t.equal(res, undefined);
});
test('MemberExpressions from Functions unresolved', function(t) {
t.plan(1);
var src = '(function () {}).constructor';
var ast = parse(src).body[0].expression;
var res = evaluate(ast, {});
t.equal(res, undefined);
});

16
frontend/node_modules/static-eval/test/prop.js generated vendored Normal file
View File

@@ -0,0 +1,16 @@
var test = require('tape');
var evaluate = require('../');
var parse = require('esprima').parse;
test('function property', function (t) {
t.plan(1);
var src = '[1,2,3+4*10+n,beep.boop(3+5),obj[""+"x"].y]';
var ast = parse(src).body[0].expression;
var res = evaluate(ast, {
n: 6,
beep: { boop: function (x) { return x * 100 } },
obj: { x: { y: 555 } }
});
t.deepEqual(res, [ 1, 2, 49, 800, 555 ]);
});

View File

@@ -0,0 +1,33 @@
var test = require('tape');
var evaluate = require('../');
var parse = require('esprima').parse;
test('untagged template strings', function (t) {
t.plan(1);
var src = '`${1},${2 + n},${`4,5`}`';
var ast = parse(src).body[0].expression;
var res = evaluate(ast, {
n: 6
});
t.deepEqual(res, '1,8,4,5');
});
test('tagged template strings', function (t) {
t.plan(3);
var src = 'template`${1},${2 + n},${`4,5`}`';
var ast = parse(src).body[0].expression;
var res = evaluate(ast, {
template: function (strings) {
t.deepEqual(strings, ['', ',', ',', '']);
var values = [].slice.call(arguments, 1);
t.deepEqual(values, [1, 8, '4,5']);
return 'foo';
},
n: 6
});
t.deepEqual(res, 'foo');
})