0.2.0 - Mid migration

This commit is contained in:
Daniel Mason 2022-04-25 14:47:15 +12:00
parent 139e6a915e
commit 7e38fdbd7d
42393 changed files with 5358157 additions and 62 deletions

21
web/node_modules/escodegen/LICENSE.BSD generated vendored Normal file
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.

84
web/node_modules/escodegen/README.md generated vendored Normal file
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.

77
web/node_modules/escodegen/bin/escodegen.js generated vendored Executable file
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 : */

64
web/node_modules/escodegen/bin/esgenerate.js generated vendored Executable file
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 : */

2647
web/node_modules/escodegen/escodegen.js generated vendored Normal file

File diff suppressed because it is too large Load diff

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,801 @@
/*
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',
ChainExpression: 'ChainExpression',
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'],
ChainExpression: ['expression'],
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;
}
function candidateExistsInLeaveList(leavelist, candidate) {
for (var i = leavelist.length - 1; i >= 0; --i) {
if (leavelist[i].node === candidate) {
return true;
}
}
return false;
}
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 (candidateExistsInLeaveList(leavelist, 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)) {
if (candidateExistsInLeaveList(leavelist, candidate)) {
continue;
}
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.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": "5.2.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"
}
}

22
web/node_modules/escodegen/node_modules/levn/LICENSE generated vendored Normal file
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.

196
web/node_modules/escodegen/node_modules/levn/README.md generated vendored Normal file
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,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"
}
}

62
web/node_modules/escodegen/package.json generated vendored Normal file
View file

@ -0,0 +1,62 @@
{
"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": "2.0.0",
"engines": {
"node": ">=6.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": "^5.2.0",
"esutils": "^2.0.2",
"esprima": "^4.0.1",
"optionator": "^0.8.1"
},
"optionalDependencies": {
"source-map": "~0.6.1"
},
"devDependencies": {
"acorn": "^7.3.1",
"bluebird": "^3.4.7",
"bower-registry-client": "^1.0.0",
"chai": "^4.2.0",
"chai-exclude": "^2.0.2",
"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"
}
}