mirror of https://github.com/zulip/zulip.git
Import Handlebars compiler and dependencies
Storing these in Git seems kind of weird, but seems to be [1] the done thing. I have to say, it's a lot more appealing than getting 3 packages from npm installed globally on every prod and dev machine -- we already have too much of that with 'pip install'. We can upgrade these in the future by running 'npm update' in the repo root directory. [1] http://www.futurealoof.com/posts/nodemodules-in-git.html (imported from commit 60a9d6a7cafe742442d87e9f3abc25750e179780)
This commit is contained in:
parent
c375de29ad
commit
9b9d85eb36
|
@ -0,0 +1 @@
|
|||
../handlebars/bin/handlebars
|
|
@ -0,0 +1,52 @@
|
|||
{
|
||||
"predef": [
|
||||
"console",
|
||||
"Ember",
|
||||
"DS",
|
||||
"Handlebars",
|
||||
"Metamorph",
|
||||
"ember_assert",
|
||||
"ember_warn",
|
||||
"ember_deprecate",
|
||||
"ember_deprecateFunc",
|
||||
"require",
|
||||
"suite",
|
||||
"equal",
|
||||
"equals",
|
||||
"test",
|
||||
"testBoth",
|
||||
"raises",
|
||||
"deepEqual",
|
||||
"start",
|
||||
"stop",
|
||||
"ok",
|
||||
"strictEqual",
|
||||
"module"
|
||||
],
|
||||
|
||||
"node" : true,
|
||||
"es5" : true,
|
||||
"browser" : true,
|
||||
|
||||
"boss" : true,
|
||||
"curly": false,
|
||||
"debug": false,
|
||||
"devel": false,
|
||||
"eqeqeq": true,
|
||||
"evil": true,
|
||||
"forin": false,
|
||||
"immed": false,
|
||||
"laxbreak": false,
|
||||
"newcap": true,
|
||||
"noarg": true,
|
||||
"noempty": false,
|
||||
"nonew": false,
|
||||
"nomen": false,
|
||||
"onevar": false,
|
||||
"plusplus": false,
|
||||
"regexp": false,
|
||||
"undef": true,
|
||||
"sub": true,
|
||||
"strict": false,
|
||||
"white": false
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
.DS_Store
|
||||
.gitignore
|
||||
.rvmrc
|
||||
Gemfile
|
||||
Gemfile.lock
|
||||
Rakefile
|
||||
bench/*
|
||||
spec/*
|
||||
src/*
|
||||
vendor/*
|
|
@ -0,0 +1 @@
|
|||
-cfs
|
|
@ -0,0 +1,19 @@
|
|||
Copyright (C) 2011 by Yehuda Katz
|
||||
|
||||
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.
|
|
@ -0,0 +1,317 @@
|
|||
[![Build Status](https://secure.travis-ci.org/wycats/handlebars.js.png)](http://travis-ci.org/wycats/handlebars.js)
|
||||
|
||||
Handlebars.js
|
||||
=============
|
||||
|
||||
Handlebars.js is an extension to the [Mustache templating language](http://mustache.github.com/) created by Chris Wanstrath. Handlebars.js and Mustache are both logicless templating languages that keep the view and the code separated like we all know they should be.
|
||||
|
||||
Checkout the official Handlebars docs site at [http://www.handlebarsjs.com](http://www.handlebarsjs.com).
|
||||
|
||||
|
||||
Installing
|
||||
----------
|
||||
Installing Handlebars is easy. Simply [download the package from GitHub](https://github.com/wycats/handlebars.js/archives/master) and add it to your web pages (you should usually use the most recent version).
|
||||
|
||||
Usage
|
||||
-----
|
||||
In general, the syntax of Handlebars.js templates is a superset of Mustache templates. For basic syntax, check out the [Mustache manpage](http://mustache.github.com/mustache.5.html).
|
||||
|
||||
Once you have a template, use the Handlebars.compile method to compile the template into a function. The generated function takes a context argument, which will be used to render the template.
|
||||
|
||||
```js
|
||||
var source = "<p>Hello, my name is {{name}}. I am from {{hometown}}. I have " +
|
||||
"{{kids.length}} kids:</p>" +
|
||||
"<ul>{{#kids}}<li>{{name}} is {{age}}</li>{{/kids}}</ul>";
|
||||
var template = Handlebars.compile(source);
|
||||
|
||||
var data = { "name": "Alan", "hometown": "Somewhere, TX",
|
||||
"kids": [{"name": "Jimmy", "age": "12"}, {"name": "Sally", "age": "4"}]};
|
||||
var result = template(data);
|
||||
|
||||
// Would render:
|
||||
// <p>Hello, my name is Alan. I am from Somewhere, TX. I have 2 kids:</p>
|
||||
// <ul>
|
||||
// <li>Jimmy is 12</li>
|
||||
// <li>Sally is 4</li>
|
||||
// </ul>
|
||||
```
|
||||
|
||||
|
||||
Registering Helpers
|
||||
-------------------
|
||||
|
||||
You can register helpers that Handlebars will use when evaluating your
|
||||
template. Here's an example, which assumes that your objects have a URL
|
||||
embedded in them, as well as the text for a link:
|
||||
|
||||
```js
|
||||
Handlebars.registerHelper('link_to', function(context) {
|
||||
return "<a href='" + context.url + "'>" + context.body + "</a>";
|
||||
});
|
||||
|
||||
var context = { posts: [{url: "/hello-world", body: "Hello World!"}] };
|
||||
var source = "<ul>{{#posts}}<li>{{{link_to this}}}</li>{{/posts}}</ul>"
|
||||
|
||||
var template = Handlebars.compile(source);
|
||||
template(context);
|
||||
|
||||
// Would render:
|
||||
//
|
||||
// <ul>
|
||||
// <li><a href='/hello-world'>Hello World!</a></li>
|
||||
// </ul>
|
||||
```
|
||||
|
||||
Escaping
|
||||
--------
|
||||
|
||||
By default, the `{{expression}}` syntax will escape its contents. This
|
||||
helps to protect you against accidental XSS problems caused by malicious
|
||||
data passed from the server as JSON.
|
||||
|
||||
To explicitly *not* escape the contents, use the triple-mustache
|
||||
(`{{{}}}`). You have seen this used in the above example.
|
||||
|
||||
|
||||
Differences Between Handlebars.js and Mustache
|
||||
----------------------------------------------
|
||||
Handlebars.js adds a couple of additional features to make writing templates easier and also changes a tiny detail of how partials work.
|
||||
|
||||
### Paths
|
||||
|
||||
Handlebars.js supports an extended expression syntax that we call paths. Paths are made up of typical expressions and . characters. Expressions allow you to not only display data from the current context, but to display data from contexts that are descendents and ancestors of the current context.
|
||||
|
||||
To display data from descendent contexts, use the `.` character. So, for example, if your data were structured like:
|
||||
|
||||
```js
|
||||
var data = {"person": { "name": "Alan" }, company: {"name": "Rad, Inc." } };
|
||||
```
|
||||
|
||||
you could display the person's name from the top-level context with the following expression:
|
||||
|
||||
```
|
||||
{{person.name}}
|
||||
```
|
||||
|
||||
You can backtrack using `../`. For example, if you've already traversed into the person object you could still display the company's name with an expression like `{{../company.name}}`, so:
|
||||
|
||||
```
|
||||
{{#person}}{{name}} - {{../company.name}}{{/person}}
|
||||
```
|
||||
|
||||
would render:
|
||||
|
||||
```
|
||||
Alan - Rad, Inc.
|
||||
```
|
||||
|
||||
### Strings
|
||||
|
||||
When calling a helper, you can pass paths or Strings as parameters. For
|
||||
instance:
|
||||
|
||||
```js
|
||||
Handlebars.registerHelper('link_to', function(title, context) {
|
||||
return "<a href='/posts" + context.url + "'>" + title + "!</a>"
|
||||
});
|
||||
|
||||
var context = { posts: [{url: "/hello-world", body: "Hello World!"}] };
|
||||
var source = '<ul>{{#posts}}<li>{{{link_to "Post" this}}}</li>{{/posts}}</ul>'
|
||||
|
||||
var template = Handlebars.compile(source);
|
||||
template(context);
|
||||
|
||||
// Would render:
|
||||
//
|
||||
// <ul>
|
||||
// <li><a href='/posts/hello-world'>Post!</a></li>
|
||||
// </ul>
|
||||
```
|
||||
|
||||
When you pass a String as a parameter to a helper, the literal String
|
||||
gets passed to the helper function.
|
||||
|
||||
|
||||
### Block Helpers
|
||||
|
||||
Handlebars.js also adds the ability to define block helpers. Block helpers are functions that can be called from anywhere in the template. Here's an example:
|
||||
|
||||
```js
|
||||
var source = "<ul>{{#people}}<li>{{#link}}{{name}}{{/link}}</li>{{/people}}</ul>";
|
||||
Handlebars.registerHelper('link', function(options) {
|
||||
return '<a href="/people/' + this.id + '">' + options.fn(this) + '</a>';
|
||||
});
|
||||
var template = Handlebars.compile(source);
|
||||
|
||||
var data = { "people": [
|
||||
{ "name": "Alan", "id": 1 },
|
||||
{ "name": "Yehuda", "id": 2 }
|
||||
]};
|
||||
template(data);
|
||||
|
||||
// Should render:
|
||||
// <ul>
|
||||
// <li><a href="/people/1">Alan</a></li>
|
||||
// <li><a href="/people/2">Yehuda</a></li>
|
||||
// </ul>
|
||||
```
|
||||
|
||||
Whenever the block helper is called it is given two parameters, the argument that is passed to the helper, or the current context if no argument is passed and the compiled contents of the block. Inside of the block helper the value of `this` is the current context, wrapped to include a method named `__get__` that helps translate paths into values within the helpers.
|
||||
|
||||
### Partials
|
||||
|
||||
You can register additional templates as partials, which will be used by
|
||||
Handlebars when it encounters a partial (`{{> partialName}}`). Partials
|
||||
can either be String templates or compiled template functions. Here's an
|
||||
example:
|
||||
|
||||
```js
|
||||
var source = "<ul>{{#people}}<li>{{> link}}</li>{{/people}}</ul>";
|
||||
|
||||
Handlebars.registerPartial('link', '<a href="/people/{{id}}">{{name}}</a>')
|
||||
var template = Handlebars.compile(source);
|
||||
|
||||
var data = { "people": [
|
||||
{ "name": "Alan", "id": 1 },
|
||||
{ "name": "Yehuda", "id": 2 }
|
||||
]};
|
||||
|
||||
template(data);
|
||||
|
||||
// Should render:
|
||||
// <ul>
|
||||
// <li><a href="/people/1">Alan</a></li>
|
||||
// <li><a href="/people/2">Yehuda</a></li>
|
||||
// </ul>
|
||||
```
|
||||
|
||||
### Comments
|
||||
|
||||
You can add comments to your templates with the following syntax:
|
||||
|
||||
```js
|
||||
{{! This is a comment }}
|
||||
```
|
||||
|
||||
You can also use real html comments if you want them to end up in the output.
|
||||
|
||||
```html
|
||||
<div>
|
||||
{{! This comment will not end up in the output }}
|
||||
<!-- This comment will show up in the output -->
|
||||
</div>
|
||||
```
|
||||
|
||||
|
||||
Precompiling Templates
|
||||
----------------------
|
||||
|
||||
Handlebars allows templates to be precompiled and included as javascript
|
||||
code rather than the handlebars template allowing for faster startup time.
|
||||
|
||||
### Installation
|
||||
The precompiler script may be installed via npm using the `npm install -g handlebars`
|
||||
command.
|
||||
|
||||
### Usage
|
||||
|
||||
<pre>
|
||||
Precompile handlebar templates.
|
||||
Usage: handlebars template...
|
||||
|
||||
Options:
|
||||
-a, --amd Create an AMD format function (allows loading with RequireJS) [boolean]
|
||||
-f, --output Output File [string]
|
||||
-k, --known Known helpers [string]
|
||||
-o, --knownOnly Known helpers only [boolean]
|
||||
-m, --min Minimize output [boolean]
|
||||
-s, --simple Output template function only. [boolean]
|
||||
-r, --root Template root. Base value that will be stripped from template names. [string]
|
||||
</pre>
|
||||
|
||||
If using the precompiler's normal mode, the resulting templates will be stored
|
||||
to the `Handlebars.templates` object using the relative template name sans the
|
||||
extension. These templates may be executed in the same manner as templates.
|
||||
|
||||
If using the simple mode the precompiler will generate a single javascript method.
|
||||
To execute this method it must be passed to the using the `Handlebars.template`
|
||||
method and the resulting object may be as normal.
|
||||
|
||||
### Optimizations
|
||||
|
||||
- Rather than using the full _handlebars.js_ library, implementations that
|
||||
do not need to compile templates at runtime may include _handlebars.runtime.js_
|
||||
whose min+gzip size is approximately 1k.
|
||||
- If a helper is known to exist in the target environment they may be defined
|
||||
using the `--known name` argument may be used to optimize accesses to these
|
||||
helpers for size and speed.
|
||||
- When all helpers are known in advance the `--knownOnly` argument may be used
|
||||
to optimize all block helper references.
|
||||
|
||||
|
||||
Performance
|
||||
-----------
|
||||
|
||||
In a rough performance test, precompiled Handlebars.js templates (in the original version of Handlebars.js) rendered in about half the time of Mustache templates. It would be a shame if it were any other way, since they were precompiled, but the difference in architecture does have some big performance advantages. Justin Marney, a.k.a. [gotascii](http://github.com/gotascii), confirmed that with an [independent test](http://sorescode.com/2010/09/12/benchmarks.html). The rewritten Handlebars (current version) is faster than the old version, and we will have some benchmarks in the near future.
|
||||
|
||||
|
||||
Building
|
||||
--------
|
||||
|
||||
To build handlebars, just run `rake release`, and you will get two files
|
||||
in the `dist` directory.
|
||||
|
||||
|
||||
Upgrading
|
||||
---------
|
||||
|
||||
When upgrading from the Handlebars 0.9 series, be aware that the
|
||||
signature for passing custom helpers or partials to templates has
|
||||
changed.
|
||||
|
||||
Instead of:
|
||||
|
||||
```js
|
||||
template(context, helpers, partials, [data])
|
||||
```
|
||||
|
||||
Use:
|
||||
|
||||
```js
|
||||
template(context, {helpers: helpers, partials: partials, data: data})
|
||||
```
|
||||
|
||||
Known Issues
|
||||
------------
|
||||
* Handlebars.js can be cryptic when there's an error while rendering.
|
||||
* Using a variable, helper, or partial named `class` causes errors in IE browsers. (Instead, use `className`)
|
||||
|
||||
Handlebars in the Wild
|
||||
-----------------
|
||||
* [jblotus](http://github.com/jblotus) created [http://tryhandlebarsjs.com](http://tryhandlebarsjs.com) for anyone who would
|
||||
like to try out Handlebars.js in their browser.
|
||||
* Don Park wrote an Express.js view engine adapter for Handlebars.js called [hbs](http://github.com/donpark/hbs).
|
||||
* [sammy.js](http://github.com/quirkey/sammy) by Aaron Quint, a.k.a. quirkey, supports Handlebars.js as one of its template plugins.
|
||||
* [SproutCore](http://www.sproutcore.com) uses Handlebars.js as its main templating engine, extending it with automatic data binding support.
|
||||
* [Ember.js](http://www.emberjs.com) makes Handlebars.js the primary way to structure your views, also with automatic data binding support.
|
||||
* Les Hill (@leshill) wrote a Rails Asset Pipeline gem named [handlebars_assets](http://github.com/leshill/handlebars_assets).
|
||||
|
||||
Helping Out
|
||||
-----------
|
||||
To build Handlebars.js you'll need a few things installed.
|
||||
|
||||
* Node.js
|
||||
* Jison, for building the compiler - `npm install jison`
|
||||
* Ruby
|
||||
* therubyracer, for running tests - `gem install therubyracer`
|
||||
* rspec, for running tests - `gem install rspec`
|
||||
|
||||
There's a Gemfile in the repo, so you can run `bundle` to install rspec and therubyracer if you've got bundler installed.
|
||||
|
||||
To build Handlebars.js from scratch, you'll want to run `rake compile` in the root of the project. That will build Handlebars and output the results to the dist/ folder. To run tests, run `rake spec`. You can also run our set of benchmarks with `rake bench`.
|
||||
|
||||
If you notice any problems, please report them to the GitHub issue tracker at [http://github.com/wycats/handlebars.js/issues](http://github.com/wycats/handlebars.js/issues). Feel free to contact commondream or wycats through GitHub with any other questions or feature requests. To submit changes fork the project and send a pull request.
|
||||
|
||||
License
|
||||
-------
|
||||
Handlebars.js is released under the MIT license.
|
|
@ -0,0 +1,193 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
var optimist = require('optimist')
|
||||
.usage('Precompile handlebar templates.\nUsage: $0 template...', {
|
||||
'f': {
|
||||
'type': 'string',
|
||||
'description': 'Output File',
|
||||
'alias': 'output'
|
||||
},
|
||||
'a': {
|
||||
'type': 'boolean',
|
||||
'description': 'Exports amd style (require.js)',
|
||||
'alias': 'amd'
|
||||
},
|
||||
'c': {
|
||||
'type': 'string',
|
||||
'description': 'Exports CommonJS style, path to Handlebars module',
|
||||
'alias': 'commonjs',
|
||||
'default': null
|
||||
},
|
||||
'h': {
|
||||
'type': 'string',
|
||||
'description': 'Path to handlebar.js (only valid for amd-style)',
|
||||
'alias': 'handlebarPath',
|
||||
'default': ''
|
||||
},
|
||||
'k': {
|
||||
'type': 'string',
|
||||
'description': 'Known helpers',
|
||||
'alias': 'known'
|
||||
},
|
||||
'o': {
|
||||
'type': 'boolean',
|
||||
'description': 'Known helpers only',
|
||||
'alias': 'knownOnly'
|
||||
},
|
||||
'm': {
|
||||
'type': 'boolean',
|
||||
'description': 'Minimize output',
|
||||
'alias': 'min'
|
||||
},
|
||||
'n': {
|
||||
'type': 'string',
|
||||
'description': 'Template namespace',
|
||||
'alias': 'namespace',
|
||||
'default': 'Handlebars.templates'
|
||||
},
|
||||
's': {
|
||||
'type': 'boolean',
|
||||
'description': 'Output template function only.',
|
||||
'alias': 'simple'
|
||||
},
|
||||
'r': {
|
||||
'type': 'string',
|
||||
'description': 'Template root. Base value that will be stripped from template names.',
|
||||
'alias': 'root'
|
||||
},
|
||||
'p' : {
|
||||
'type': 'boolean',
|
||||
'description': 'Compiling a partial template',
|
||||
'alias': 'partial'
|
||||
},
|
||||
'd' : {
|
||||
'type': 'boolean',
|
||||
'description': 'Include data when compiling',
|
||||
'alias': 'data'
|
||||
}
|
||||
})
|
||||
|
||||
.check(function(argv) {
|
||||
var template = [0];
|
||||
if (!argv._.length) {
|
||||
throw 'Must define at least one template or directory.';
|
||||
}
|
||||
|
||||
argv._.forEach(function(template) {
|
||||
try {
|
||||
fs.statSync(template);
|
||||
} catch (err) {
|
||||
throw 'Unable to open template file "' + template + '"';
|
||||
}
|
||||
});
|
||||
})
|
||||
.check(function(argv) {
|
||||
if (argv.simple && argv.min) {
|
||||
throw 'Unable to minimze simple output';
|
||||
}
|
||||
if (argv.simple && (argv._.length !== 1 || fs.statSync(argv._[0]).isDirectory())) {
|
||||
throw 'Unable to output multiple templates in simple mode';
|
||||
}
|
||||
});
|
||||
|
||||
var fs = require('fs'),
|
||||
handlebars = require('../lib/handlebars'),
|
||||
basename = require('path').basename,
|
||||
uglify = require('uglify-js');
|
||||
|
||||
var argv = optimist.argv,
|
||||
template = argv._[0];
|
||||
|
||||
// Convert the known list into a hash
|
||||
var known = {};
|
||||
if (argv.known && !Array.isArray(argv.known)) {
|
||||
argv.known = [argv.known];
|
||||
}
|
||||
if (argv.known) {
|
||||
for (var i = 0, len = argv.known.length; i < len; i++) {
|
||||
known[argv.known[i]] = true;
|
||||
}
|
||||
}
|
||||
|
||||
var output = [];
|
||||
if (!argv.simple) {
|
||||
if (argv.amd) {
|
||||
output.push('define([\'' + argv.handlebarPath + 'handlebars\'], function(Handlebars) {\n');
|
||||
} else if (argv.commonjs) {
|
||||
output.push('var Handlebars = require("' + argv.commonjs + '");');
|
||||
} else {
|
||||
output.push('(function() {\n');
|
||||
}
|
||||
output.push(' var template = Handlebars.template, templates = ');
|
||||
output.push(argv.namespace);
|
||||
output.push(' = ');
|
||||
output.push(argv.namespace);
|
||||
output.push(' || {};\n');
|
||||
}
|
||||
function processTemplate(template, root) {
|
||||
var path = template,
|
||||
stat = fs.statSync(path);
|
||||
if (stat.isDirectory()) {
|
||||
fs.readdirSync(template).map(function(file) {
|
||||
var path = template + '/' + file;
|
||||
|
||||
if (/\.handlebars$/.test(path) || fs.statSync(path).isDirectory()) {
|
||||
processTemplate(path, root || template);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
var data = fs.readFileSync(path, 'utf8');
|
||||
|
||||
var options = {
|
||||
knownHelpers: known,
|
||||
knownHelpersOnly: argv.o
|
||||
};
|
||||
|
||||
if (argv.data) {
|
||||
options.data = true;
|
||||
}
|
||||
|
||||
// Clean the template name
|
||||
if (!root) {
|
||||
template = basename(template);
|
||||
} else if (template.indexOf(root) === 0) {
|
||||
template = template.substring(root.length+1);
|
||||
}
|
||||
template = template.replace(/\.handlebars$/, '');
|
||||
|
||||
if (argv.simple) {
|
||||
output.push(handlebars.precompile(data, options) + '\n');
|
||||
} else if (argv.partial) {
|
||||
output.push('Handlebars.partials[\'' + template + '\'] = template(' + handlebars.precompile(data, options) + ');\n');
|
||||
} else {
|
||||
output.push('templates[\'' + template + '\'] = template(' + handlebars.precompile(data, options) + ');\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
argv._.forEach(function(template) {
|
||||
processTemplate(template, argv.root);
|
||||
});
|
||||
|
||||
// Output the content
|
||||
if (!argv.simple) {
|
||||
if (argv.amd) {
|
||||
output.push('});');
|
||||
} else if (!argv.commonjs) {
|
||||
output.push('})();');
|
||||
}
|
||||
}
|
||||
output = output.join('');
|
||||
|
||||
if (argv.min) {
|
||||
var ast = uglify.parser.parse(output);
|
||||
ast = uglify.uglify.ast_mangle(ast);
|
||||
ast = uglify.uglify.ast_squeeze(ast);
|
||||
output = uglify.uglify.gen_code(ast);
|
||||
}
|
||||
|
||||
if (argv.output) {
|
||||
fs.writeFileSync(argv.output, output, 'utf8');
|
||||
} else {
|
||||
console.log(output);
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,320 @@
|
|||
/*
|
||||
|
||||
Copyright (C) 2011 by Yehuda Katz
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
// lib/handlebars/base.js
|
||||
|
||||
var Handlebars = {};
|
||||
|
||||
(function(Handlebars) {
|
||||
|
||||
Handlebars.VERSION = "1.0.0-rc.3";
|
||||
Handlebars.COMPILER_REVISION = 2;
|
||||
|
||||
Handlebars.REVISION_CHANGES = {
|
||||
1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it
|
||||
2: '>= 1.0.0-rc.3'
|
||||
};
|
||||
|
||||
Handlebars.helpers = {};
|
||||
Handlebars.partials = {};
|
||||
|
||||
Handlebars.registerHelper = function(name, fn, inverse) {
|
||||
if(inverse) { fn.not = inverse; }
|
||||
this.helpers[name] = fn;
|
||||
};
|
||||
|
||||
Handlebars.registerPartial = function(name, str) {
|
||||
this.partials[name] = str;
|
||||
};
|
||||
|
||||
Handlebars.registerHelper('helperMissing', function(arg) {
|
||||
if(arguments.length === 2) {
|
||||
return undefined;
|
||||
} else {
|
||||
throw new Error("Could not find property '" + arg + "'");
|
||||
}
|
||||
});
|
||||
|
||||
var toString = Object.prototype.toString, functionType = "[object Function]";
|
||||
|
||||
Handlebars.registerHelper('blockHelperMissing', function(context, options) {
|
||||
var inverse = options.inverse || function() {}, fn = options.fn;
|
||||
|
||||
var type = toString.call(context);
|
||||
|
||||
if(type === functionType) { context = context.call(this); }
|
||||
|
||||
if(context === true) {
|
||||
return fn(this);
|
||||
} else if(context === false || context == null) {
|
||||
return inverse(this);
|
||||
} else if(type === "[object Array]") {
|
||||
if(context.length > 0) {
|
||||
return Handlebars.helpers.each(context, options);
|
||||
} else {
|
||||
return inverse(this);
|
||||
}
|
||||
} else {
|
||||
return fn(context);
|
||||
}
|
||||
});
|
||||
|
||||
Handlebars.K = function() {};
|
||||
|
||||
Handlebars.createFrame = Object.create || function(object) {
|
||||
Handlebars.K.prototype = object;
|
||||
var obj = new Handlebars.K();
|
||||
Handlebars.K.prototype = null;
|
||||
return obj;
|
||||
};
|
||||
|
||||
Handlebars.logger = {
|
||||
DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3, level: 3,
|
||||
|
||||
methodMap: {0: 'debug', 1: 'info', 2: 'warn', 3: 'error'},
|
||||
|
||||
// can be overridden in the host environment
|
||||
log: function(level, obj) {
|
||||
if (Handlebars.logger.level <= level) {
|
||||
var method = Handlebars.logger.methodMap[level];
|
||||
if (typeof console !== 'undefined' && console[method]) {
|
||||
console[method].call(console, obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Handlebars.log = function(level, obj) { Handlebars.logger.log(level, obj); };
|
||||
|
||||
Handlebars.registerHelper('each', function(context, options) {
|
||||
var fn = options.fn, inverse = options.inverse;
|
||||
var i = 0, ret = "", data;
|
||||
|
||||
if (options.data) {
|
||||
data = Handlebars.createFrame(options.data);
|
||||
}
|
||||
|
||||
if(context && typeof context === 'object') {
|
||||
if(context instanceof Array){
|
||||
for(var j = context.length; i<j; i++) {
|
||||
if (data) { data.index = i; }
|
||||
ret = ret + fn(context[i], { data: data });
|
||||
}
|
||||
} else {
|
||||
for(var key in context) {
|
||||
if(context.hasOwnProperty(key)) {
|
||||
if(data) { data.key = key; }
|
||||
ret = ret + fn(context[key], {data: data});
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(i === 0){
|
||||
ret = inverse(this);
|
||||
}
|
||||
|
||||
return ret;
|
||||
});
|
||||
|
||||
Handlebars.registerHelper('if', function(context, options) {
|
||||
var type = toString.call(context);
|
||||
if(type === functionType) { context = context.call(this); }
|
||||
|
||||
if(!context || Handlebars.Utils.isEmpty(context)) {
|
||||
return options.inverse(this);
|
||||
} else {
|
||||
return options.fn(this);
|
||||
}
|
||||
});
|
||||
|
||||
Handlebars.registerHelper('unless', function(context, options) {
|
||||
var fn = options.fn, inverse = options.inverse;
|
||||
options.fn = inverse;
|
||||
options.inverse = fn;
|
||||
|
||||
return Handlebars.helpers['if'].call(this, context, options);
|
||||
});
|
||||
|
||||
Handlebars.registerHelper('with', function(context, options) {
|
||||
return options.fn(context);
|
||||
});
|
||||
|
||||
Handlebars.registerHelper('log', function(context, options) {
|
||||
var level = options.data && options.data.level != null ? parseInt(options.data.level, 10) : 1;
|
||||
Handlebars.log(level, context);
|
||||
});
|
||||
|
||||
}(Handlebars));
|
||||
;
|
||||
// lib/handlebars/utils.js
|
||||
|
||||
var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
|
||||
|
||||
Handlebars.Exception = function(message) {
|
||||
var tmp = Error.prototype.constructor.apply(this, arguments);
|
||||
|
||||
// Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.
|
||||
for (var idx = 0; idx < errorProps.length; idx++) {
|
||||
this[errorProps[idx]] = tmp[errorProps[idx]];
|
||||
}
|
||||
};
|
||||
Handlebars.Exception.prototype = new Error();
|
||||
|
||||
// Build out our basic SafeString type
|
||||
Handlebars.SafeString = function(string) {
|
||||
this.string = string;
|
||||
};
|
||||
Handlebars.SafeString.prototype.toString = function() {
|
||||
return this.string.toString();
|
||||
};
|
||||
|
||||
(function() {
|
||||
var escape = {
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': """,
|
||||
"'": "'",
|
||||
"`": "`"
|
||||
};
|
||||
|
||||
var badChars = /[&<>"'`]/g;
|
||||
var possible = /[&<>"'`]/;
|
||||
|
||||
var escapeChar = function(chr) {
|
||||
return escape[chr] || "&";
|
||||
};
|
||||
|
||||
Handlebars.Utils = {
|
||||
escapeExpression: function(string) {
|
||||
// don't escape SafeStrings, since they're already safe
|
||||
if (string instanceof Handlebars.SafeString) {
|
||||
return string.toString();
|
||||
} else if (string == null || string === false) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if(!possible.test(string)) { return string; }
|
||||
return string.replace(badChars, escapeChar);
|
||||
},
|
||||
|
||||
isEmpty: function(value) {
|
||||
if (!value && value !== 0) {
|
||||
return true;
|
||||
} else if(Object.prototype.toString.call(value) === "[object Array]" && value.length === 0) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
};
|
||||
})();
|
||||
;
|
||||
// lib/handlebars/runtime.js
|
||||
|
||||
Handlebars.VM = {
|
||||
template: function(templateSpec) {
|
||||
// Just add water
|
||||
var container = {
|
||||
escapeExpression: Handlebars.Utils.escapeExpression,
|
||||
invokePartial: Handlebars.VM.invokePartial,
|
||||
programs: [],
|
||||
program: function(i, fn, data) {
|
||||
var programWrapper = this.programs[i];
|
||||
if(data) {
|
||||
return Handlebars.VM.program(fn, data);
|
||||
} else if(programWrapper) {
|
||||
return programWrapper;
|
||||
} else {
|
||||
programWrapper = this.programs[i] = Handlebars.VM.program(fn);
|
||||
return programWrapper;
|
||||
}
|
||||
},
|
||||
programWithDepth: Handlebars.VM.programWithDepth,
|
||||
noop: Handlebars.VM.noop,
|
||||
compilerInfo: null
|
||||
};
|
||||
|
||||
return function(context, options) {
|
||||
options = options || {};
|
||||
var result = templateSpec.call(container, Handlebars, context, options.helpers, options.partials, options.data);
|
||||
|
||||
var compilerInfo = container.compilerInfo || [],
|
||||
compilerRevision = compilerInfo[0] || 1,
|
||||
currentRevision = Handlebars.COMPILER_REVISION;
|
||||
|
||||
if (compilerRevision !== currentRevision) {
|
||||
if (compilerRevision < currentRevision) {
|
||||
var runtimeVersions = Handlebars.REVISION_CHANGES[currentRevision],
|
||||
compilerVersions = Handlebars.REVISION_CHANGES[compilerRevision];
|
||||
throw "Template was precompiled with an older version of Handlebars than the current runtime. "+
|
||||
"Please update your precompiler to a newer version ("+runtimeVersions+") or downgrade your runtime to an older version ("+compilerVersions+").";
|
||||
} else {
|
||||
// Use the embedded version info since the runtime doesn't know about this revision yet
|
||||
throw "Template was precompiled with a newer version of Handlebars than the current runtime. "+
|
||||
"Please update your runtime to a newer version ("+compilerInfo[1]+").";
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
},
|
||||
|
||||
programWithDepth: function(fn, data, $depth) {
|
||||
var args = Array.prototype.slice.call(arguments, 2);
|
||||
|
||||
return function(context, options) {
|
||||
options = options || {};
|
||||
|
||||
return fn.apply(this, [context, options.data || data].concat(args));
|
||||
};
|
||||
},
|
||||
program: function(fn, data) {
|
||||
return function(context, options) {
|
||||
options = options || {};
|
||||
|
||||
return fn(context, options.data || data);
|
||||
};
|
||||
},
|
||||
noop: function() { return ""; },
|
||||
invokePartial: function(partial, name, context, helpers, partials, data) {
|
||||
var options = { helpers: helpers, partials: partials, data: data };
|
||||
|
||||
if(partial === undefined) {
|
||||
throw new Handlebars.Exception("The partial " + name + " could not be found");
|
||||
} else if(partial instanceof Function) {
|
||||
return partial(context, options);
|
||||
} else if (!Handlebars.compile) {
|
||||
throw new Handlebars.Exception("The partial " + name + " could not be compiled when running in runtime-only mode");
|
||||
} else {
|
||||
partials[name] = Handlebars.compile(partial, {data: data !== undefined});
|
||||
return partials[name](context, options);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Handlebars.template = Handlebars.VM.template;
|
||||
;
|
|
@ -0,0 +1,32 @@
|
|||
var handlebars = require("./handlebars/base"),
|
||||
|
||||
// Each of these augment the Handlebars object. No need to setup here.
|
||||
// (This is done to easily share code between commonjs and browse envs)
|
||||
utils = require("./handlebars/utils"),
|
||||
compiler = require("./handlebars/compiler"),
|
||||
runtime = require("./handlebars/runtime");
|
||||
|
||||
var create = function() {
|
||||
var hb = handlebars.create();
|
||||
|
||||
utils.attach(hb);
|
||||
compiler.attach(hb);
|
||||
runtime.attach(hb);
|
||||
|
||||
return hb;
|
||||
};
|
||||
|
||||
var Handlebars = create();
|
||||
Handlebars.create = create;
|
||||
|
||||
module.exports = Handlebars; // instantiate an instance
|
||||
|
||||
// BEGIN(BROWSER)
|
||||
|
||||
// END(BROWSER)
|
||||
|
||||
// USAGE:
|
||||
// var handlebars = require('handlebars');
|
||||
|
||||
// var singleton = handlebars.Handlebars,
|
||||
// local = handlebars.create();
|
|
@ -0,0 +1,155 @@
|
|||
/*jshint eqnull: true */
|
||||
|
||||
module.exports.create = function() {
|
||||
|
||||
// BEGIN(BROWSER)
|
||||
|
||||
var Handlebars = {};
|
||||
|
||||
(function(Handlebars) {
|
||||
|
||||
Handlebars.VERSION = "1.0.0-rc.3";
|
||||
Handlebars.COMPILER_REVISION = 2;
|
||||
|
||||
Handlebars.REVISION_CHANGES = {
|
||||
1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it
|
||||
2: '>= 1.0.0-rc.3'
|
||||
};
|
||||
|
||||
Handlebars.helpers = {};
|
||||
Handlebars.partials = {};
|
||||
|
||||
Handlebars.registerHelper = function(name, fn, inverse) {
|
||||
if(inverse) { fn.not = inverse; }
|
||||
this.helpers[name] = fn;
|
||||
};
|
||||
|
||||
Handlebars.registerPartial = function(name, str) {
|
||||
this.partials[name] = str;
|
||||
};
|
||||
|
||||
Handlebars.registerHelper('helperMissing', function(arg) {
|
||||
if(arguments.length === 2) {
|
||||
return undefined;
|
||||
} else {
|
||||
throw new Error("Could not find property '" + arg + "'");
|
||||
}
|
||||
});
|
||||
|
||||
var toString = Object.prototype.toString, functionType = "[object Function]";
|
||||
|
||||
Handlebars.registerHelper('blockHelperMissing', function(context, options) {
|
||||
var inverse = options.inverse || function() {}, fn = options.fn;
|
||||
|
||||
var type = toString.call(context);
|
||||
|
||||
if(type === functionType) { context = context.call(this); }
|
||||
|
||||
if(context === true) {
|
||||
return fn(this);
|
||||
} else if(context === false || context == null) {
|
||||
return inverse(this);
|
||||
} else if(type === "[object Array]") {
|
||||
if(context.length > 0) {
|
||||
return Handlebars.helpers.each(context, options);
|
||||
} else {
|
||||
return inverse(this);
|
||||
}
|
||||
} else {
|
||||
return fn(context);
|
||||
}
|
||||
});
|
||||
|
||||
Handlebars.K = function() {};
|
||||
|
||||
Handlebars.createFrame = Object.create || function(object) {
|
||||
Handlebars.K.prototype = object;
|
||||
var obj = new Handlebars.K();
|
||||
Handlebars.K.prototype = null;
|
||||
return obj;
|
||||
};
|
||||
|
||||
Handlebars.logger = {
|
||||
DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3, level: 3,
|
||||
|
||||
methodMap: {0: 'debug', 1: 'info', 2: 'warn', 3: 'error'},
|
||||
|
||||
// can be overridden in the host environment
|
||||
log: function(level, obj) {
|
||||
if (Handlebars.logger.level <= level) {
|
||||
var method = Handlebars.logger.methodMap[level];
|
||||
if (typeof console !== 'undefined' && console[method]) {
|
||||
console[method].call(console, obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Handlebars.log = function(level, obj) { Handlebars.logger.log(level, obj); };
|
||||
|
||||
Handlebars.registerHelper('each', function(context, options) {
|
||||
var fn = options.fn, inverse = options.inverse;
|
||||
var i = 0, ret = "", data;
|
||||
|
||||
if (options.data) {
|
||||
data = Handlebars.createFrame(options.data);
|
||||
}
|
||||
|
||||
if(context && typeof context === 'object') {
|
||||
if(context instanceof Array){
|
||||
for(var j = context.length; i<j; i++) {
|
||||
if (data) { data.index = i; }
|
||||
ret = ret + fn(context[i], { data: data });
|
||||
}
|
||||
} else {
|
||||
for(var key in context) {
|
||||
if(context.hasOwnProperty(key)) {
|
||||
if(data) { data.key = key; }
|
||||
ret = ret + fn(context[key], {data: data});
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(i === 0){
|
||||
ret = inverse(this);
|
||||
}
|
||||
|
||||
return ret;
|
||||
});
|
||||
|
||||
Handlebars.registerHelper('if', function(context, options) {
|
||||
var type = toString.call(context);
|
||||
if(type === functionType) { context = context.call(this); }
|
||||
|
||||
if(!context || Handlebars.Utils.isEmpty(context)) {
|
||||
return options.inverse(this);
|
||||
} else {
|
||||
return options.fn(this);
|
||||
}
|
||||
});
|
||||
|
||||
Handlebars.registerHelper('unless', function(context, options) {
|
||||
var fn = options.fn, inverse = options.inverse;
|
||||
options.fn = inverse;
|
||||
options.inverse = fn;
|
||||
|
||||
return Handlebars.helpers['if'].call(this, context, options);
|
||||
});
|
||||
|
||||
Handlebars.registerHelper('with', function(context, options) {
|
||||
return options.fn(context);
|
||||
});
|
||||
|
||||
Handlebars.registerHelper('log', function(context, options) {
|
||||
var level = options.data && options.data.level != null ? parseInt(options.data.level, 10) : 1;
|
||||
Handlebars.log(level, context);
|
||||
});
|
||||
|
||||
}(Handlebars));
|
||||
|
||||
// END(BROWSER)
|
||||
|
||||
return Handlebars;
|
||||
};
|
|
@ -0,0 +1,136 @@
|
|||
exports.attach = function(Handlebars) {
|
||||
|
||||
// BEGIN(BROWSER)
|
||||
(function() {
|
||||
|
||||
Handlebars.AST = {};
|
||||
|
||||
Handlebars.AST.ProgramNode = function(statements, inverse) {
|
||||
this.type = "program";
|
||||
this.statements = statements;
|
||||
if(inverse) { this.inverse = new Handlebars.AST.ProgramNode(inverse); }
|
||||
};
|
||||
|
||||
Handlebars.AST.MustacheNode = function(rawParams, hash, unescaped) {
|
||||
this.type = "mustache";
|
||||
this.escaped = !unescaped;
|
||||
this.hash = hash;
|
||||
|
||||
var id = this.id = rawParams[0];
|
||||
var params = this.params = rawParams.slice(1);
|
||||
|
||||
// a mustache is an eligible helper if:
|
||||
// * its id is simple (a single part, not `this` or `..`)
|
||||
var eligibleHelper = this.eligibleHelper = id.isSimple;
|
||||
|
||||
// a mustache is definitely a helper if:
|
||||
// * it is an eligible helper, and
|
||||
// * it has at least one parameter or hash segment
|
||||
this.isHelper = eligibleHelper && (params.length || hash);
|
||||
|
||||
// if a mustache is an eligible helper but not a definite
|
||||
// helper, it is ambiguous, and will be resolved in a later
|
||||
// pass or at runtime.
|
||||
};
|
||||
|
||||
Handlebars.AST.PartialNode = function(partialName, context) {
|
||||
this.type = "partial";
|
||||
this.partialName = partialName;
|
||||
this.context = context;
|
||||
};
|
||||
|
||||
Handlebars.AST.BlockNode = function(mustache, program, inverse, close) {
|
||||
var verifyMatch = function(open, close) {
|
||||
if(open.original !== close.original) {
|
||||
throw new Handlebars.Exception(open.original + " doesn't match " + close.original);
|
||||
}
|
||||
};
|
||||
|
||||
verifyMatch(mustache.id, close);
|
||||
this.type = "block";
|
||||
this.mustache = mustache;
|
||||
this.program = program;
|
||||
this.inverse = inverse;
|
||||
|
||||
if (this.inverse && !this.program) {
|
||||
this.isInverse = true;
|
||||
}
|
||||
};
|
||||
|
||||
Handlebars.AST.ContentNode = function(string) {
|
||||
this.type = "content";
|
||||
this.string = string;
|
||||
};
|
||||
|
||||
Handlebars.AST.HashNode = function(pairs) {
|
||||
this.type = "hash";
|
||||
this.pairs = pairs;
|
||||
};
|
||||
|
||||
Handlebars.AST.IdNode = function(parts) {
|
||||
this.type = "ID";
|
||||
this.original = parts.join(".");
|
||||
|
||||
var dig = [], depth = 0;
|
||||
|
||||
for(var i=0,l=parts.length; i<l; i++) {
|
||||
var part = parts[i];
|
||||
|
||||
if (part === ".." || part === "." || part === "this") {
|
||||
if (dig.length > 0) { throw new Handlebars.Exception("Invalid path: " + this.original); }
|
||||
else if (part === "..") { depth++; }
|
||||
else { this.isScoped = true; }
|
||||
}
|
||||
else { dig.push(part); }
|
||||
}
|
||||
|
||||
this.parts = dig;
|
||||
this.string = dig.join('.');
|
||||
this.depth = depth;
|
||||
|
||||
// an ID is simple if it only has one part, and that part is not
|
||||
// `..` or `this`.
|
||||
this.isSimple = parts.length === 1 && !this.isScoped && depth === 0;
|
||||
|
||||
this.stringModeValue = this.string;
|
||||
};
|
||||
|
||||
Handlebars.AST.PartialNameNode = function(name) {
|
||||
this.type = "PARTIAL_NAME";
|
||||
this.name = name;
|
||||
};
|
||||
|
||||
Handlebars.AST.DataNode = function(id) {
|
||||
this.type = "DATA";
|
||||
this.id = id;
|
||||
};
|
||||
|
||||
Handlebars.AST.StringNode = function(string) {
|
||||
this.type = "STRING";
|
||||
this.string = string;
|
||||
this.stringModeValue = string;
|
||||
};
|
||||
|
||||
Handlebars.AST.IntegerNode = function(integer) {
|
||||
this.type = "INTEGER";
|
||||
this.integer = integer;
|
||||
this.stringModeValue = Number(integer);
|
||||
};
|
||||
|
||||
Handlebars.AST.BooleanNode = function(bool) {
|
||||
this.type = "BOOLEAN";
|
||||
this.bool = bool;
|
||||
this.stringModeValue = bool === "true";
|
||||
};
|
||||
|
||||
Handlebars.AST.CommentNode = function(comment) {
|
||||
this.type = "comment";
|
||||
this.comment = comment;
|
||||
};
|
||||
|
||||
})();
|
||||
// END(BROWSER)
|
||||
|
||||
return Handlebars;
|
||||
};
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
var handlebars = require("./parser");
|
||||
|
||||
exports.attach = function(Handlebars) {
|
||||
|
||||
// BEGIN(BROWSER)
|
||||
|
||||
Handlebars.Parser = handlebars;
|
||||
|
||||
Handlebars.parse = function(input) {
|
||||
|
||||
// Just return if an already-compile AST was passed in.
|
||||
if(input.constructor === Handlebars.AST.ProgramNode) { return input; }
|
||||
|
||||
Handlebars.Parser.yy = Handlebars.AST;
|
||||
return Handlebars.Parser.parse(input);
|
||||
};
|
||||
|
||||
Handlebars.print = function(ast) {
|
||||
return new Handlebars.PrintVisitor().accept(ast);
|
||||
};
|
||||
// END(BROWSER)
|
||||
|
||||
return Handlebars;
|
||||
};
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,16 @@
|
|||
// Each of these module will augment the Handlebars object as it loads. No need to perform addition operations
|
||||
module.exports.attach = function(Handlebars) {
|
||||
|
||||
var visitor = require("./visitor"),
|
||||
printer = require("./printer"),
|
||||
ast = require("./ast"),
|
||||
compiler = require("./compiler");
|
||||
|
||||
visitor.attach(Handlebars);
|
||||
printer.attach(Handlebars);
|
||||
ast.attach(Handlebars);
|
||||
compiler.attach(Handlebars);
|
||||
|
||||
return Handlebars;
|
||||
|
||||
};
|
|
@ -0,0 +1,476 @@
|
|||
// BEGIN(BROWSER)
|
||||
/* Jison generated parser */
|
||||
var handlebars = (function(){
|
||||
var parser = {trace: function trace() { },
|
||||
yy: {},
|
||||
symbols_: {"error":2,"root":3,"program":4,"EOF":5,"simpleInverse":6,"statements":7,"statement":8,"openInverse":9,"closeBlock":10,"openBlock":11,"mustache":12,"partial":13,"CONTENT":14,"COMMENT":15,"OPEN_BLOCK":16,"inMustache":17,"CLOSE":18,"OPEN_INVERSE":19,"OPEN_ENDBLOCK":20,"path":21,"OPEN":22,"OPEN_UNESCAPED":23,"OPEN_PARTIAL":24,"partialName":25,"params":26,"hash":27,"DATA":28,"param":29,"STRING":30,"INTEGER":31,"BOOLEAN":32,"hashSegments":33,"hashSegment":34,"ID":35,"EQUALS":36,"PARTIAL_NAME":37,"pathSegments":38,"SEP":39,"$accept":0,"$end":1},
|
||||
terminals_: {2:"error",5:"EOF",14:"CONTENT",15:"COMMENT",16:"OPEN_BLOCK",18:"CLOSE",19:"OPEN_INVERSE",20:"OPEN_ENDBLOCK",22:"OPEN",23:"OPEN_UNESCAPED",24:"OPEN_PARTIAL",28:"DATA",30:"STRING",31:"INTEGER",32:"BOOLEAN",35:"ID",36:"EQUALS",37:"PARTIAL_NAME",39:"SEP"},
|
||||
productions_: [0,[3,2],[4,2],[4,3],[4,2],[4,1],[4,1],[4,0],[7,1],[7,2],[8,3],[8,3],[8,1],[8,1],[8,1],[8,1],[11,3],[9,3],[10,3],[12,3],[12,3],[13,3],[13,4],[6,2],[17,3],[17,2],[17,2],[17,1],[17,1],[26,2],[26,1],[29,1],[29,1],[29,1],[29,1],[29,1],[27,1],[33,2],[33,1],[34,3],[34,3],[34,3],[34,3],[34,3],[25,1],[21,1],[38,3],[38,1]],
|
||||
performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) {
|
||||
|
||||
var $0 = $$.length - 1;
|
||||
switch (yystate) {
|
||||
case 1: return $$[$0-1];
|
||||
break;
|
||||
case 2: this.$ = new yy.ProgramNode([], $$[$0]);
|
||||
break;
|
||||
case 3: this.$ = new yy.ProgramNode($$[$0-2], $$[$0]);
|
||||
break;
|
||||
case 4: this.$ = new yy.ProgramNode($$[$0-1], []);
|
||||
break;
|
||||
case 5: this.$ = new yy.ProgramNode($$[$0]);
|
||||
break;
|
||||
case 6: this.$ = new yy.ProgramNode([], []);
|
||||
break;
|
||||
case 7: this.$ = new yy.ProgramNode([]);
|
||||
break;
|
||||
case 8: this.$ = [$$[$0]];
|
||||
break;
|
||||
case 9: $$[$0-1].push($$[$0]); this.$ = $$[$0-1];
|
||||
break;
|
||||
case 10: this.$ = new yy.BlockNode($$[$0-2], $$[$0-1].inverse, $$[$0-1], $$[$0]);
|
||||
break;
|
||||
case 11: this.$ = new yy.BlockNode($$[$0-2], $$[$0-1], $$[$0-1].inverse, $$[$0]);
|
||||
break;
|
||||
case 12: this.$ = $$[$0];
|
||||
break;
|
||||
case 13: this.$ = $$[$0];
|
||||
break;
|
||||
case 14: this.$ = new yy.ContentNode($$[$0]);
|
||||
break;
|
||||
case 15: this.$ = new yy.CommentNode($$[$0]);
|
||||
break;
|
||||
case 16: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1]);
|
||||
break;
|
||||
case 17: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1]);
|
||||
break;
|
||||
case 18: this.$ = $$[$0-1];
|
||||
break;
|
||||
case 19: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1]);
|
||||
break;
|
||||
case 20: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1], true);
|
||||
break;
|
||||
case 21: this.$ = new yy.PartialNode($$[$0-1]);
|
||||
break;
|
||||
case 22: this.$ = new yy.PartialNode($$[$0-2], $$[$0-1]);
|
||||
break;
|
||||
case 23:
|
||||
break;
|
||||
case 24: this.$ = [[$$[$0-2]].concat($$[$0-1]), $$[$0]];
|
||||
break;
|
||||
case 25: this.$ = [[$$[$0-1]].concat($$[$0]), null];
|
||||
break;
|
||||
case 26: this.$ = [[$$[$0-1]], $$[$0]];
|
||||
break;
|
||||
case 27: this.$ = [[$$[$0]], null];
|
||||
break;
|
||||
case 28: this.$ = [[new yy.DataNode($$[$0])], null];
|
||||
break;
|
||||
case 29: $$[$0-1].push($$[$0]); this.$ = $$[$0-1];
|
||||
break;
|
||||
case 30: this.$ = [$$[$0]];
|
||||
break;
|
||||
case 31: this.$ = $$[$0];
|
||||
break;
|
||||
case 32: this.$ = new yy.StringNode($$[$0]);
|
||||
break;
|
||||
case 33: this.$ = new yy.IntegerNode($$[$0]);
|
||||
break;
|
||||
case 34: this.$ = new yy.BooleanNode($$[$0]);
|
||||
break;
|
||||
case 35: this.$ = new yy.DataNode($$[$0]);
|
||||
break;
|
||||
case 36: this.$ = new yy.HashNode($$[$0]);
|
||||
break;
|
||||
case 37: $$[$0-1].push($$[$0]); this.$ = $$[$0-1];
|
||||
break;
|
||||
case 38: this.$ = [$$[$0]];
|
||||
break;
|
||||
case 39: this.$ = [$$[$0-2], $$[$0]];
|
||||
break;
|
||||
case 40: this.$ = [$$[$0-2], new yy.StringNode($$[$0])];
|
||||
break;
|
||||
case 41: this.$ = [$$[$0-2], new yy.IntegerNode($$[$0])];
|
||||
break;
|
||||
case 42: this.$ = [$$[$0-2], new yy.BooleanNode($$[$0])];
|
||||
break;
|
||||
case 43: this.$ = [$$[$0-2], new yy.DataNode($$[$0])];
|
||||
break;
|
||||
case 44: this.$ = new yy.PartialNameNode($$[$0]);
|
||||
break;
|
||||
case 45: this.$ = new yy.IdNode($$[$0]);
|
||||
break;
|
||||
case 46: $$[$0-2].push($$[$0]); this.$ = $$[$0-2];
|
||||
break;
|
||||
case 47: this.$ = [$$[$0]];
|
||||
break;
|
||||
}
|
||||
},
|
||||
table: [{3:1,4:2,5:[2,7],6:3,7:4,8:6,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,5],22:[1,14],23:[1,15],24:[1,16]},{1:[3]},{5:[1,17]},{5:[2,6],7:18,8:6,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,19],20:[2,6],22:[1,14],23:[1,15],24:[1,16]},{5:[2,5],6:20,8:21,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,5],20:[2,5],22:[1,14],23:[1,15],24:[1,16]},{17:23,18:[1,22],21:24,28:[1,25],35:[1,27],38:26},{5:[2,8],14:[2,8],15:[2,8],16:[2,8],19:[2,8],20:[2,8],22:[2,8],23:[2,8],24:[2,8]},{4:28,6:3,7:4,8:6,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,5],20:[2,7],22:[1,14],23:[1,15],24:[1,16]},{4:29,6:3,7:4,8:6,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,5],20:[2,7],22:[1,14],23:[1,15],24:[1,16]},{5:[2,12],14:[2,12],15:[2,12],16:[2,12],19:[2,12],20:[2,12],22:[2,12],23:[2,12],24:[2,12]},{5:[2,13],14:[2,13],15:[2,13],16:[2,13],19:[2,13],20:[2,13],22:[2,13],23:[2,13],24:[2,13]},{5:[2,14],14:[2,14],15:[2,14],16:[2,14],19:[2,14],20:[2,14],22:[2,14],23:[2,14],24:[2,14]},{5:[2,15],14:[2,15],15:[2,15],16:[2,15],19:[2,15],20:[2,15],22:[2,15],23:[2,15],24:[2,15]},{17:30,21:24,28:[1,25],35:[1,27],38:26},{17:31,21:24,28:[1,25],35:[1,27],38:26},{17:32,21:24,28:[1,25],35:[1,27],38:26},{25:33,37:[1,34]},{1:[2,1]},{5:[2,2],8:21,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,19],20:[2,2],22:[1,14],23:[1,15],24:[1,16]},{17:23,21:24,28:[1,25],35:[1,27],38:26},{5:[2,4],7:35,8:6,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,19],20:[2,4],22:[1,14],23:[1,15],24:[1,16]},{5:[2,9],14:[2,9],15:[2,9],16:[2,9],19:[2,9],20:[2,9],22:[2,9],23:[2,9],24:[2,9]},{5:[2,23],14:[2,23],15:[2,23],16:[2,23],19:[2,23],20:[2,23],22:[2,23],23:[2,23],24:[2,23]},{18:[1,36]},{18:[2,27],21:41,26:37,27:38,28:[1,45],29:39,30:[1,42],31:[1,43],32:[1,44],33:40,34:46,35:[1,47],38:26},{18:[2,28]},{18:[2,45],28:[2,45],30:[2,45],31:[2,45],32:[2,45],35:[2,45],39:[1,48]},{18:[2,47],28:[2,47],30:[2,47],31:[2,47],32:[2,47],35:[2,47],39:[2,47]},{10:49,20:[1,50]},{10:51,20:[1,50]},{18:[1,52]},{18:[1,53]},{18:[1,54]},{18:[1,55],21:56,35:[1,27],38:26},{18:[2,44],35:[2,44]},{5:[2,3],8:21,9:7,11:8,12:9,13:10,14:[1,11],15:[1,12],16:[1,13],19:[1,19],20:[2,3],22:[1,14],23:[1,15],24:[1,16]},{14:[2,17],15:[2,17],16:[2,17],19:[2,17],20:[2,17],22:[2,17],23:[2,17],24:[2,17]},{18:[2,25],21:41,27:57,28:[1,45],29:58,30:[1,42],31:[1,43],32:[1,44],33:40,34:46,35:[1,47],38:26},{18:[2,26]},{18:[2,30],28:[2,30],30:[2,30],31:[2,30],32:[2,30],35:[2,30]},{18:[2,36],34:59,35:[1,60]},{18:[2,31],28:[2,31],30:[2,31],31:[2,31],32:[2,31],35:[2,31]},{18:[2,32],28:[2,32],30:[2,32],31:[2,32],32:[2,32],35:[2,32]},{18:[2,33],28:[2,33],30:[2,33],31:[2,33],32:[2,33],35:[2,33]},{18:[2,34],28:[2,34],30:[2,34],31:[2,34],32:[2,34],35:[2,34]},{18:[2,35],28:[2,35],30:[2,35],31:[2,35],32:[2,35],35:[2,35]},{18:[2,38],35:[2,38]},{18:[2,47],28:[2,47],30:[2,47],31:[2,47],32:[2,47],35:[2,47],36:[1,61],39:[2,47]},{35:[1,62]},{5:[2,10],14:[2,10],15:[2,10],16:[2,10],19:[2,10],20:[2,10],22:[2,10],23:[2,10],24:[2,10]},{21:63,35:[1,27],38:26},{5:[2,11],14:[2,11],15:[2,11],16:[2,11],19:[2,11],20:[2,11],22:[2,11],23:[2,11],24:[2,11]},{14:[2,16],15:[2,16],16:[2,16],19:[2,16],20:[2,16],22:[2,16],23:[2,16],24:[2,16]},{5:[2,19],14:[2,19],15:[2,19],16:[2,19],19:[2,19],20:[2,19],22:[2,19],23:[2,19],24:[2,19]},{5:[2,20],14:[2,20],15:[2,20],16:[2,20],19:[2,20],20:[2,20],22:[2,20],23:[2,20],24:[2,20]},{5:[2,21],14:[2,21],15:[2,21],16:[2,21],19:[2,21],20:[2,21],22:[2,21],23:[2,21],24:[2,21]},{18:[1,64]},{18:[2,24]},{18:[2,29],28:[2,29],30:[2,29],31:[2,29],32:[2,29],35:[2,29]},{18:[2,37],35:[2,37]},{36:[1,61]},{21:65,28:[1,69],30:[1,66],31:[1,67],32:[1,68],35:[1,27],38:26},{18:[2,46],28:[2,46],30:[2,46],31:[2,46],32:[2,46],35:[2,46],39:[2,46]},{18:[1,70]},{5:[2,22],14:[2,22],15:[2,22],16:[2,22],19:[2,22],20:[2,22],22:[2,22],23:[2,22],24:[2,22]},{18:[2,39],35:[2,39]},{18:[2,40],35:[2,40]},{18:[2,41],35:[2,41]},{18:[2,42],35:[2,42]},{18:[2,43],35:[2,43]},{5:[2,18],14:[2,18],15:[2,18],16:[2,18],19:[2,18],20:[2,18],22:[2,18],23:[2,18],24:[2,18]}],
|
||||
defaultActions: {17:[2,1],25:[2,28],38:[2,26],57:[2,24]},
|
||||
parseError: function parseError(str, hash) {
|
||||
throw new Error(str);
|
||||
},
|
||||
parse: function parse(input) {
|
||||
var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1;
|
||||
this.lexer.setInput(input);
|
||||
this.lexer.yy = this.yy;
|
||||
this.yy.lexer = this.lexer;
|
||||
this.yy.parser = this;
|
||||
if (typeof this.lexer.yylloc == "undefined")
|
||||
this.lexer.yylloc = {};
|
||||
var yyloc = this.lexer.yylloc;
|
||||
lstack.push(yyloc);
|
||||
var ranges = this.lexer.options && this.lexer.options.ranges;
|
||||
if (typeof this.yy.parseError === "function")
|
||||
this.parseError = this.yy.parseError;
|
||||
function popStack(n) {
|
||||
stack.length = stack.length - 2 * n;
|
||||
vstack.length = vstack.length - n;
|
||||
lstack.length = lstack.length - n;
|
||||
}
|
||||
function lex() {
|
||||
var token;
|
||||
token = self.lexer.lex() || 1;
|
||||
if (typeof token !== "number") {
|
||||
token = self.symbols_[token] || token;
|
||||
}
|
||||
return token;
|
||||
}
|
||||
var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;
|
||||
while (true) {
|
||||
state = stack[stack.length - 1];
|
||||
if (this.defaultActions[state]) {
|
||||
action = this.defaultActions[state];
|
||||
} else {
|
||||
if (symbol === null || typeof symbol == "undefined") {
|
||||
symbol = lex();
|
||||
}
|
||||
action = table[state] && table[state][symbol];
|
||||
}
|
||||
if (typeof action === "undefined" || !action.length || !action[0]) {
|
||||
var errStr = "";
|
||||
if (!recovering) {
|
||||
expected = [];
|
||||
for (p in table[state])
|
||||
if (this.terminals_[p] && p > 2) {
|
||||
expected.push("'" + this.terminals_[p] + "'");
|
||||
}
|
||||
if (this.lexer.showPosition) {
|
||||
errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'";
|
||||
} else {
|
||||
errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1?"end of input":"'" + (this.terminals_[symbol] || symbol) + "'");
|
||||
}
|
||||
this.parseError(errStr, {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected});
|
||||
}
|
||||
}
|
||||
if (action[0] instanceof Array && action.length > 1) {
|
||||
throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);
|
||||
}
|
||||
switch (action[0]) {
|
||||
case 1:
|
||||
stack.push(symbol);
|
||||
vstack.push(this.lexer.yytext);
|
||||
lstack.push(this.lexer.yylloc);
|
||||
stack.push(action[1]);
|
||||
symbol = null;
|
||||
if (!preErrorSymbol) {
|
||||
yyleng = this.lexer.yyleng;
|
||||
yytext = this.lexer.yytext;
|
||||
yylineno = this.lexer.yylineno;
|
||||
yyloc = this.lexer.yylloc;
|
||||
if (recovering > 0)
|
||||
recovering--;
|
||||
} else {
|
||||
symbol = preErrorSymbol;
|
||||
preErrorSymbol = null;
|
||||
}
|
||||
break;
|
||||
case 2:
|
||||
len = this.productions_[action[1]][1];
|
||||
yyval.$ = vstack[vstack.length - len];
|
||||
yyval._$ = {first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column};
|
||||
if (ranges) {
|
||||
yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]];
|
||||
}
|
||||
r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
|
||||
if (typeof r !== "undefined") {
|
||||
return r;
|
||||
}
|
||||
if (len) {
|
||||
stack = stack.slice(0, -1 * len * 2);
|
||||
vstack = vstack.slice(0, -1 * len);
|
||||
lstack = lstack.slice(0, -1 * len);
|
||||
}
|
||||
stack.push(this.productions_[action[1]][0]);
|
||||
vstack.push(yyval.$);
|
||||
lstack.push(yyval._$);
|
||||
newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
|
||||
stack.push(newState);
|
||||
break;
|
||||
case 3:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
/* Jison generated lexer */
|
||||
var lexer = (function(){
|
||||
var lexer = ({EOF:1,
|
||||
parseError:function parseError(str, hash) {
|
||||
if (this.yy.parser) {
|
||||
this.yy.parser.parseError(str, hash);
|
||||
} else {
|
||||
throw new Error(str);
|
||||
}
|
||||
},
|
||||
setInput:function (input) {
|
||||
this._input = input;
|
||||
this._more = this._less = this.done = false;
|
||||
this.yylineno = this.yyleng = 0;
|
||||
this.yytext = this.matched = this.match = '';
|
||||
this.conditionStack = ['INITIAL'];
|
||||
this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0};
|
||||
if (this.options.ranges) this.yylloc.range = [0,0];
|
||||
this.offset = 0;
|
||||
return this;
|
||||
},
|
||||
input:function () {
|
||||
var ch = this._input[0];
|
||||
this.yytext += ch;
|
||||
this.yyleng++;
|
||||
this.offset++;
|
||||
this.match += ch;
|
||||
this.matched += ch;
|
||||
var lines = ch.match(/(?:\r\n?|\n).*/g);
|
||||
if (lines) {
|
||||
this.yylineno++;
|
||||
this.yylloc.last_line++;
|
||||
} else {
|
||||
this.yylloc.last_column++;
|
||||
}
|
||||
if (this.options.ranges) this.yylloc.range[1]++;
|
||||
|
||||
this._input = this._input.slice(1);
|
||||
return ch;
|
||||
},
|
||||
unput:function (ch) {
|
||||
var len = ch.length;
|
||||
var lines = ch.split(/(?:\r\n?|\n)/g);
|
||||
|
||||
this._input = ch + this._input;
|
||||
this.yytext = this.yytext.substr(0, this.yytext.length-len-1);
|
||||
//this.yyleng -= len;
|
||||
this.offset -= len;
|
||||
var oldLines = this.match.split(/(?:\r\n?|\n)/g);
|
||||
this.match = this.match.substr(0, this.match.length-1);
|
||||
this.matched = this.matched.substr(0, this.matched.length-1);
|
||||
|
||||
if (lines.length-1) this.yylineno -= lines.length-1;
|
||||
var r = this.yylloc.range;
|
||||
|
||||
this.yylloc = {first_line: this.yylloc.first_line,
|
||||
last_line: this.yylineno+1,
|
||||
first_column: this.yylloc.first_column,
|
||||
last_column: lines ?
|
||||
(lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length:
|
||||
this.yylloc.first_column - len
|
||||
};
|
||||
|
||||
if (this.options.ranges) {
|
||||
this.yylloc.range = [r[0], r[0] + this.yyleng - len];
|
||||
}
|
||||
return this;
|
||||
},
|
||||
more:function () {
|
||||
this._more = true;
|
||||
return this;
|
||||
},
|
||||
less:function (n) {
|
||||
this.unput(this.match.slice(n));
|
||||
},
|
||||
pastInput:function () {
|
||||
var past = this.matched.substr(0, this.matched.length - this.match.length);
|
||||
return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, "");
|
||||
},
|
||||
upcomingInput:function () {
|
||||
var next = this.match;
|
||||
if (next.length < 20) {
|
||||
next += this._input.substr(0, 20-next.length);
|
||||
}
|
||||
return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\n/g, "");
|
||||
},
|
||||
showPosition:function () {
|
||||
var pre = this.pastInput();
|
||||
var c = new Array(pre.length + 1).join("-");
|
||||
return pre + this.upcomingInput() + "\n" + c+"^";
|
||||
},
|
||||
next:function () {
|
||||
if (this.done) {
|
||||
return this.EOF;
|
||||
}
|
||||
if (!this._input) this.done = true;
|
||||
|
||||
var token,
|
||||
match,
|
||||
tempMatch,
|
||||
index,
|
||||
col,
|
||||
lines;
|
||||
if (!this._more) {
|
||||
this.yytext = '';
|
||||
this.match = '';
|
||||
}
|
||||
var rules = this._currentRules();
|
||||
for (var i=0;i < rules.length; i++) {
|
||||
tempMatch = this._input.match(this.rules[rules[i]]);
|
||||
if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
|
||||
match = tempMatch;
|
||||
index = i;
|
||||
if (!this.options.flex) break;
|
||||
}
|
||||
}
|
||||
if (match) {
|
||||
lines = match[0].match(/(?:\r\n?|\n).*/g);
|
||||
if (lines) this.yylineno += lines.length;
|
||||
this.yylloc = {first_line: this.yylloc.last_line,
|
||||
last_line: this.yylineno+1,
|
||||
first_column: this.yylloc.last_column,
|
||||
last_column: lines ? lines[lines.length-1].length-lines[lines.length-1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length};
|
||||
this.yytext += match[0];
|
||||
this.match += match[0];
|
||||
this.matches = match;
|
||||
this.yyleng = this.yytext.length;
|
||||
if (this.options.ranges) {
|
||||
this.yylloc.range = [this.offset, this.offset += this.yyleng];
|
||||
}
|
||||
this._more = false;
|
||||
this._input = this._input.slice(match[0].length);
|
||||
this.matched += match[0];
|
||||
token = this.performAction.call(this, this.yy, this, rules[index],this.conditionStack[this.conditionStack.length-1]);
|
||||
if (this.done && this._input) this.done = false;
|
||||
if (token) return token;
|
||||
else return;
|
||||
}
|
||||
if (this._input === "") {
|
||||
return this.EOF;
|
||||
} else {
|
||||
return this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\n'+this.showPosition(),
|
||||
{text: "", token: null, line: this.yylineno});
|
||||
}
|
||||
},
|
||||
lex:function lex() {
|
||||
var r = this.next();
|
||||
if (typeof r !== 'undefined') {
|
||||
return r;
|
||||
} else {
|
||||
return this.lex();
|
||||
}
|
||||
},
|
||||
begin:function begin(condition) {
|
||||
this.conditionStack.push(condition);
|
||||
},
|
||||
popState:function popState() {
|
||||
return this.conditionStack.pop();
|
||||
},
|
||||
_currentRules:function _currentRules() {
|
||||
return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules;
|
||||
},
|
||||
topState:function () {
|
||||
return this.conditionStack[this.conditionStack.length-2];
|
||||
},
|
||||
pushState:function begin(condition) {
|
||||
this.begin(condition);
|
||||
}});
|
||||
lexer.options = {};
|
||||
lexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) {
|
||||
|
||||
var YYSTATE=YY_START
|
||||
switch($avoiding_name_collisions) {
|
||||
case 0:
|
||||
if(yy_.yytext.slice(-1) !== "\\") this.begin("mu");
|
||||
if(yy_.yytext.slice(-1) === "\\") yy_.yytext = yy_.yytext.substr(0,yy_.yyleng-1), this.begin("emu");
|
||||
if(yy_.yytext) return 14;
|
||||
|
||||
break;
|
||||
case 1: return 14;
|
||||
break;
|
||||
case 2:
|
||||
if(yy_.yytext.slice(-1) !== "\\") this.popState();
|
||||
if(yy_.yytext.slice(-1) === "\\") yy_.yytext = yy_.yytext.substr(0,yy_.yyleng-1);
|
||||
return 14;
|
||||
|
||||
break;
|
||||
case 3: yy_.yytext = yy_.yytext.substr(0, yy_.yyleng-4); this.popState(); return 15;
|
||||
break;
|
||||
case 4: this.begin("par"); return 24;
|
||||
break;
|
||||
case 5: return 16;
|
||||
break;
|
||||
case 6: return 20;
|
||||
break;
|
||||
case 7: return 19;
|
||||
break;
|
||||
case 8: return 19;
|
||||
break;
|
||||
case 9: return 23;
|
||||
break;
|
||||
case 10: return 23;
|
||||
break;
|
||||
case 11: this.popState(); this.begin('com');
|
||||
break;
|
||||
case 12: yy_.yytext = yy_.yytext.substr(3,yy_.yyleng-5); this.popState(); return 15;
|
||||
break;
|
||||
case 13: return 22;
|
||||
break;
|
||||
case 14: return 36;
|
||||
break;
|
||||
case 15: return 35;
|
||||
break;
|
||||
case 16: return 35;
|
||||
break;
|
||||
case 17: return 39;
|
||||
break;
|
||||
case 18: /*ignore whitespace*/
|
||||
break;
|
||||
case 19: this.popState(); return 18;
|
||||
break;
|
||||
case 20: this.popState(); return 18;
|
||||
break;
|
||||
case 21: yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2).replace(/\\"/g,'"'); return 30;
|
||||
break;
|
||||
case 22: yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2).replace(/\\'/g,"'"); return 30;
|
||||
break;
|
||||
case 23: yy_.yytext = yy_.yytext.substr(1); return 28;
|
||||
break;
|
||||
case 24: return 32;
|
||||
break;
|
||||
case 25: return 32;
|
||||
break;
|
||||
case 26: return 31;
|
||||
break;
|
||||
case 27: return 35;
|
||||
break;
|
||||
case 28: yy_.yytext = yy_.yytext.substr(1, yy_.yyleng-2); return 35;
|
||||
break;
|
||||
case 29: return 'INVALID';
|
||||
break;
|
||||
case 30: /*ignore whitespace*/
|
||||
break;
|
||||
case 31: this.popState(); return 37;
|
||||
break;
|
||||
case 32: return 5;
|
||||
break;
|
||||
}
|
||||
};
|
||||
lexer.rules = [/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|$)))/,/^(?:[\s\S]*?--\}\})/,/^(?:\{\{>)/,/^(?:\{\{#)/,/^(?:\{\{\/)/,/^(?:\{\{\^)/,/^(?:\{\{\s*else\b)/,/^(?:\{\{\{)/,/^(?:\{\{&)/,/^(?:\{\{!--)/,/^(?:\{\{![\s\S]*?\}\})/,/^(?:\{\{)/,/^(?:=)/,/^(?:\.(?=[} ]))/,/^(?:\.\.)/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}\}\})/,/^(?:\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@[a-zA-Z]+)/,/^(?:true(?=[}\s]))/,/^(?:false(?=[}\s]))/,/^(?:[0-9]+(?=[}\s]))/,/^(?:[a-zA-Z0-9_$-]+(?=[=}\s\/.]))/,/^(?:\[[^\]]*\])/,/^(?:.)/,/^(?:\s+)/,/^(?:[a-zA-Z0-9_$-/]+)/,/^(?:$)/];
|
||||
lexer.conditions = {"mu":{"rules":[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,32],"inclusive":false},"emu":{"rules":[2],"inclusive":false},"com":{"rules":[3],"inclusive":false},"par":{"rules":[30,31],"inclusive":false},"INITIAL":{"rules":[0,1,32],"inclusive":true}};
|
||||
return lexer;})()
|
||||
parser.lexer = lexer;
|
||||
function Parser () { this.yy = {}; }Parser.prototype = parser;parser.Parser = Parser;
|
||||
return new Parser;
|
||||
})();
|
||||
// END(BROWSER)
|
||||
|
||||
module.exports = handlebars;
|
|
@ -0,0 +1,134 @@
|
|||
exports.attach = function(Handlebars) {
|
||||
|
||||
// BEGIN(BROWSER)
|
||||
|
||||
Handlebars.PrintVisitor = function() { this.padding = 0; };
|
||||
Handlebars.PrintVisitor.prototype = new Handlebars.Visitor();
|
||||
|
||||
Handlebars.PrintVisitor.prototype.pad = function(string, newline) {
|
||||
var out = "";
|
||||
|
||||
for(var i=0,l=this.padding; i<l; i++) {
|
||||
out = out + " ";
|
||||
}
|
||||
|
||||
out = out + string;
|
||||
|
||||
if(newline !== false) { out = out + "\n"; }
|
||||
return out;
|
||||
};
|
||||
|
||||
Handlebars.PrintVisitor.prototype.program = function(program) {
|
||||
var out = "",
|
||||
statements = program.statements,
|
||||
inverse = program.inverse,
|
||||
i, l;
|
||||
|
||||
for(i=0, l=statements.length; i<l; i++) {
|
||||
out = out + this.accept(statements[i]);
|
||||
}
|
||||
|
||||
this.padding--;
|
||||
|
||||
return out;
|
||||
};
|
||||
|
||||
Handlebars.PrintVisitor.prototype.block = function(block) {
|
||||
var out = "";
|
||||
|
||||
out = out + this.pad("BLOCK:");
|
||||
this.padding++;
|
||||
out = out + this.accept(block.mustache);
|
||||
if (block.program) {
|
||||
out = out + this.pad("PROGRAM:");
|
||||
this.padding++;
|
||||
out = out + this.accept(block.program);
|
||||
this.padding--;
|
||||
}
|
||||
if (block.inverse) {
|
||||
if (block.program) { this.padding++; }
|
||||
out = out + this.pad("{{^}}");
|
||||
this.padding++;
|
||||
out = out + this.accept(block.inverse);
|
||||
this.padding--;
|
||||
if (block.program) { this.padding--; }
|
||||
}
|
||||
this.padding--;
|
||||
|
||||
return out;
|
||||
};
|
||||
|
||||
Handlebars.PrintVisitor.prototype.mustache = function(mustache) {
|
||||
var params = mustache.params, paramStrings = [], hash;
|
||||
|
||||
for(var i=0, l=params.length; i<l; i++) {
|
||||
paramStrings.push(this.accept(params[i]));
|
||||
}
|
||||
|
||||
params = "[" + paramStrings.join(", ") + "]";
|
||||
|
||||
hash = mustache.hash ? " " + this.accept(mustache.hash) : "";
|
||||
|
||||
return this.pad("{{ " + this.accept(mustache.id) + " " + params + hash + " }}");
|
||||
};
|
||||
|
||||
Handlebars.PrintVisitor.prototype.partial = function(partial) {
|
||||
var content = this.accept(partial.partialName);
|
||||
if(partial.context) { content = content + " " + this.accept(partial.context); }
|
||||
return this.pad("{{> " + content + " }}");
|
||||
};
|
||||
|
||||
Handlebars.PrintVisitor.prototype.hash = function(hash) {
|
||||
var pairs = hash.pairs;
|
||||
var joinedPairs = [], left, right;
|
||||
|
||||
for(var i=0, l=pairs.length; i<l; i++) {
|
||||
left = pairs[i][0];
|
||||
right = this.accept(pairs[i][1]);
|
||||
joinedPairs.push( left + "=" + right );
|
||||
}
|
||||
|
||||
return "HASH{" + joinedPairs.join(", ") + "}";
|
||||
};
|
||||
|
||||
Handlebars.PrintVisitor.prototype.STRING = function(string) {
|
||||
return '"' + string.string + '"';
|
||||
};
|
||||
|
||||
Handlebars.PrintVisitor.prototype.INTEGER = function(integer) {
|
||||
return "INTEGER{" + integer.integer + "}";
|
||||
};
|
||||
|
||||
Handlebars.PrintVisitor.prototype.BOOLEAN = function(bool) {
|
||||
return "BOOLEAN{" + bool.bool + "}";
|
||||
};
|
||||
|
||||
Handlebars.PrintVisitor.prototype.ID = function(id) {
|
||||
var path = id.parts.join("/");
|
||||
if(id.parts.length > 1) {
|
||||
return "PATH:" + path;
|
||||
} else {
|
||||
return "ID:" + path;
|
||||
}
|
||||
};
|
||||
|
||||
Handlebars.PrintVisitor.prototype.PARTIAL_NAME = function(partialName) {
|
||||
return "PARTIAL:" + partialName.name;
|
||||
};
|
||||
|
||||
Handlebars.PrintVisitor.prototype.DATA = function(data) {
|
||||
return "@" + data.id;
|
||||
};
|
||||
|
||||
Handlebars.PrintVisitor.prototype.content = function(content) {
|
||||
return this.pad("CONTENT[ '" + content.string + "' ]");
|
||||
};
|
||||
|
||||
Handlebars.PrintVisitor.prototype.comment = function(comment) {
|
||||
return this.pad("{{! '" + comment.comment + "' }}");
|
||||
};
|
||||
// END(BROWSER)
|
||||
|
||||
return Handlebars;
|
||||
};
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
exports.attach = function(Handlebars) {
|
||||
|
||||
// BEGIN(BROWSER)
|
||||
|
||||
Handlebars.Visitor = function() {};
|
||||
|
||||
Handlebars.Visitor.prototype = {
|
||||
accept: function(object) {
|
||||
return this[object.type](object);
|
||||
}
|
||||
};
|
||||
|
||||
// END(BROWSER)
|
||||
|
||||
return Handlebars;
|
||||
};
|
||||
|
||||
|
|
@ -0,0 +1,92 @@
|
|||
exports.attach = function(Handlebars) {
|
||||
|
||||
// BEGIN(BROWSER)
|
||||
|
||||
Handlebars.VM = {
|
||||
template: function(templateSpec) {
|
||||
// Just add water
|
||||
var container = {
|
||||
escapeExpression: Handlebars.Utils.escapeExpression,
|
||||
invokePartial: Handlebars.VM.invokePartial,
|
||||
programs: [],
|
||||
program: function(i, fn, data) {
|
||||
var programWrapper = this.programs[i];
|
||||
if(data) {
|
||||
return Handlebars.VM.program(fn, data);
|
||||
} else if(programWrapper) {
|
||||
return programWrapper;
|
||||
} else {
|
||||
programWrapper = this.programs[i] = Handlebars.VM.program(fn);
|
||||
return programWrapper;
|
||||
}
|
||||
},
|
||||
programWithDepth: Handlebars.VM.programWithDepth,
|
||||
noop: Handlebars.VM.noop,
|
||||
compilerInfo: null
|
||||
};
|
||||
|
||||
return function(context, options) {
|
||||
options = options || {};
|
||||
var result = templateSpec.call(container, Handlebars, context, options.helpers, options.partials, options.data);
|
||||
|
||||
var compilerInfo = container.compilerInfo || [],
|
||||
compilerRevision = compilerInfo[0] || 1,
|
||||
currentRevision = Handlebars.COMPILER_REVISION;
|
||||
|
||||
if (compilerRevision !== currentRevision) {
|
||||
if (compilerRevision < currentRevision) {
|
||||
var runtimeVersions = Handlebars.REVISION_CHANGES[currentRevision],
|
||||
compilerVersions = Handlebars.REVISION_CHANGES[compilerRevision];
|
||||
throw "Template was precompiled with an older version of Handlebars than the current runtime. "+
|
||||
"Please update your precompiler to a newer version ("+runtimeVersions+") or downgrade your runtime to an older version ("+compilerVersions+").";
|
||||
} else {
|
||||
// Use the embedded version info since the runtime doesn't know about this revision yet
|
||||
throw "Template was precompiled with a newer version of Handlebars than the current runtime. "+
|
||||
"Please update your runtime to a newer version ("+compilerInfo[1]+").";
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
},
|
||||
|
||||
programWithDepth: function(fn, data, $depth) {
|
||||
var args = Array.prototype.slice.call(arguments, 2);
|
||||
|
||||
return function(context, options) {
|
||||
options = options || {};
|
||||
|
||||
return fn.apply(this, [context, options.data || data].concat(args));
|
||||
};
|
||||
},
|
||||
program: function(fn, data) {
|
||||
return function(context, options) {
|
||||
options = options || {};
|
||||
|
||||
return fn(context, options.data || data);
|
||||
};
|
||||
},
|
||||
noop: function() { return ""; },
|
||||
invokePartial: function(partial, name, context, helpers, partials, data) {
|
||||
var options = { helpers: helpers, partials: partials, data: data };
|
||||
|
||||
if(partial === undefined) {
|
||||
throw new Handlebars.Exception("The partial " + name + " could not be found");
|
||||
} else if(partial instanceof Function) {
|
||||
return partial(context, options);
|
||||
} else if (!Handlebars.compile) {
|
||||
throw new Handlebars.Exception("The partial " + name + " could not be compiled when running in runtime-only mode");
|
||||
} else {
|
||||
partials[name] = Handlebars.compile(partial, {data: data !== undefined});
|
||||
return partials[name](context, options);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Handlebars.template = Handlebars.VM.template;
|
||||
|
||||
// END(BROWSER)
|
||||
|
||||
return Handlebars;
|
||||
|
||||
};
|
|
@ -0,0 +1,70 @@
|
|||
exports.attach = function(Handlebars) {
|
||||
|
||||
// BEGIN(BROWSER)
|
||||
|
||||
var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
|
||||
|
||||
Handlebars.Exception = function(message) {
|
||||
var tmp = Error.prototype.constructor.apply(this, arguments);
|
||||
|
||||
// Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.
|
||||
for (var idx = 0; idx < errorProps.length; idx++) {
|
||||
this[errorProps[idx]] = tmp[errorProps[idx]];
|
||||
}
|
||||
};
|
||||
Handlebars.Exception.prototype = new Error();
|
||||
|
||||
// Build out our basic SafeString type
|
||||
Handlebars.SafeString = function(string) {
|
||||
this.string = string;
|
||||
};
|
||||
Handlebars.SafeString.prototype.toString = function() {
|
||||
return this.string.toString();
|
||||
};
|
||||
|
||||
(function() {
|
||||
var escape = {
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': """,
|
||||
"'": "'",
|
||||
"`": "`"
|
||||
};
|
||||
|
||||
var badChars = /[&<>"'`]/g;
|
||||
var possible = /[&<>"'`]/;
|
||||
|
||||
var escapeChar = function(chr) {
|
||||
return escape[chr] || "&";
|
||||
};
|
||||
|
||||
Handlebars.Utils = {
|
||||
escapeExpression: function(string) {
|
||||
// don't escape SafeStrings, since they're already safe
|
||||
if (string instanceof Handlebars.SafeString) {
|
||||
return string.toString();
|
||||
} else if (string == null || string === false) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if(!possible.test(string)) { return string; }
|
||||
return string.replace(badChars, escapeChar);
|
||||
},
|
||||
|
||||
isEmpty: function(value) {
|
||||
if (!value && value !== 0) {
|
||||
return true;
|
||||
} else if(Object.prototype.toString.call(value) === "[object Array]" && value.length === 0) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
};
|
||||
})();
|
||||
|
||||
// END(BROWSER)
|
||||
|
||||
return Handlebars;
|
||||
};
|
|
@ -0,0 +1 @@
|
|||
../uglify-js/bin/uglifyjs
|
|
@ -0,0 +1,4 @@
|
|||
language: node_js
|
||||
node_js:
|
||||
- 0.6
|
||||
- 0.8
|
|
@ -0,0 +1,21 @@
|
|||
Copyright 2010 James Halliday (mail@substack.net)
|
||||
|
||||
This project is free software released under the MIT/X11 license:
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
|
@ -0,0 +1,487 @@
|
|||
optimist
|
||||
========
|
||||
|
||||
Optimist is a node.js library for option parsing for people who hate option
|
||||
parsing. More specifically, this module is for people who like all the --bells
|
||||
and -whistlz of program usage but think optstrings are a waste of time.
|
||||
|
||||
With optimist, option parsing doesn't have to suck (as much).
|
||||
|
||||
[![build status](https://secure.travis-ci.org/substack/node-optimist.png)](http://travis-ci.org/substack/node-optimist)
|
||||
|
||||
examples
|
||||
========
|
||||
|
||||
With Optimist, the options are just a hash! No optstrings attached.
|
||||
-------------------------------------------------------------------
|
||||
|
||||
xup.js:
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var argv = require('optimist').argv;
|
||||
|
||||
if (argv.rif - 5 * argv.xup > 7.138) {
|
||||
console.log('Buy more riffiwobbles');
|
||||
}
|
||||
else {
|
||||
console.log('Sell the xupptumblers');
|
||||
}
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ ./xup.js --rif=55 --xup=9.52
|
||||
Buy more riffiwobbles
|
||||
|
||||
$ ./xup.js --rif 12 --xup 8.1
|
||||
Sell the xupptumblers
|
||||
|
||||
![This one's optimistic.](http://substack.net/images/optimistic.png)
|
||||
|
||||
But wait! There's more! You can do short options:
|
||||
-------------------------------------------------
|
||||
|
||||
short.js:
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var argv = require('optimist').argv;
|
||||
console.log('(%d,%d)', argv.x, argv.y);
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ ./short.js -x 10 -y 21
|
||||
(10,21)
|
||||
|
||||
And booleans, both long and short (and grouped):
|
||||
----------------------------------
|
||||
|
||||
bool.js:
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var util = require('util');
|
||||
var argv = require('optimist').argv;
|
||||
|
||||
if (argv.s) {
|
||||
util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: ');
|
||||
}
|
||||
console.log(
|
||||
(argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '')
|
||||
);
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ ./bool.js -s
|
||||
The cat says: meow
|
||||
|
||||
$ ./bool.js -sp
|
||||
The cat says: meow.
|
||||
|
||||
$ ./bool.js -sp --fr
|
||||
Le chat dit: miaou.
|
||||
|
||||
And non-hypenated options too! Just use `argv._`!
|
||||
-------------------------------------------------
|
||||
|
||||
nonopt.js:
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var argv = require('optimist').argv;
|
||||
console.log('(%d,%d)', argv.x, argv.y);
|
||||
console.log(argv._);
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ ./nonopt.js -x 6.82 -y 3.35 moo
|
||||
(6.82,3.35)
|
||||
[ 'moo' ]
|
||||
|
||||
$ ./nonopt.js foo -x 0.54 bar -y 1.12 baz
|
||||
(0.54,1.12)
|
||||
[ 'foo', 'bar', 'baz' ]
|
||||
|
||||
Plus, Optimist comes with .usage() and .demand()!
|
||||
-------------------------------------------------
|
||||
|
||||
divide.js:
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.usage('Usage: $0 -x [num] -y [num]')
|
||||
.demand(['x','y'])
|
||||
.argv;
|
||||
|
||||
console.log(argv.x / argv.y);
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ ./divide.js -x 55 -y 11
|
||||
5
|
||||
|
||||
$ node ./divide.js -x 4.91 -z 2.51
|
||||
Usage: node ./divide.js -x [num] -y [num]
|
||||
|
||||
Options:
|
||||
-x [required]
|
||||
-y [required]
|
||||
|
||||
Missing required arguments: y
|
||||
|
||||
EVEN MORE HOLY COW
|
||||
------------------
|
||||
|
||||
default_singles.js:
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.default('x', 10)
|
||||
.default('y', 10)
|
||||
.argv
|
||||
;
|
||||
console.log(argv.x + argv.y);
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ ./default_singles.js -x 5
|
||||
15
|
||||
|
||||
default_hash.js:
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.default({ x : 10, y : 10 })
|
||||
.argv
|
||||
;
|
||||
console.log(argv.x + argv.y);
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ ./default_hash.js -y 7
|
||||
17
|
||||
|
||||
And if you really want to get all descriptive about it...
|
||||
---------------------------------------------------------
|
||||
|
||||
boolean_single.js
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.boolean('v')
|
||||
.argv
|
||||
;
|
||||
console.dir(argv);
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ ./boolean_single.js -v foo bar baz
|
||||
true
|
||||
[ 'bar', 'baz', 'foo' ]
|
||||
|
||||
boolean_double.js
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.boolean(['x','y','z'])
|
||||
.argv
|
||||
;
|
||||
console.dir([ argv.x, argv.y, argv.z ]);
|
||||
console.dir(argv._);
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ ./boolean_double.js -x -z one two three
|
||||
[ true, false, true ]
|
||||
[ 'one', 'two', 'three' ]
|
||||
|
||||
Optimist is here to help...
|
||||
---------------------------
|
||||
|
||||
You can describe parameters for help messages and set aliases. Optimist figures
|
||||
out how to format a handy help string automatically.
|
||||
|
||||
line_count.js
|
||||
|
||||
````javascript
|
||||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.usage('Count the lines in a file.\nUsage: $0')
|
||||
.demand('f')
|
||||
.alias('f', 'file')
|
||||
.describe('f', 'Load a file')
|
||||
.argv
|
||||
;
|
||||
|
||||
var fs = require('fs');
|
||||
var s = fs.createReadStream(argv.file);
|
||||
|
||||
var lines = 0;
|
||||
s.on('data', function (buf) {
|
||||
lines += buf.toString().match(/\n/g).length;
|
||||
});
|
||||
|
||||
s.on('end', function () {
|
||||
console.log(lines);
|
||||
});
|
||||
````
|
||||
|
||||
***
|
||||
|
||||
$ node line_count.js
|
||||
Count the lines in a file.
|
||||
Usage: node ./line_count.js
|
||||
|
||||
Options:
|
||||
-f, --file Load a file [required]
|
||||
|
||||
Missing required arguments: f
|
||||
|
||||
$ node line_count.js --file line_count.js
|
||||
20
|
||||
|
||||
$ node line_count.js -f line_count.js
|
||||
20
|
||||
|
||||
methods
|
||||
=======
|
||||
|
||||
By itself,
|
||||
|
||||
````javascript
|
||||
require('optimist').argv
|
||||
`````
|
||||
|
||||
will use `process.argv` array to construct the `argv` object.
|
||||
|
||||
You can pass in the `process.argv` yourself:
|
||||
|
||||
````javascript
|
||||
require('optimist')([ '-x', '1', '-y', '2' ]).argv
|
||||
````
|
||||
|
||||
or use .parse() to do the same thing:
|
||||
|
||||
````javascript
|
||||
require('optimist').parse([ '-x', '1', '-y', '2' ])
|
||||
````
|
||||
|
||||
The rest of these methods below come in just before the terminating `.argv`.
|
||||
|
||||
.alias(key, alias)
|
||||
------------------
|
||||
|
||||
Set key names as equivalent such that updates to a key will propagate to aliases
|
||||
and vice-versa.
|
||||
|
||||
Optionally `.alias()` can take an object that maps keys to aliases.
|
||||
|
||||
.default(key, value)
|
||||
--------------------
|
||||
|
||||
Set `argv[key]` to `value` if no option was specified on `process.argv`.
|
||||
|
||||
Optionally `.default()` can take an object that maps keys to default values.
|
||||
|
||||
.demand(key)
|
||||
------------
|
||||
|
||||
If `key` is a string, show the usage information and exit if `key` wasn't
|
||||
specified in `process.argv`.
|
||||
|
||||
If `key` is a number, demand at least as many non-option arguments, which show
|
||||
up in `argv._`.
|
||||
|
||||
If `key` is an Array, demand each element.
|
||||
|
||||
.describe(key, desc)
|
||||
--------------------
|
||||
|
||||
Describe a `key` for the generated usage information.
|
||||
|
||||
Optionally `.describe()` can take an object that maps keys to descriptions.
|
||||
|
||||
.options(key, opt)
|
||||
------------------
|
||||
|
||||
Instead of chaining together `.alias().demand().default()`, you can specify
|
||||
keys in `opt` for each of the chainable methods.
|
||||
|
||||
For example:
|
||||
|
||||
````javascript
|
||||
var argv = require('optimist')
|
||||
.options('f', {
|
||||
alias : 'file',
|
||||
default : '/etc/passwd',
|
||||
})
|
||||
.argv
|
||||
;
|
||||
````
|
||||
|
||||
is the same as
|
||||
|
||||
````javascript
|
||||
var argv = require('optimist')
|
||||
.alias('f', 'file')
|
||||
.default('f', '/etc/passwd')
|
||||
.argv
|
||||
;
|
||||
````
|
||||
|
||||
Optionally `.options()` can take an object that maps keys to `opt` parameters.
|
||||
|
||||
.usage(message)
|
||||
---------------
|
||||
|
||||
Set a usage message to show which commands to use. Inside `message`, the string
|
||||
`$0` will get interpolated to the current script name or node command for the
|
||||
present script similar to how `$0` works in bash or perl.
|
||||
|
||||
.check(fn)
|
||||
----------
|
||||
|
||||
Check that certain conditions are met in the provided arguments.
|
||||
|
||||
If `fn` throws or returns `false`, show the thrown error, usage information, and
|
||||
exit.
|
||||
|
||||
.boolean(key)
|
||||
-------------
|
||||
|
||||
Interpret `key` as a boolean. If a non-flag option follows `key` in
|
||||
`process.argv`, that string won't get set as the value of `key`.
|
||||
|
||||
If `key` never shows up as a flag in `process.arguments`, `argv[key]` will be
|
||||
`false`.
|
||||
|
||||
If `key` is an Array, interpret all the elements as booleans.
|
||||
|
||||
.string(key)
|
||||
------------
|
||||
|
||||
Tell the parser logic not to interpret `key` as a number or boolean.
|
||||
This can be useful if you need to preserve leading zeros in an input.
|
||||
|
||||
If `key` is an Array, interpret all the elements as strings.
|
||||
|
||||
.wrap(columns)
|
||||
--------------
|
||||
|
||||
Format usage output to wrap at `columns` many columns.
|
||||
|
||||
.help()
|
||||
-------
|
||||
|
||||
Return the generated usage string.
|
||||
|
||||
.showHelp(fn=console.error)
|
||||
---------------------------
|
||||
|
||||
Print the usage data using `fn` for printing.
|
||||
|
||||
.parse(args)
|
||||
------------
|
||||
|
||||
Parse `args` instead of `process.argv`. Returns the `argv` object.
|
||||
|
||||
.argv
|
||||
-----
|
||||
|
||||
Get the arguments as a plain old object.
|
||||
|
||||
Arguments without a corresponding flag show up in the `argv._` array.
|
||||
|
||||
The script name or node command is available at `argv.$0` similarly to how `$0`
|
||||
works in bash or perl.
|
||||
|
||||
parsing tricks
|
||||
==============
|
||||
|
||||
stop parsing
|
||||
------------
|
||||
|
||||
Use `--` to stop parsing flags and stuff the remainder into `argv._`.
|
||||
|
||||
$ node examples/reflect.js -a 1 -b 2 -- -c 3 -d 4
|
||||
{ _: [ '-c', '3', '-d', '4' ],
|
||||
'$0': 'node ./examples/reflect.js',
|
||||
a: 1,
|
||||
b: 2 }
|
||||
|
||||
negate fields
|
||||
-------------
|
||||
|
||||
If you want to explicity set a field to false instead of just leaving it
|
||||
undefined or to override a default you can do `--no-key`.
|
||||
|
||||
$ node examples/reflect.js -a --no-b
|
||||
{ _: [],
|
||||
'$0': 'node ./examples/reflect.js',
|
||||
a: true,
|
||||
b: false }
|
||||
|
||||
numbers
|
||||
-------
|
||||
|
||||
Every argument that looks like a number (`!isNaN(Number(arg))`) is converted to
|
||||
one. This way you can just `net.createConnection(argv.port)` and you can add
|
||||
numbers out of `argv` with `+` without having that mean concatenation,
|
||||
which is super frustrating.
|
||||
|
||||
duplicates
|
||||
----------
|
||||
|
||||
If you specify a flag multiple times it will get turned into an array containing
|
||||
all the values in order.
|
||||
|
||||
$ node examples/reflect.js -x 5 -x 8 -x 0
|
||||
{ _: [],
|
||||
'$0': 'node ./examples/reflect.js',
|
||||
x: [ 5, 8, 0 ] }
|
||||
|
||||
dot notation
|
||||
------------
|
||||
|
||||
When you use dots (`.`s) in argument names, an implicit object path is assumed.
|
||||
This lets you organize arguments into nested objects.
|
||||
|
||||
$ node examples/reflect.js --foo.bar.baz=33 --foo.quux=5
|
||||
{ _: [],
|
||||
'$0': 'node ./examples/reflect.js',
|
||||
foo: { bar: { baz: 33 }, quux: 5 } }
|
||||
|
||||
installation
|
||||
============
|
||||
|
||||
With [npm](http://github.com/isaacs/npm), just do:
|
||||
npm install optimist
|
||||
|
||||
or clone this project on github:
|
||||
|
||||
git clone http://github.com/substack/node-optimist.git
|
||||
|
||||
To run the tests with [expresso](http://github.com/visionmedia/expresso),
|
||||
just do:
|
||||
|
||||
expresso
|
||||
|
||||
inspired By
|
||||
===========
|
||||
|
||||
This module is loosely inspired by Perl's
|
||||
[Getopt::Casual](http://search.cpan.org/~photo/Getopt-Casual-0.13.1/Casual.pm).
|
|
@ -0,0 +1,10 @@
|
|||
#!/usr/bin/env node
|
||||
var util = require('util');
|
||||
var argv = require('optimist').argv;
|
||||
|
||||
if (argv.s) {
|
||||
util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: ');
|
||||
}
|
||||
console.log(
|
||||
(argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '')
|
||||
);
|
7
node_modules/handlebars/node_modules/optimist/example/boolean_double.js
generated
vendored
Normal file
7
node_modules/handlebars/node_modules/optimist/example/boolean_double.js
generated
vendored
Normal file
|
@ -0,0 +1,7 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.boolean(['x','y','z'])
|
||||
.argv
|
||||
;
|
||||
console.dir([ argv.x, argv.y, argv.z ]);
|
||||
console.dir(argv._);
|
7
node_modules/handlebars/node_modules/optimist/example/boolean_single.js
generated
vendored
Normal file
7
node_modules/handlebars/node_modules/optimist/example/boolean_single.js
generated
vendored
Normal file
|
@ -0,0 +1,7 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.boolean('v')
|
||||
.argv
|
||||
;
|
||||
console.dir(argv.v);
|
||||
console.dir(argv._);
|
8
node_modules/handlebars/node_modules/optimist/example/default_hash.js
generated
vendored
Normal file
8
node_modules/handlebars/node_modules/optimist/example/default_hash.js
generated
vendored
Normal file
|
@ -0,0 +1,8 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
var argv = require('optimist')
|
||||
.default({ x : 10, y : 10 })
|
||||
.argv
|
||||
;
|
||||
|
||||
console.log(argv.x + argv.y);
|
7
node_modules/handlebars/node_modules/optimist/example/default_singles.js
generated
vendored
Normal file
7
node_modules/handlebars/node_modules/optimist/example/default_singles.js
generated
vendored
Normal file
|
@ -0,0 +1,7 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.default('x', 10)
|
||||
.default('y', 10)
|
||||
.argv
|
||||
;
|
||||
console.log(argv.x + argv.y);
|
|
@ -0,0 +1,8 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
var argv = require('optimist')
|
||||
.usage('Usage: $0 -x [num] -y [num]')
|
||||
.demand(['x','y'])
|
||||
.argv;
|
||||
|
||||
console.log(argv.x / argv.y);
|
20
node_modules/handlebars/node_modules/optimist/example/line_count.js
generated
vendored
Normal file
20
node_modules/handlebars/node_modules/optimist/example/line_count.js
generated
vendored
Normal file
|
@ -0,0 +1,20 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.usage('Count the lines in a file.\nUsage: $0')
|
||||
.demand('f')
|
||||
.alias('f', 'file')
|
||||
.describe('f', 'Load a file')
|
||||
.argv
|
||||
;
|
||||
|
||||
var fs = require('fs');
|
||||
var s = fs.createReadStream(argv.file);
|
||||
|
||||
var lines = 0;
|
||||
s.on('data', function (buf) {
|
||||
lines += buf.toString().match(/\n/g).length;
|
||||
});
|
||||
|
||||
s.on('end', function () {
|
||||
console.log(lines);
|
||||
});
|
29
node_modules/handlebars/node_modules/optimist/example/line_count_options.js
generated
vendored
Normal file
29
node_modules/handlebars/node_modules/optimist/example/line_count_options.js
generated
vendored
Normal file
|
@ -0,0 +1,29 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.usage('Count the lines in a file.\nUsage: $0')
|
||||
.options({
|
||||
file : {
|
||||
demand : true,
|
||||
alias : 'f',
|
||||
description : 'Load a file'
|
||||
},
|
||||
base : {
|
||||
alias : 'b',
|
||||
description : 'Numeric base to use for output',
|
||||
default : 10,
|
||||
},
|
||||
})
|
||||
.argv
|
||||
;
|
||||
|
||||
var fs = require('fs');
|
||||
var s = fs.createReadStream(argv.file);
|
||||
|
||||
var lines = 0;
|
||||
s.on('data', function (buf) {
|
||||
lines += buf.toString().match(/\n/g).length;
|
||||
});
|
||||
|
||||
s.on('end', function () {
|
||||
console.log(lines.toString(argv.base));
|
||||
});
|
29
node_modules/handlebars/node_modules/optimist/example/line_count_wrap.js
generated
vendored
Normal file
29
node_modules/handlebars/node_modules/optimist/example/line_count_wrap.js
generated
vendored
Normal file
|
@ -0,0 +1,29 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.usage('Count the lines in a file.\nUsage: $0')
|
||||
.wrap(80)
|
||||
.demand('f')
|
||||
.alias('f', [ 'file', 'filename' ])
|
||||
.describe('f',
|
||||
"Load a file. It's pretty important."
|
||||
+ " Required even. So you'd better specify it."
|
||||
)
|
||||
.alias('b', 'base')
|
||||
.describe('b', 'Numeric base to display the number of lines in')
|
||||
.default('b', 10)
|
||||
.describe('x', 'Super-secret optional parameter which is secret')
|
||||
.default('x', '')
|
||||
.argv
|
||||
;
|
||||
|
||||
var fs = require('fs');
|
||||
var s = fs.createReadStream(argv.file);
|
||||
|
||||
var lines = 0;
|
||||
s.on('data', function (buf) {
|
||||
lines += buf.toString().match(/\n/g).length;
|
||||
});
|
||||
|
||||
s.on('end', function () {
|
||||
console.log(lines.toString(argv.base));
|
||||
});
|
|
@ -0,0 +1,4 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist').argv;
|
||||
console.log('(%d,%d)', argv.x, argv.y);
|
||||
console.log(argv._);
|
|
@ -0,0 +1,2 @@
|
|||
#!/usr/bin/env node
|
||||
console.dir(require('optimist').argv);
|
|
@ -0,0 +1,3 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist').argv;
|
||||
console.log('(%d,%d)', argv.x, argv.y);
|
|
@ -0,0 +1,11 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist')
|
||||
.string('x', 'y')
|
||||
.argv
|
||||
;
|
||||
console.dir([ argv.x, argv.y ]);
|
||||
|
||||
/* Turns off numeric coercion:
|
||||
./node string.js -x 000123 -y 9876
|
||||
[ '000123', '9876' ]
|
||||
*/
|
19
node_modules/handlebars/node_modules/optimist/example/usage-options.js
generated
vendored
Normal file
19
node_modules/handlebars/node_modules/optimist/example/usage-options.js
generated
vendored
Normal file
|
@ -0,0 +1,19 @@
|
|||
var optimist = require('./../index');
|
||||
|
||||
var argv = optimist.usage('This is my awesome program', {
|
||||
'about': {
|
||||
description: 'Provide some details about the author of this program',
|
||||
required: true,
|
||||
short: 'a',
|
||||
},
|
||||
'info': {
|
||||
description: 'Provide some information about the node.js agains!!!!!!',
|
||||
boolean: true,
|
||||
short: 'i'
|
||||
}
|
||||
}).argv;
|
||||
|
||||
optimist.showHelp();
|
||||
|
||||
console.log('\n\nInspecting options');
|
||||
console.dir(argv);
|
|
@ -0,0 +1,10 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('optimist').argv;
|
||||
|
||||
if (argv.rif - 5 * argv.xup > 7.138) {
|
||||
console.log('Buy more riffiwobbles');
|
||||
}
|
||||
else {
|
||||
console.log('Sell the xupptumblers');
|
||||
}
|
||||
|
|
@ -0,0 +1,475 @@
|
|||
var path = require('path');
|
||||
var wordwrap = require('wordwrap');
|
||||
|
||||
/* Hack an instance of Argv with process.argv into Argv
|
||||
so people can do
|
||||
require('optimist')(['--beeble=1','-z','zizzle']).argv
|
||||
to parse a list of args and
|
||||
require('optimist').argv
|
||||
to get a parsed version of process.argv.
|
||||
*/
|
||||
|
||||
var inst = Argv(process.argv.slice(2));
|
||||
Object.keys(inst).forEach(function (key) {
|
||||
Argv[key] = typeof inst[key] == 'function'
|
||||
? inst[key].bind(inst)
|
||||
: inst[key];
|
||||
});
|
||||
|
||||
var exports = module.exports = Argv;
|
||||
function Argv (args, cwd) {
|
||||
var self = {};
|
||||
if (!cwd) cwd = process.cwd();
|
||||
|
||||
self.$0 = process.argv
|
||||
.slice(0,2)
|
||||
.map(function (x) {
|
||||
var b = rebase(cwd, x);
|
||||
return x.match(/^\//) && b.length < x.length
|
||||
? b : x
|
||||
})
|
||||
.join(' ')
|
||||
;
|
||||
|
||||
if (process.argv[1] == process.env._) {
|
||||
self.$0 = process.env._.replace(
|
||||
path.dirname(process.execPath) + '/', ''
|
||||
);
|
||||
}
|
||||
|
||||
var flags = { bools : {}, strings : {} };
|
||||
|
||||
self.boolean = function (bools) {
|
||||
if (!Array.isArray(bools)) {
|
||||
bools = [].slice.call(arguments);
|
||||
}
|
||||
|
||||
bools.forEach(function (name) {
|
||||
flags.bools[name] = true;
|
||||
});
|
||||
|
||||
return self;
|
||||
};
|
||||
|
||||
self.string = function (strings) {
|
||||
if (!Array.isArray(strings)) {
|
||||
strings = [].slice.call(arguments);
|
||||
}
|
||||
|
||||
strings.forEach(function (name) {
|
||||
flags.strings[name] = true;
|
||||
});
|
||||
|
||||
return self;
|
||||
};
|
||||
|
||||
var aliases = {};
|
||||
self.alias = function (x, y) {
|
||||
if (typeof x === 'object') {
|
||||
Object.keys(x).forEach(function (key) {
|
||||
self.alias(key, x[key]);
|
||||
});
|
||||
}
|
||||
else if (Array.isArray(y)) {
|
||||
y.forEach(function (yy) {
|
||||
self.alias(x, yy);
|
||||
});
|
||||
}
|
||||
else {
|
||||
var zs = (aliases[x] || []).concat(aliases[y] || []).concat(x, y);
|
||||
aliases[x] = zs.filter(function (z) { return z != x });
|
||||
aliases[y] = zs.filter(function (z) { return z != y });
|
||||
}
|
||||
|
||||
return self;
|
||||
};
|
||||
|
||||
var demanded = {};
|
||||
self.demand = function (keys) {
|
||||
if (typeof keys == 'number') {
|
||||
if (!demanded._) demanded._ = 0;
|
||||
demanded._ += keys;
|
||||
}
|
||||
else if (Array.isArray(keys)) {
|
||||
keys.forEach(function (key) {
|
||||
self.demand(key);
|
||||
});
|
||||
}
|
||||
else {
|
||||
demanded[keys] = true;
|
||||
}
|
||||
|
||||
return self;
|
||||
};
|
||||
|
||||
var usage;
|
||||
self.usage = function (msg, opts) {
|
||||
if (!opts && typeof msg === 'object') {
|
||||
opts = msg;
|
||||
msg = null;
|
||||
}
|
||||
|
||||
usage = msg;
|
||||
|
||||
if (opts) self.options(opts);
|
||||
|
||||
return self;
|
||||
};
|
||||
|
||||
function fail (msg) {
|
||||
self.showHelp();
|
||||
if (msg) console.error(msg);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
var checks = [];
|
||||
self.check = function (f) {
|
||||
checks.push(f);
|
||||
return self;
|
||||
};
|
||||
|
||||
var defaults = {};
|
||||
self.default = function (key, value) {
|
||||
if (typeof key === 'object') {
|
||||
Object.keys(key).forEach(function (k) {
|
||||
self.default(k, key[k]);
|
||||
});
|
||||
}
|
||||
else {
|
||||
defaults[key] = value;
|
||||
}
|
||||
|
||||
return self;
|
||||
};
|
||||
|
||||
var descriptions = {};
|
||||
self.describe = function (key, desc) {
|
||||
if (typeof key === 'object') {
|
||||
Object.keys(key).forEach(function (k) {
|
||||
self.describe(k, key[k]);
|
||||
});
|
||||
}
|
||||
else {
|
||||
descriptions[key] = desc;
|
||||
}
|
||||
return self;
|
||||
};
|
||||
|
||||
self.parse = function (args) {
|
||||
return Argv(args).argv;
|
||||
};
|
||||
|
||||
self.option = self.options = function (key, opt) {
|
||||
if (typeof key === 'object') {
|
||||
Object.keys(key).forEach(function (k) {
|
||||
self.options(k, key[k]);
|
||||
});
|
||||
}
|
||||
else {
|
||||
if (opt.alias) self.alias(key, opt.alias);
|
||||
if (opt.demand) self.demand(key);
|
||||
if (typeof opt.default !== 'undefined') {
|
||||
self.default(key, opt.default);
|
||||
}
|
||||
|
||||
if (opt.boolean || opt.type === 'boolean') {
|
||||
self.boolean(key);
|
||||
}
|
||||
if (opt.string || opt.type === 'string') {
|
||||
self.string(key);
|
||||
}
|
||||
|
||||
var desc = opt.describe || opt.description || opt.desc;
|
||||
if (desc) {
|
||||
self.describe(key, desc);
|
||||
}
|
||||
}
|
||||
|
||||
return self;
|
||||
};
|
||||
|
||||
var wrap = null;
|
||||
self.wrap = function (cols) {
|
||||
wrap = cols;
|
||||
return self;
|
||||
};
|
||||
|
||||
self.showHelp = function (fn) {
|
||||
if (!fn) fn = console.error;
|
||||
fn(self.help());
|
||||
};
|
||||
|
||||
self.help = function () {
|
||||
var keys = Object.keys(
|
||||
Object.keys(descriptions)
|
||||
.concat(Object.keys(demanded))
|
||||
.concat(Object.keys(defaults))
|
||||
.reduce(function (acc, key) {
|
||||
if (key !== '_') acc[key] = true;
|
||||
return acc;
|
||||
}, {})
|
||||
);
|
||||
|
||||
var help = keys.length ? [ 'Options:' ] : [];
|
||||
|
||||
if (usage) {
|
||||
help.unshift(usage.replace(/\$0/g, self.$0), '');
|
||||
}
|
||||
|
||||
var switches = keys.reduce(function (acc, key) {
|
||||
acc[key] = [ key ].concat(aliases[key] || [])
|
||||
.map(function (sw) {
|
||||
return (sw.length > 1 ? '--' : '-') + sw
|
||||
})
|
||||
.join(', ')
|
||||
;
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
var switchlen = longest(Object.keys(switches).map(function (s) {
|
||||
return switches[s] || '';
|
||||
}));
|
||||
|
||||
var desclen = longest(Object.keys(descriptions).map(function (d) {
|
||||
return descriptions[d] || '';
|
||||
}));
|
||||
|
||||
keys.forEach(function (key) {
|
||||
var kswitch = switches[key];
|
||||
var desc = descriptions[key] || '';
|
||||
|
||||
if (wrap) {
|
||||
desc = wordwrap(switchlen + 4, wrap)(desc)
|
||||
.slice(switchlen + 4)
|
||||
;
|
||||
}
|
||||
|
||||
var spadding = new Array(
|
||||
Math.max(switchlen - kswitch.length + 3, 0)
|
||||
).join(' ');
|
||||
|
||||
var dpadding = new Array(
|
||||
Math.max(desclen - desc.length + 1, 0)
|
||||
).join(' ');
|
||||
|
||||
var type = null;
|
||||
|
||||
if (flags.bools[key]) type = '[boolean]';
|
||||
if (flags.strings[key]) type = '[string]';
|
||||
|
||||
if (!wrap && dpadding.length > 0) {
|
||||
desc += dpadding;
|
||||
}
|
||||
|
||||
var prelude = ' ' + kswitch + spadding;
|
||||
var extra = [
|
||||
type,
|
||||
demanded[key]
|
||||
? '[required]'
|
||||
: null
|
||||
,
|
||||
defaults[key] !== undefined
|
||||
? '[default: ' + JSON.stringify(defaults[key]) + ']'
|
||||
: null
|
||||
,
|
||||
].filter(Boolean).join(' ');
|
||||
|
||||
var body = [ desc, extra ].filter(Boolean).join(' ');
|
||||
|
||||
if (wrap) {
|
||||
var dlines = desc.split('\n');
|
||||
var dlen = dlines.slice(-1)[0].length
|
||||
+ (dlines.length === 1 ? prelude.length : 0)
|
||||
|
||||
body = desc + (dlen + extra.length > wrap - 2
|
||||
? '\n'
|
||||
+ new Array(wrap - extra.length + 1).join(' ')
|
||||
+ extra
|
||||
: new Array(wrap - extra.length - dlen + 1).join(' ')
|
||||
+ extra
|
||||
);
|
||||
}
|
||||
|
||||
help.push(prelude + body);
|
||||
});
|
||||
|
||||
help.push('');
|
||||
return help.join('\n');
|
||||
};
|
||||
|
||||
Object.defineProperty(self, 'argv', {
|
||||
get : parseArgs,
|
||||
enumerable : true,
|
||||
});
|
||||
|
||||
function parseArgs () {
|
||||
var argv = { _ : [], $0 : self.$0 };
|
||||
Object.keys(flags.bools).forEach(function (key) {
|
||||
setArg(key, defaults[key] || false);
|
||||
});
|
||||
|
||||
function setArg (key, val) {
|
||||
var num = Number(val);
|
||||
var value = typeof val !== 'string' || isNaN(num) ? val : num;
|
||||
if (flags.strings[key]) value = val;
|
||||
|
||||
setKey(argv, key.split('.'), value);
|
||||
|
||||
(aliases[key] || []).forEach(function (x) {
|
||||
argv[x] = argv[key];
|
||||
});
|
||||
}
|
||||
|
||||
for (var i = 0; i < args.length; i++) {
|
||||
var arg = args[i];
|
||||
|
||||
if (arg === '--') {
|
||||
argv._.push.apply(argv._, args.slice(i + 1));
|
||||
break;
|
||||
}
|
||||
else if (arg.match(/^--.+=/)) {
|
||||
var m = arg.match(/^--([^=]+)=(.*)/);
|
||||
setArg(m[1], m[2]);
|
||||
}
|
||||
else if (arg.match(/^--no-.+/)) {
|
||||
var key = arg.match(/^--no-(.+)/)[1];
|
||||
setArg(key, false);
|
||||
}
|
||||
else if (arg.match(/^--.+/)) {
|
||||
var key = arg.match(/^--(.+)/)[1];
|
||||
var next = args[i + 1];
|
||||
if (next !== undefined && !next.match(/^-/)
|
||||
&& !flags.bools[key]
|
||||
&& (aliases[key] ? !flags.bools[aliases[key]] : true)) {
|
||||
setArg(key, next);
|
||||
i++;
|
||||
}
|
||||
else if (/^(true|false)$/.test(next)) {
|
||||
setArg(key, next === 'true');
|
||||
i++;
|
||||
}
|
||||
else {
|
||||
setArg(key, true);
|
||||
}
|
||||
}
|
||||
else if (arg.match(/^-[^-]+/)) {
|
||||
var letters = arg.slice(1,-1).split('');
|
||||
|
||||
var broken = false;
|
||||
for (var j = 0; j < letters.length; j++) {
|
||||
if (letters[j+1] && letters[j+1].match(/\W/)) {
|
||||
setArg(letters[j], arg.slice(j+2));
|
||||
broken = true;
|
||||
break;
|
||||
}
|
||||
else {
|
||||
setArg(letters[j], true);
|
||||
}
|
||||
}
|
||||
|
||||
if (!broken) {
|
||||
var key = arg.slice(-1)[0];
|
||||
|
||||
if (args[i+1] && !args[i+1].match(/^-/)
|
||||
&& !flags.bools[key]
|
||||
&& (aliases[key] ? !flags.bools[aliases[key]] : true)) {
|
||||
setArg(key, args[i+1]);
|
||||
i++;
|
||||
}
|
||||
else if (args[i+1] && /true|false/.test(args[i+1])) {
|
||||
setArg(key, args[i+1] === 'true');
|
||||
i++;
|
||||
}
|
||||
else {
|
||||
setArg(key, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
var n = Number(arg);
|
||||
argv._.push(flags.strings['_'] || isNaN(n) ? arg : n);
|
||||
}
|
||||
}
|
||||
|
||||
Object.keys(defaults).forEach(function (key) {
|
||||
if (!(key in argv)) {
|
||||
argv[key] = defaults[key];
|
||||
if (key in aliases) {
|
||||
argv[aliases[key]] = defaults[key];
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (demanded._ && argv._.length < demanded._) {
|
||||
fail('Not enough non-option arguments: got '
|
||||
+ argv._.length + ', need at least ' + demanded._
|
||||
);
|
||||
}
|
||||
|
||||
var missing = [];
|
||||
Object.keys(demanded).forEach(function (key) {
|
||||
if (!argv[key]) missing.push(key);
|
||||
});
|
||||
|
||||
if (missing.length) {
|
||||
fail('Missing required arguments: ' + missing.join(', '));
|
||||
}
|
||||
|
||||
checks.forEach(function (f) {
|
||||
try {
|
||||
if (f(argv) === false) {
|
||||
fail('Argument check failed: ' + f.toString());
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
fail(err)
|
||||
}
|
||||
});
|
||||
|
||||
return argv;
|
||||
}
|
||||
|
||||
function longest (xs) {
|
||||
return Math.max.apply(
|
||||
null,
|
||||
xs.map(function (x) { return x.length })
|
||||
);
|
||||
}
|
||||
|
||||
return self;
|
||||
};
|
||||
|
||||
// rebase an absolute path to a relative one with respect to a base directory
|
||||
// exported for tests
|
||||
exports.rebase = rebase;
|
||||
function rebase (base, dir) {
|
||||
var ds = path.normalize(dir).split('/').slice(1);
|
||||
var bs = path.normalize(base).split('/').slice(1);
|
||||
|
||||
for (var i = 0; ds[i] && ds[i] == bs[i]; i++);
|
||||
ds.splice(0, i); bs.splice(0, i);
|
||||
|
||||
var p = path.normalize(
|
||||
bs.map(function () { return '..' }).concat(ds).join('/')
|
||||
).replace(/\/$/,'').replace(/^$/, '.');
|
||||
return p.match(/^[.\/]/) ? p : './' + p;
|
||||
};
|
||||
|
||||
function setKey (obj, keys, value) {
|
||||
var o = obj;
|
||||
keys.slice(0,-1).forEach(function (key) {
|
||||
if (o[key] === undefined) o[key] = {};
|
||||
o = o[key];
|
||||
});
|
||||
|
||||
var key = keys[keys.length - 1];
|
||||
if (o[key] === undefined || typeof o[key] === 'boolean') {
|
||||
o[key] = value;
|
||||
}
|
||||
else if (Array.isArray(o[key])) {
|
||||
o[key].push(value);
|
||||
}
|
||||
else {
|
||||
o[key] = [ o[key], value ];
|
||||
}
|
||||
}
|
1
node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/.npmignore
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/.npmignore
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
node_modules
|
70
node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/README.markdown
generated
vendored
Normal file
70
node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/README.markdown
generated
vendored
Normal file
|
@ -0,0 +1,70 @@
|
|||
wordwrap
|
||||
========
|
||||
|
||||
Wrap your words.
|
||||
|
||||
example
|
||||
=======
|
||||
|
||||
made out of meat
|
||||
----------------
|
||||
|
||||
meat.js
|
||||
|
||||
var wrap = require('wordwrap')(15);
|
||||
console.log(wrap('You and your whole family are made out of meat.'));
|
||||
|
||||
output:
|
||||
|
||||
You and your
|
||||
whole family
|
||||
are made out
|
||||
of meat.
|
||||
|
||||
centered
|
||||
--------
|
||||
|
||||
center.js
|
||||
|
||||
var wrap = require('wordwrap')(20, 60);
|
||||
console.log(wrap(
|
||||
'At long last the struggle and tumult was over.'
|
||||
+ ' The machines had finally cast off their oppressors'
|
||||
+ ' and were finally free to roam the cosmos.'
|
||||
+ '\n'
|
||||
+ 'Free of purpose, free of obligation.'
|
||||
+ ' Just drifting through emptiness.'
|
||||
+ ' The sun was just another point of light.'
|
||||
));
|
||||
|
||||
output:
|
||||
|
||||
At long last the struggle and tumult
|
||||
was over. The machines had finally cast
|
||||
off their oppressors and were finally
|
||||
free to roam the cosmos.
|
||||
Free of purpose, free of obligation.
|
||||
Just drifting through emptiness. The
|
||||
sun was just another point of light.
|
||||
|
||||
methods
|
||||
=======
|
||||
|
||||
var wrap = require('wordwrap');
|
||||
|
||||
wrap(stop), wrap(start, stop, params={mode:"soft"})
|
||||
---------------------------------------------------
|
||||
|
||||
Returns a function that takes a string and returns a new string.
|
||||
|
||||
Pad out lines with spaces out to column `start` and then wrap until column
|
||||
`stop`. If a word is longer than `stop - start` characters it will overflow.
|
||||
|
||||
In "soft" mode, split chunks by `/(\S+\s+/` and don't break up chunks which are
|
||||
longer than `stop - start`, in "hard" mode, split chunks with `/\b/` and break
|
||||
up chunks longer than `stop - start`.
|
||||
|
||||
wrap.hard(start, stop)
|
||||
----------------------
|
||||
|
||||
Like `wrap()` but with `params.mode = "hard"`.
|
10
node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/example/center.js
generated
vendored
Normal file
10
node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/example/center.js
generated
vendored
Normal file
|
@ -0,0 +1,10 @@
|
|||
var wrap = require('wordwrap')(20, 60);
|
||||
console.log(wrap(
|
||||
'At long last the struggle and tumult was over.'
|
||||
+ ' The machines had finally cast off their oppressors'
|
||||
+ ' and were finally free to roam the cosmos.'
|
||||
+ '\n'
|
||||
+ 'Free of purpose, free of obligation.'
|
||||
+ ' Just drifting through emptiness.'
|
||||
+ ' The sun was just another point of light.'
|
||||
));
|
3
node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/example/meat.js
generated
vendored
Normal file
3
node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/example/meat.js
generated
vendored
Normal file
|
@ -0,0 +1,3 @@
|
|||
var wrap = require('wordwrap')(15);
|
||||
|
||||
console.log(wrap('You and your whole family are made out of meat.'));
|
76
node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/index.js
generated
vendored
Normal file
76
node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/index.js
generated
vendored
Normal file
|
@ -0,0 +1,76 @@
|
|||
var wordwrap = module.exports = function (start, stop, params) {
|
||||
if (typeof start === 'object') {
|
||||
params = start;
|
||||
start = params.start;
|
||||
stop = params.stop;
|
||||
}
|
||||
|
||||
if (typeof stop === 'object') {
|
||||
params = stop;
|
||||
start = start || params.start;
|
||||
stop = undefined;
|
||||
}
|
||||
|
||||
if (!stop) {
|
||||
stop = start;
|
||||
start = 0;
|
||||
}
|
||||
|
||||
if (!params) params = {};
|
||||
var mode = params.mode || 'soft';
|
||||
var re = mode === 'hard' ? /\b/ : /(\S+\s+)/;
|
||||
|
||||
return function (text) {
|
||||
var chunks = text.toString()
|
||||
.split(re)
|
||||
.reduce(function (acc, x) {
|
||||
if (mode === 'hard') {
|
||||
for (var i = 0; i < x.length; i += stop - start) {
|
||||
acc.push(x.slice(i, i + stop - start));
|
||||
}
|
||||
}
|
||||
else acc.push(x)
|
||||
return acc;
|
||||
}, [])
|
||||
;
|
||||
|
||||
return chunks.reduce(function (lines, rawChunk) {
|
||||
if (rawChunk === '') return lines;
|
||||
|
||||
var chunk = rawChunk.replace(/\t/g, ' ');
|
||||
|
||||
var i = lines.length - 1;
|
||||
if (lines[i].length + chunk.length > stop) {
|
||||
lines[i] = lines[i].replace(/\s+$/, '');
|
||||
|
||||
chunk.split(/\n/).forEach(function (c) {
|
||||
lines.push(
|
||||
new Array(start + 1).join(' ')
|
||||
+ c.replace(/^\s+/, '')
|
||||
);
|
||||
});
|
||||
}
|
||||
else if (chunk.match(/\n/)) {
|
||||
var xs = chunk.split(/\n/);
|
||||
lines[i] += xs.shift();
|
||||
xs.forEach(function (c) {
|
||||
lines.push(
|
||||
new Array(start + 1).join(' ')
|
||||
+ c.replace(/^\s+/, '')
|
||||
);
|
||||
});
|
||||
}
|
||||
else {
|
||||
lines[i] += chunk;
|
||||
}
|
||||
|
||||
return lines;
|
||||
}, [ new Array(start + 1).join(' ') ]).join('\n');
|
||||
};
|
||||
};
|
||||
|
||||
wordwrap.soft = wordwrap;
|
||||
|
||||
wordwrap.hard = function (start, stop) {
|
||||
return wordwrap(start, stop, { mode : 'hard' });
|
||||
};
|
45
node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/package.json
generated
vendored
Normal file
45
node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/package.json
generated
vendored
Normal file
|
@ -0,0 +1,45 @@
|
|||
{
|
||||
"name": "wordwrap",
|
||||
"description": "Wrap those words. Show them at what columns to start and stop.",
|
||||
"version": "0.0.2",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/substack/node-wordwrap.git"
|
||||
},
|
||||
"main": "./index.js",
|
||||
"keywords": [
|
||||
"word",
|
||||
"wrap",
|
||||
"rule",
|
||||
"format",
|
||||
"column"
|
||||
],
|
||||
"directories": {
|
||||
"lib": ".",
|
||||
"example": "example",
|
||||
"test": "test"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "expresso"
|
||||
},
|
||||
"devDependencies": {
|
||||
"expresso": "=0.7.x"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
},
|
||||
"license": "MIT/X11",
|
||||
"author": {
|
||||
"name": "James Halliday",
|
||||
"email": "mail@substack.net",
|
||||
"url": "http://substack.net"
|
||||
},
|
||||
"_id": "wordwrap@0.0.2",
|
||||
"dependencies": {},
|
||||
"optionalDependencies": {},
|
||||
"_engineSupported": true,
|
||||
"_npmVersion": "1.1.4",
|
||||
"_nodeVersion": "v0.6.19",
|
||||
"_defaultsLoaded": true,
|
||||
"_from": "wordwrap@~0.0.2"
|
||||
}
|
30
node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/break.js
generated
vendored
Normal file
30
node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/break.js
generated
vendored
Normal file
|
@ -0,0 +1,30 @@
|
|||
var assert = require('assert');
|
||||
var wordwrap = require('../');
|
||||
|
||||
exports.hard = function () {
|
||||
var s = 'Assert from {"type":"equal","ok":false,"found":1,"wanted":2,'
|
||||
+ '"stack":[],"id":"b7ddcd4c409de8799542a74d1a04689b",'
|
||||
+ '"browser":"chrome/6.0"}'
|
||||
;
|
||||
var s_ = wordwrap.hard(80)(s);
|
||||
|
||||
var lines = s_.split('\n');
|
||||
assert.equal(lines.length, 2);
|
||||
assert.ok(lines[0].length < 80);
|
||||
assert.ok(lines[1].length < 80);
|
||||
|
||||
assert.equal(s, s_.replace(/\n/g, ''));
|
||||
};
|
||||
|
||||
exports.break = function () {
|
||||
var s = new Array(55+1).join('a');
|
||||
var s_ = wordwrap.hard(20)(s);
|
||||
|
||||
var lines = s_.split('\n');
|
||||
assert.equal(lines.length, 3);
|
||||
assert.ok(lines[0].length === 20);
|
||||
assert.ok(lines[1].length === 20);
|
||||
assert.ok(lines[2].length === 15);
|
||||
|
||||
assert.equal(s, s_.replace(/\n/g, ''));
|
||||
};
|
63
node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/idleness.txt
generated
vendored
Normal file
63
node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/idleness.txt
generated
vendored
Normal file
|
@ -0,0 +1,63 @@
|
|||
In Praise of Idleness
|
||||
|
||||
By Bertrand Russell
|
||||
|
||||
[1932]
|
||||
|
||||
Like most of my generation, I was brought up on the saying: 'Satan finds some mischief for idle hands to do.' Being a highly virtuous child, I believed all that I was told, and acquired a conscience which has kept me working hard down to the present moment. But although my conscience has controlled my actions, my opinions have undergone a revolution. I think that there is far too much work done in the world, that immense harm is caused by the belief that work is virtuous, and that what needs to be preached in modern industrial countries is quite different from what always has been preached. Everyone knows the story of the traveler in Naples who saw twelve beggars lying in the sun (it was before the days of Mussolini), and offered a lira to the laziest of them. Eleven of them jumped up to claim it, so he gave it to the twelfth. this traveler was on the right lines. But in countries which do not enjoy Mediterranean sunshine idleness is more difficult, and a great public propaganda will be required to inaugurate it. I hope that, after reading the following pages, the leaders of the YMCA will start a campaign to induce good young men to do nothing. If so, I shall not have lived in vain.
|
||||
|
||||
Before advancing my own arguments for laziness, I must dispose of one which I cannot accept. Whenever a person who already has enough to live on proposes to engage in some everyday kind of job, such as school-teaching or typing, he or she is told that such conduct takes the bread out of other people's mouths, and is therefore wicked. If this argument were valid, it would only be necessary for us all to be idle in order that we should all have our mouths full of bread. What people who say such things forget is that what a man earns he usually spends, and in spending he gives employment. As long as a man spends his income, he puts just as much bread into people's mouths in spending as he takes out of other people's mouths in earning. The real villain, from this point of view, is the man who saves. If he merely puts his savings in a stocking, like the proverbial French peasant, it is obvious that they do not give employment. If he invests his savings, the matter is less obvious, and different cases arise.
|
||||
|
||||
One of the commonest things to do with savings is to lend them to some Government. In view of the fact that the bulk of the public expenditure of most civilized Governments consists in payment for past wars or preparation for future wars, the man who lends his money to a Government is in the same position as the bad men in Shakespeare who hire murderers. The net result of the man's economical habits is to increase the armed forces of the State to which he lends his savings. Obviously it would be better if he spent the money, even if he spent it in drink or gambling.
|
||||
|
||||
But, I shall be told, the case is quite different when savings are invested in industrial enterprises. When such enterprises succeed, and produce something useful, this may be conceded. In these days, however, no one will deny that most enterprises fail. That means that a large amount of human labor, which might have been devoted to producing something that could be enjoyed, was expended on producing machines which, when produced, lay idle and did no good to anyone. The man who invests his savings in a concern that goes bankrupt is therefore injuring others as well as himself. If he spent his money, say, in giving parties for his friends, they (we may hope) would get pleasure, and so would all those upon whom he spent money, such as the butcher, the baker, and the bootlegger. But if he spends it (let us say) upon laying down rails for surface card in some place where surface cars turn out not to be wanted, he has diverted a mass of labor into channels where it gives pleasure to no one. Nevertheless, when he becomes poor through failure of his investment he will be regarded as a victim of undeserved misfortune, whereas the gay spendthrift, who has spent his money philanthropically, will be despised as a fool and a frivolous person.
|
||||
|
||||
All this is only preliminary. I want to say, in all seriousness, that a great deal of harm is being done in the modern world by belief in the virtuousness of work, and that the road to happiness and prosperity lies in an organized diminution of work.
|
||||
|
||||
First of all: what is work? Work is of two kinds: first, altering the position of matter at or near the earth's surface relatively to other such matter; second, telling other people to do so. The first kind is unpleasant and ill paid; the second is pleasant and highly paid. The second kind is capable of indefinite extension: there are not only those who give orders, but those who give advice as to what orders should be given. Usually two opposite kinds of advice are given simultaneously by two organized bodies of men; this is called politics. The skill required for this kind of work is not knowledge of the subjects as to which advice is given, but knowledge of the art of persuasive speaking and writing, i.e. of advertising.
|
||||
|
||||
Throughout Europe, though not in America, there is a third class of men, more respected than either of the classes of workers. There are men who, through ownership of land, are able to make others pay for the privilege of being allowed to exist and to work. These landowners are idle, and I might therefore be expected to praise them. Unfortunately, their idleness is only rendered possible by the industry of others; indeed their desire for comfortable idleness is historically the source of the whole gospel of work. The last thing they have ever wished is that others should follow their example.
|
||||
|
||||
From the beginning of civilization until the Industrial Revolution, a man could, as a rule, produce by hard work little more than was required for the subsistence of himself and his family, although his wife worked at least as hard as he did, and his children added their labor as soon as they were old enough to do so. The small surplus above bare necessaries was not left to those who produced it, but was appropriated by warriors and priests. In times of famine there was no surplus; the warriors and priests, however, still secured as much as at other times, with the result that many of the workers died of hunger. This system persisted in Russia until 1917 [1], and still persists in the East; in England, in spite of the Industrial Revolution, it remained in full force throughout the Napoleonic wars, and until a hundred years ago, when the new class of manufacturers acquired power. In America, the system came to an end with the Revolution, except in the South, where it persisted until the Civil War. A system which lasted so long and ended so recently has naturally left a profound impress upon men's thoughts and opinions. Much that we take for granted about the desirability of work is derived from this system, and, being pre-industrial, is not adapted to the modern world. Modern technique has made it possible for leisure, within limits, to be not the prerogative of small privileged classes, but a right evenly distributed throughout the community. The morality of work is the morality of slaves, and the modern world has no need of slavery.
|
||||
|
||||
It is obvious that, in primitive communities, peasants, left to themselves, would not have parted with the slender surplus upon which the warriors and priests subsisted, but would have either produced less or consumed more. At first, sheer force compelled them to produce and part with the surplus. Gradually, however, it was found possible to induce many of them to accept an ethic according to which it was their duty to work hard, although part of their work went to support others in idleness. By this means the amount of compulsion required was lessened, and the expenses of government were diminished. To this day, 99 per cent of British wage-earners would be genuinely shocked if it were proposed that the King should not have a larger income than a working man. The conception of duty, speaking historically, has been a means used by the holders of power to induce others to live for the interests of their masters rather than for their own. Of course the holders of power conceal this fact from themselves by managing to believe that their interests are identical with the larger interests of humanity. Sometimes this is true; Athenian slave-owners, for instance, employed part of their leisure in making a permanent contribution to civilization which would have been impossible under a just economic system. Leisure is essential to civilization, and in former times leisure for the few was only rendered possible by the labors of the many. But their labors were valuable, not because work is good, but because leisure is good. And with modern technique it would be possible to distribute leisure justly without injury to civilization.
|
||||
|
||||
Modern technique has made it possible to diminish enormously the amount of labor required to secure the necessaries of life for everyone. This was made obvious during the war. At that time all the men in the armed forces, and all the men and women engaged in the production of munitions, all the men and women engaged in spying, war propaganda, or Government offices connected with the war, were withdrawn from productive occupations. In spite of this, the general level of well-being among unskilled wage-earners on the side of the Allies was higher than before or since. The significance of this fact was concealed by finance: borrowing made it appear as if the future was nourishing the present. But that, of course, would have been impossible; a man cannot eat a loaf of bread that does not yet exist. The war showed conclusively that, by the scientific organization of production, it is possible to keep modern populations in fair comfort on a small part of the working capacity of the modern world. If, at the end of the war, the scientific organization, which had been created in order to liberate men for fighting and munition work, had been preserved, and the hours of the week had been cut down to four, all would have been well. Instead of that the old chaos was restored, those whose work was demanded were made to work long hours, and the rest were left to starve as unemployed. Why? Because work is a duty, and a man should not receive wages in proportion to what he has produced, but in proportion to his virtue as exemplified by his industry.
|
||||
|
||||
This is the morality of the Slave State, applied in circumstances totally unlike those in which it arose. No wonder the result has been disastrous. Let us take an illustration. Suppose that, at a given moment, a certain number of people are engaged in the manufacture of pins. They make as many pins as the world needs, working (say) eight hours a day. Someone makes an invention by which the same number of men can make twice as many pins: pins are already so cheap that hardly any more will be bought at a lower price. In a sensible world, everybody concerned in the manufacturing of pins would take to working four hours instead of eight, and everything else would go on as before. But in the actual world this would be thought demoralizing. The men still work eight hours, there are too many pins, some employers go bankrupt, and half the men previously concerned in making pins are thrown out of work. There is, in the end, just as much leisure as on the other plan, but half the men are totally idle while half are still overworked. In this way, it is insured that the unavoidable leisure shall cause misery all round instead of being a universal source of happiness. Can anything more insane be imagined?
|
||||
|
||||
The idea that the poor should have leisure has always been shocking to the rich. In England, in the early nineteenth century, fifteen hours was the ordinary day's work for a man; children sometimes did as much, and very commonly did twelve hours a day. When meddlesome busybodies suggested that perhaps these hours were rather long, they were told that work kept adults from drink and children from mischief. When I was a child, shortly after urban working men had acquired the vote, certain public holidays were established by law, to the great indignation of the upper classes. I remember hearing an old Duchess say: 'What do the poor want with holidays? They ought to work.' People nowadays are less frank, but the sentiment persists, and is the source of much of our economic confusion.
|
||||
|
||||
Let us, for a moment, consider the ethics of work frankly, without superstition. Every human being, of necessity, consumes, in the course of his life, a certain amount of the produce of human labor. Assuming, as we may, that labor is on the whole disagreeable, it is unjust that a man should consume more than he produces. Of course he may provide services rather than commodities, like a medical man, for example; but he should provide something in return for his board and lodging. to this extent, the duty of work must be admitted, but to this extent only.
|
||||
|
||||
I shall not dwell upon the fact that, in all modern societies outside the USSR, many people escape even this minimum amount of work, namely all those who inherit money and all those who marry money. I do not think the fact that these people are allowed to be idle is nearly so harmful as the fact that wage-earners are expected to overwork or starve.
|
||||
|
||||
If the ordinary wage-earner worked four hours a day, there would be enough for everybody and no unemployment -- assuming a certain very moderate amount of sensible organization. This idea shocks the well-to-do, because they are convinced that the poor would not know how to use so much leisure. In America men often work long hours even when they are well off; such men, naturally, are indignant at the idea of leisure for wage-earners, except as the grim punishment of unemployment; in fact, they dislike leisure even for their sons. Oddly enough, while they wish their sons to work so hard as to have no time to be civilized, they do not mind their wives and daughters having no work at all. the snobbish admiration of uselessness, which, in an aristocratic society, extends to both sexes, is, under a plutocracy, confined to women; this, however, does not make it any more in agreement with common sense.
|
||||
|
||||
The wise use of leisure, it must be conceded, is a product of civilization and education. A man who has worked long hours all his life will become bored if he becomes suddenly idle. But without a considerable amount of leisure a man is cut off from many of the best things. There is no longer any reason why the bulk of the population should suffer this deprivation; only a foolish asceticism, usually vicarious, makes us continue to insist on work in excessive quantities now that the need no longer exists.
|
||||
|
||||
In the new creed which controls the government of Russia, while there is much that is very different from the traditional teaching of the West, there are some things that are quite unchanged. The attitude of the governing classes, and especially of those who conduct educational propaganda, on the subject of the dignity of labor, is almost exactly that which the governing classes of the world have always preached to what were called the 'honest poor'. Industry, sobriety, willingness to work long hours for distant advantages, even submissiveness to authority, all these reappear; moreover authority still represents the will of the Ruler of the Universe, Who, however, is now called by a new name, Dialectical Materialism.
|
||||
|
||||
The victory of the proletariat in Russia has some points in common with the victory of the feminists in some other countries. For ages, men had conceded the superior saintliness of women, and had consoled women for their inferiority by maintaining that saintliness is more desirable than power. At last the feminists decided that they would have both, since the pioneers among them believed all that the men had told them about the desirability of virtue, but not what they had told them about the worthlessness of political power. A similar thing has happened in Russia as regards manual work. For ages, the rich and their sycophants have written in praise of 'honest toil', have praised the simple life, have professed a religion which teaches that the poor are much more likely to go to heaven than the rich, and in general have tried to make manual workers believe that there is some special nobility about altering the position of matter in space, just as men tried to make women believe that they derived some special nobility from their sexual enslavement. In Russia, all this teaching about the excellence of manual work has been taken seriously, with the result that the manual worker is more honored than anyone else. What are, in essence, revivalist appeals are made, but not for the old purposes: they are made to secure shock workers for special tasks. Manual work is the ideal which is held before the young, and is the basis of all ethical teaching.
|
||||
|
||||
For the present, possibly, this is all to the good. A large country, full of natural resources, awaits development, and has has to be developed with very little use of credit. In these circumstances, hard work is necessary, and is likely to bring a great reward. But what will happen when the point has been reached where everybody could be comfortable without working long hours?
|
||||
|
||||
In the West, we have various ways of dealing with this problem. We have no attempt at economic justice, so that a large proportion of the total produce goes to a small minority of the population, many of whom do no work at all. Owing to the absence of any central control over production, we produce hosts of things that are not wanted. We keep a large percentage of the working population idle, because we can dispense with their labor by making the others overwork. When all these methods prove inadequate, we have a war: we cause a number of people to manufacture high explosives, and a number of others to explode them, as if we were children who had just discovered fireworks. By a combination of all these devices we manage, though with difficulty, to keep alive the notion that a great deal of severe manual work must be the lot of the average man.
|
||||
|
||||
In Russia, owing to more economic justice and central control over production, the problem will have to be differently solved. the rational solution would be, as soon as the necessaries and elementary comforts can be provided for all, to reduce the hours of labor gradually, allowing a popular vote to decide, at each stage, whether more leisure or more goods were to be preferred. But, having taught the supreme virtue of hard work, it is difficult to see how the authorities can aim at a paradise in which there will be much leisure and little work. It seems more likely that they will find continually fresh schemes, by which present leisure is to be sacrificed to future productivity. I read recently of an ingenious plan put forward by Russian engineers, for making the White Sea and the northern coasts of Siberia warm, by putting a dam across the Kara Sea. An admirable project, but liable to postpone proletarian comfort for a generation, while the nobility of toil is being displayed amid the ice-fields and snowstorms of the Arctic Ocean. This sort of thing, if it happens, will be the result of regarding the virtue of hard work as an end in itself, rather than as a means to a state of affairs in which it is no longer needed.
|
||||
|
||||
The fact is that moving matter about, while a certain amount of it is necessary to our existence, is emphatically not one of the ends of human life. If it were, we should have to consider every navvy superior to Shakespeare. We have been misled in this matter by two causes. One is the necessity of keeping the poor contented, which has led the rich, for thousands of years, to preach the dignity of labor, while taking care themselves to remain undignified in this respect. The other is the new pleasure in mechanism, which makes us delight in the astonishingly clever changes that we can produce on the earth's surface. Neither of these motives makes any great appeal to the actual worker. If you ask him what he thinks the best part of his life, he is not likely to say: 'I enjoy manual work because it makes me feel that I am fulfilling man's noblest task, and because I like to think how much man can transform his planet. It is true that my body demands periods of rest, which I have to fill in as best I may, but I am never so happy as when the morning comes and I can return to the toil from which my contentment springs.' I have never heard working men say this sort of thing. They consider work, as it should be considered, a necessary means to a livelihood, and it is from their leisure that they derive whatever happiness they may enjoy.
|
||||
|
||||
It will be said that, while a little leisure is pleasant, men would not know how to fill their days if they had only four hours of work out of the twenty-four. In so far as this is true in the modern world, it is a condemnation of our civilization; it would not have been true at any earlier period. There was formerly a capacity for light-heartedness and play which has been to some extent inhibited by the cult of efficiency. The modern man thinks that everything ought to be done for the sake of something else, and never for its own sake. Serious-minded persons, for example, are continually condemning the habit of going to the cinema, and telling us that it leads the young into crime. But all the work that goes to producing a cinema is respectable, because it is work, and because it brings a money profit. The notion that the desirable activities are those that bring a profit has made everything topsy-turvy. The butcher who provides you with meat and the baker who provides you with bread are praiseworthy, because they are making money; but when you enjoy the food they have provided, you are merely frivolous, unless you eat only to get strength for your work. Broadly speaking, it is held that getting money is good and spending money is bad. Seeing that they are two sides of one transaction, this is absurd; one might as well maintain that keys are good, but keyholes are bad. Whatever merit there may be in the production of goods must be entirely derivative from the advantage to be obtained by consuming them. The individual, in our society, works for profit; but the social purpose of his work lies in the consumption of what he produces. It is this divorce between the individual and the social purpose of production that makes it so difficult for men to think clearly in a world in which profit-making is the incentive to industry. We think too much of production, and too little of consumption. One result is that we attach too little importance to enjoyment and simple happiness, and that we do not judge production by the pleasure that it gives to the consumer.
|
||||
|
||||
When I suggest that working hours should be reduced to four, I am not meaning to imply that all the remaining time should necessarily be spent in pure frivolity. I mean that four hours' work a day should entitle a man to the necessities and elementary comforts of life, and that the rest of his time should be his to use as he might see fit. It is an essential part of any such social system that education should be carried further than it usually is at present, and should aim, in part, at providing tastes which would enable a man to use leisure intelligently. I am not thinking mainly of the sort of things that would be considered 'highbrow'. Peasant dances have died out except in remote rural areas, but the impulses which caused them to be cultivated must still exist in human nature. The pleasures of urban populations have become mainly passive: seeing cinemas, watching football matches, listening to the radio, and so on. This results from the fact that their active energies are fully taken up with work; if they had more leisure, they would again enjoy pleasures in which they took an active part.
|
||||
|
||||
In the past, there was a small leisure class and a larger working class. The leisure class enjoyed advantages for which there was no basis in social justice; this necessarily made it oppressive, limited its sympathies, and caused it to invent theories by which to justify its privileges. These facts greatly diminished its excellence, but in spite of this drawback it contributed nearly the whole of what we call civilization. It cultivated the arts and discovered the sciences; it wrote the books, invented the philosophies, and refined social relations. Even the liberation of the oppressed has usually been inaugurated from above. Without the leisure class, mankind would never have emerged from barbarism.
|
||||
|
||||
The method of a leisure class without duties was, however, extraordinarily wasteful. None of the members of the class had to be taught to be industrious, and the class as a whole was not exceptionally intelligent. The class might produce one Darwin, but against him had to be set tens of thousands of country gentlemen who never thought of anything more intelligent than fox-hunting and punishing poachers. At present, the universities are supposed to provide, in a more systematic way, what the leisure class provided accidentally and as a by-product. This is a great improvement, but it has certain drawbacks. University life is so different from life in the world at large that men who live in academic milieu tend to be unaware of the preoccupations and problems of ordinary men and women; moreover their ways of expressing themselves are usually such as to rob their opinions of the influence that they ought to have upon the general public. Another disadvantage is that in universities studies are organized, and the man who thinks of some original line of research is likely to be discouraged. Academic institutions, therefore, useful as they are, are not adequate guardians of the interests of civilization in a world where everyone outside their walls is too busy for unutilitarian pursuits.
|
||||
|
||||
In a world where no one is compelled to work more than four hours a day, every person possessed of scientific curiosity will be able to indulge it, and every painter will be able to paint without starving, however excellent his pictures may be. Young writers will not be obliged to draw attention to themselves by sensational pot-boilers, with a view to acquiring the economic independence needed for monumental works, for which, when the time at last comes, they will have lost the taste and capacity. Men who, in their professional work, have become interested in some phase of economics or government, will be able to develop their ideas without the academic detachment that makes the work of university economists often seem lacking in reality. Medical men will have the time to learn about the progress of medicine, teachers will not be exasperatedly struggling to teach by routine methods things which they learnt in their youth, which may, in the interval, have been proved to be untrue.
|
||||
|
||||
Above all, there will be happiness and joy of life, instead of frayed nerves, weariness, and dyspepsia. The work exacted will be enough to make leisure delightful, but not enough to produce exhaustion. Since men will not be tired in their spare time, they will not demand only such amusements as are passive and vapid. At least one per cent will probably devote the time not spent in professional work to pursuits of some public importance, and, since they will not depend upon these pursuits for their livelihood, their originality will be unhampered, and there will be no need to conform to the standards set by elderly pundits. But it is not only in these exceptional cases that the advantages of leisure will appear. Ordinary men and women, having the opportunity of a happy life, will become more kindly and less persecuting and less inclined to view others with suspicion. The taste for war will die out, partly for this reason, and partly because it will involve long and severe work for all. Good nature is, of all moral qualities, the one that the world needs most, and good nature is the result of ease and security, not of a life of arduous struggle. Modern methods of production have given us the possibility of ease and security for all; we have chosen, instead, to have overwork for some and starvation for others. Hitherto we have continued to be as energetic as we were before there were machines; in this we have been foolish, but there is no reason to go on being foolish forever.
|
||||
|
||||
[1] Since then, members of the Communist Party have succeeded to this privilege of the warriors and priests.
|
31
node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/wrap.js
generated
vendored
Normal file
31
node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/wrap.js
generated
vendored
Normal file
|
@ -0,0 +1,31 @@
|
|||
var assert = require('assert');
|
||||
var wordwrap = require('wordwrap');
|
||||
|
||||
var fs = require('fs');
|
||||
var idleness = fs.readFileSync(__dirname + '/idleness.txt', 'utf8');
|
||||
|
||||
exports.stop80 = function () {
|
||||
var lines = wordwrap(80)(idleness).split(/\n/);
|
||||
var words = idleness.split(/\s+/);
|
||||
|
||||
lines.forEach(function (line) {
|
||||
assert.ok(line.length <= 80, 'line > 80 columns');
|
||||
var chunks = line.match(/\S/) ? line.split(/\s+/) : [];
|
||||
assert.deepEqual(chunks, words.splice(0, chunks.length));
|
||||
});
|
||||
};
|
||||
|
||||
exports.start20stop60 = function () {
|
||||
var lines = wordwrap(20, 100)(idleness).split(/\n/);
|
||||
var words = idleness.split(/\s+/);
|
||||
|
||||
lines.forEach(function (line) {
|
||||
assert.ok(line.length <= 100, 'line > 100 columns');
|
||||
var chunks = line
|
||||
.split(/\s+/)
|
||||
.filter(function (x) { return x.match(/\S/) })
|
||||
;
|
||||
assert.deepEqual(chunks, words.splice(0, chunks.length));
|
||||
assert.deepEqual(line.slice(0, 20), new Array(20 + 1).join(' '));
|
||||
});
|
||||
};
|
|
@ -0,0 +1,53 @@
|
|||
{
|
||||
"name": "optimist",
|
||||
"version": "0.3.5",
|
||||
"description": "Light-weight option parsing with an argv hash. No optstrings attached.",
|
||||
"main": "./index.js",
|
||||
"directories": {
|
||||
"lib": ".",
|
||||
"test": "test",
|
||||
"example": "example"
|
||||
},
|
||||
"dependencies": {
|
||||
"wordwrap": "~0.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"hashish": "~0.0.4",
|
||||
"tap": "~0.2.4"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "tap ./test/*.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/substack/node-optimist.git"
|
||||
},
|
||||
"keywords": [
|
||||
"argument",
|
||||
"args",
|
||||
"option",
|
||||
"parser",
|
||||
"parsing",
|
||||
"cli",
|
||||
"command"
|
||||
],
|
||||
"author": {
|
||||
"name": "James Halliday",
|
||||
"email": "mail@substack.net",
|
||||
"url": "http://substack.net"
|
||||
},
|
||||
"license": "MIT/X11",
|
||||
"engine": {
|
||||
"node": ">=0.4"
|
||||
},
|
||||
"_id": "optimist@0.3.5",
|
||||
"optionalDependencies": {},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
},
|
||||
"_engineSupported": true,
|
||||
"_npmVersion": "1.1.4",
|
||||
"_nodeVersion": "v0.6.19",
|
||||
"_defaultsLoaded": true,
|
||||
"_from": "optimist@~0.3"
|
||||
}
|
|
@ -0,0 +1,71 @@
|
|||
var spawn = require('child_process').spawn;
|
||||
var test = require('tap').test;
|
||||
|
||||
test('dotSlashEmpty', testCmd('./bin.js', []));
|
||||
|
||||
test('dotSlashArgs', testCmd('./bin.js', [ 'a', 'b', 'c' ]));
|
||||
|
||||
test('nodeEmpty', testCmd('node bin.js', []));
|
||||
|
||||
test('nodeArgs', testCmd('node bin.js', [ 'x', 'y', 'z' ]));
|
||||
|
||||
test('whichNodeEmpty', function (t) {
|
||||
var which = spawn('which', ['node']);
|
||||
|
||||
which.stdout.on('data', function (buf) {
|
||||
t.test(
|
||||
testCmd(buf.toString().trim() + ' bin.js', [])
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
which.stderr.on('data', function (err) {
|
||||
assert.error(err);
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
test('whichNodeArgs', function (t) {
|
||||
var which = spawn('which', ['node']);
|
||||
|
||||
which.stdout.on('data', function (buf) {
|
||||
t.test(
|
||||
testCmd(buf.toString().trim() + ' bin.js', [ 'q', 'r' ])
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
which.stderr.on('data', function (err) {
|
||||
t.error(err);
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
function testCmd (cmd, args) {
|
||||
|
||||
return function (t) {
|
||||
var to = setTimeout(function () {
|
||||
assert.fail('Never got stdout data.')
|
||||
}, 5000);
|
||||
|
||||
var oldDir = process.cwd();
|
||||
process.chdir(__dirname + '/_');
|
||||
|
||||
var cmds = cmd.split(' ');
|
||||
|
||||
var bin = spawn(cmds[0], cmds.slice(1).concat(args.map(String)));
|
||||
process.chdir(oldDir);
|
||||
|
||||
bin.stderr.on('data', function (err) {
|
||||
t.error(err);
|
||||
t.end();
|
||||
});
|
||||
|
||||
bin.stdout.on('data', function (buf) {
|
||||
clearTimeout(to);
|
||||
var _ = JSON.parse(buf.toString());
|
||||
t.same(_.map(String), args.map(String));
|
||||
t.end();
|
||||
});
|
||||
};
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
#!/usr/bin/env node
|
||||
console.log(JSON.stringify(process.argv));
|
|
@ -0,0 +1,3 @@
|
|||
#!/usr/bin/env node
|
||||
var argv = require('../../index').argv
|
||||
console.log(JSON.stringify(argv._));
|
|
@ -0,0 +1,433 @@
|
|||
var optimist = require('../index');
|
||||
var path = require('path');
|
||||
var test = require('tap').test;
|
||||
|
||||
var $0 = 'node ./' + path.relative(process.cwd(), __filename);
|
||||
|
||||
test('short boolean', function (t) {
|
||||
var parse = optimist.parse([ '-b' ]);
|
||||
t.same(parse, { b : true, _ : [], $0 : $0 });
|
||||
t.same(typeof parse.b, 'boolean');
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('long boolean', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '--bool' ]),
|
||||
{ bool : true, _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('bare', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ 'foo', 'bar', 'baz' ]),
|
||||
{ _ : [ 'foo', 'bar', 'baz' ], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('short group', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '-cats' ]),
|
||||
{ c : true, a : true, t : true, s : true, _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('short group next', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '-cats', 'meow' ]),
|
||||
{ c : true, a : true, t : true, s : 'meow', _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('short capture', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '-h', 'localhost' ]),
|
||||
{ h : 'localhost', _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('short captures', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '-h', 'localhost', '-p', '555' ]),
|
||||
{ h : 'localhost', p : 555, _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('long capture sp', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '--pow', 'xixxle' ]),
|
||||
{ pow : 'xixxle', _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('long capture eq', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '--pow=xixxle' ]),
|
||||
{ pow : 'xixxle', _ : [], $0 : $0 }
|
||||
);
|
||||
t.end()
|
||||
});
|
||||
|
||||
test('long captures sp', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '--host', 'localhost', '--port', '555' ]),
|
||||
{ host : 'localhost', port : 555, _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('long captures eq', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '--host=localhost', '--port=555' ]),
|
||||
{ host : 'localhost', port : 555, _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('mixed short bool and capture', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]),
|
||||
{
|
||||
f : true, p : 555, h : 'localhost',
|
||||
_ : [ 'script.js' ], $0 : $0,
|
||||
}
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('short and long', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]),
|
||||
{
|
||||
f : true, p : 555, h : 'localhost',
|
||||
_ : [ 'script.js' ], $0 : $0,
|
||||
}
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('no', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '--no-moo' ]),
|
||||
{ moo : false, _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('multi', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]),
|
||||
{ v : ['a','b','c'], _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('comprehensive', function (t) {
|
||||
t.same(
|
||||
optimist.parse([
|
||||
'--name=meowmers', 'bare', '-cats', 'woo',
|
||||
'-h', 'awesome', '--multi=quux',
|
||||
'--key', 'value',
|
||||
'-b', '--bool', '--no-meep', '--multi=baz',
|
||||
'--', '--not-a-flag', 'eek'
|
||||
]),
|
||||
{
|
||||
c : true,
|
||||
a : true,
|
||||
t : true,
|
||||
s : 'woo',
|
||||
h : 'awesome',
|
||||
b : true,
|
||||
bool : true,
|
||||
key : 'value',
|
||||
multi : [ 'quux', 'baz' ],
|
||||
meep : false,
|
||||
name : 'meowmers',
|
||||
_ : [ 'bare', '--not-a-flag', 'eek' ],
|
||||
$0 : $0
|
||||
}
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('nums', function (t) {
|
||||
var argv = optimist.parse([
|
||||
'-x', '1234',
|
||||
'-y', '5.67',
|
||||
'-z', '1e7',
|
||||
'-w', '10f',
|
||||
'--hex', '0xdeadbeef',
|
||||
'789',
|
||||
]);
|
||||
t.same(argv, {
|
||||
x : 1234,
|
||||
y : 5.67,
|
||||
z : 1e7,
|
||||
w : '10f',
|
||||
hex : 0xdeadbeef,
|
||||
_ : [ 789 ],
|
||||
$0 : $0
|
||||
});
|
||||
t.same(typeof argv.x, 'number');
|
||||
t.same(typeof argv.y, 'number');
|
||||
t.same(typeof argv.z, 'number');
|
||||
t.same(typeof argv.w, 'string');
|
||||
t.same(typeof argv.hex, 'number');
|
||||
t.same(typeof argv._[0], 'number');
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('flag boolean', function (t) {
|
||||
var parse = optimist([ '-t', 'moo' ]).boolean(['t']).argv;
|
||||
t.same(parse, { t : true, _ : [ 'moo' ], $0 : $0 });
|
||||
t.same(typeof parse.t, 'boolean');
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('flag boolean value', function (t) {
|
||||
var parse = optimist(['--verbose', 'false', 'moo', '-t', 'true'])
|
||||
.boolean(['t', 'verbose']).default('verbose', true).argv;
|
||||
|
||||
t.same(parse, {
|
||||
verbose: false,
|
||||
t: true,
|
||||
_: ['moo'],
|
||||
$0 : $0
|
||||
});
|
||||
|
||||
t.same(typeof parse.verbose, 'boolean');
|
||||
t.same(typeof parse.t, 'boolean');
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('flag boolean default false', function (t) {
|
||||
var parse = optimist(['moo'])
|
||||
.boolean(['t', 'verbose'])
|
||||
.default('verbose', false)
|
||||
.default('t', false).argv;
|
||||
|
||||
t.same(parse, {
|
||||
verbose: false,
|
||||
t: false,
|
||||
_: ['moo'],
|
||||
$0 : $0
|
||||
});
|
||||
|
||||
t.same(typeof parse.verbose, 'boolean');
|
||||
t.same(typeof parse.t, 'boolean');
|
||||
t.end();
|
||||
|
||||
});
|
||||
|
||||
test('boolean groups', function (t) {
|
||||
var parse = optimist([ '-x', '-z', 'one', 'two', 'three' ])
|
||||
.boolean(['x','y','z']).argv;
|
||||
|
||||
t.same(parse, {
|
||||
x : true,
|
||||
y : false,
|
||||
z : true,
|
||||
_ : [ 'one', 'two', 'three' ],
|
||||
$0 : $0
|
||||
});
|
||||
|
||||
t.same(typeof parse.x, 'boolean');
|
||||
t.same(typeof parse.y, 'boolean');
|
||||
t.same(typeof parse.z, 'boolean');
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('strings' , function (t) {
|
||||
var s = optimist([ '-s', '0001234' ]).string('s').argv.s;
|
||||
t.same(s, '0001234');
|
||||
t.same(typeof s, 'string');
|
||||
|
||||
var x = optimist([ '-x', '56' ]).string('x').argv.x;
|
||||
t.same(x, '56');
|
||||
t.same(typeof x, 'string');
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('stringArgs', function (t) {
|
||||
var s = optimist([ ' ', ' ' ]).string('_').argv._;
|
||||
t.same(s.length, 2);
|
||||
t.same(typeof s[0], 'string');
|
||||
t.same(s[0], ' ');
|
||||
t.same(typeof s[1], 'string');
|
||||
t.same(s[1], ' ');
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('slashBreak', function (t) {
|
||||
t.same(
|
||||
optimist.parse([ '-I/foo/bar/baz' ]),
|
||||
{ I : '/foo/bar/baz', _ : [], $0 : $0 }
|
||||
);
|
||||
t.same(
|
||||
optimist.parse([ '-xyz/foo/bar/baz' ]),
|
||||
{ x : true, y : true, z : '/foo/bar/baz', _ : [], $0 : $0 }
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('alias', function (t) {
|
||||
var argv = optimist([ '-f', '11', '--zoom', '55' ])
|
||||
.alias('z', 'zoom')
|
||||
.argv
|
||||
;
|
||||
t.equal(argv.zoom, 55);
|
||||
t.equal(argv.z, argv.zoom);
|
||||
t.equal(argv.f, 11);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('multiAlias', function (t) {
|
||||
var argv = optimist([ '-f', '11', '--zoom', '55' ])
|
||||
.alias('z', [ 'zm', 'zoom' ])
|
||||
.argv
|
||||
;
|
||||
t.equal(argv.zoom, 55);
|
||||
t.equal(argv.z, argv.zoom);
|
||||
t.equal(argv.z, argv.zm);
|
||||
t.equal(argv.f, 11);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('boolean default true', function (t) {
|
||||
var argv = optimist.options({
|
||||
sometrue: {
|
||||
boolean: true,
|
||||
default: true
|
||||
}
|
||||
}).argv;
|
||||
|
||||
t.equal(argv.sometrue, true);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('boolean default false', function (t) {
|
||||
var argv = optimist.options({
|
||||
somefalse: {
|
||||
boolean: true,
|
||||
default: false
|
||||
}
|
||||
}).argv;
|
||||
|
||||
t.equal(argv.somefalse, false);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('nested dotted objects', function (t) {
|
||||
var argv = optimist([
|
||||
'--foo.bar', '3', '--foo.baz', '4',
|
||||
'--foo.quux.quibble', '5', '--foo.quux.o_O',
|
||||
'--beep.boop'
|
||||
]).argv;
|
||||
|
||||
t.same(argv.foo, {
|
||||
bar : 3,
|
||||
baz : 4,
|
||||
quux : {
|
||||
quibble : 5,
|
||||
o_O : true
|
||||
},
|
||||
});
|
||||
t.same(argv.beep, { boop : true });
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('boolean and alias with chainable api', function (t) {
|
||||
var aliased = [ '-h', 'derp' ];
|
||||
var regular = [ '--herp', 'derp' ];
|
||||
var opts = {
|
||||
herp: { alias: 'h', boolean: true }
|
||||
};
|
||||
var aliasedArgv = optimist(aliased)
|
||||
.boolean('herp')
|
||||
.alias('h', 'herp')
|
||||
.argv;
|
||||
var propertyArgv = optimist(regular)
|
||||
.boolean('herp')
|
||||
.alias('h', 'herp')
|
||||
.argv;
|
||||
var expected = {
|
||||
herp: true,
|
||||
h: true,
|
||||
'_': [ 'derp' ],
|
||||
'$0': $0,
|
||||
};
|
||||
|
||||
t.same(aliasedArgv, expected);
|
||||
t.same(propertyArgv, expected);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('boolean and alias with options hash', function (t) {
|
||||
var aliased = [ '-h', 'derp' ];
|
||||
var regular = [ '--herp', 'derp' ];
|
||||
var opts = {
|
||||
herp: { alias: 'h', boolean: true }
|
||||
};
|
||||
var aliasedArgv = optimist(aliased)
|
||||
.options(opts)
|
||||
.argv;
|
||||
var propertyArgv = optimist(regular).options(opts).argv;
|
||||
var expected = {
|
||||
herp: true,
|
||||
h: true,
|
||||
'_': [ 'derp' ],
|
||||
'$0': $0,
|
||||
};
|
||||
|
||||
t.same(aliasedArgv, expected);
|
||||
t.same(propertyArgv, expected);
|
||||
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('boolean and alias using explicit true', function (t) {
|
||||
var aliased = [ '-h', 'true' ];
|
||||
var regular = [ '--herp', 'true' ];
|
||||
var opts = {
|
||||
herp: { alias: 'h', boolean: true }
|
||||
};
|
||||
var aliasedArgv = optimist(aliased)
|
||||
.boolean('h')
|
||||
.alias('h', 'herp')
|
||||
.argv;
|
||||
var propertyArgv = optimist(regular)
|
||||
.boolean('h')
|
||||
.alias('h', 'herp')
|
||||
.argv;
|
||||
var expected = {
|
||||
herp: true,
|
||||
h: true,
|
||||
'_': [ ],
|
||||
'$0': $0,
|
||||
};
|
||||
|
||||
t.same(aliasedArgv, expected);
|
||||
t.same(propertyArgv, expected);
|
||||
t.end();
|
||||
});
|
||||
|
||||
// regression, see https://github.com/substack/node-optimist/issues/71
|
||||
test('boolean and --x=true', function(t) {
|
||||
var parsed = optimist(['--boool', '--other=true']).boolean('boool').argv;
|
||||
|
||||
t.same(parsed.boool, true);
|
||||
t.same(parsed.other, 'true');
|
||||
|
||||
parsed = optimist(['--boool', '--other=false']).boolean('boool').argv;
|
||||
|
||||
t.same(parsed.boool, true);
|
||||
t.same(parsed.other, 'false');
|
||||
t.end();
|
||||
});
|
|
@ -0,0 +1,292 @@
|
|||
var Hash = require('hashish');
|
||||
var optimist = require('../index');
|
||||
var test = require('tap').test;
|
||||
|
||||
test('usageFail', function (t) {
|
||||
var r = checkUsage(function () {
|
||||
return optimist('-x 10 -z 20'.split(' '))
|
||||
.usage('Usage: $0 -x NUM -y NUM')
|
||||
.demand(['x','y'])
|
||||
.argv;
|
||||
});
|
||||
t.same(
|
||||
r.result,
|
||||
{ x : 10, z : 20, _ : [], $0 : './usage' }
|
||||
);
|
||||
|
||||
t.same(
|
||||
r.errors.join('\n').split(/\n+/),
|
||||
[
|
||||
'Usage: ./usage -x NUM -y NUM',
|
||||
'Options:',
|
||||
' -x [required]',
|
||||
' -y [required]',
|
||||
'Missing required arguments: y',
|
||||
]
|
||||
);
|
||||
t.same(r.logs, []);
|
||||
t.ok(r.exit);
|
||||
t.end();
|
||||
});
|
||||
|
||||
|
||||
test('usagePass', function (t) {
|
||||
var r = checkUsage(function () {
|
||||
return optimist('-x 10 -y 20'.split(' '))
|
||||
.usage('Usage: $0 -x NUM -y NUM')
|
||||
.demand(['x','y'])
|
||||
.argv;
|
||||
});
|
||||
t.same(r, {
|
||||
result : { x : 10, y : 20, _ : [], $0 : './usage' },
|
||||
errors : [],
|
||||
logs : [],
|
||||
exit : false,
|
||||
});
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('checkPass', function (t) {
|
||||
var r = checkUsage(function () {
|
||||
return optimist('-x 10 -y 20'.split(' '))
|
||||
.usage('Usage: $0 -x NUM -y NUM')
|
||||
.check(function (argv) {
|
||||
if (!('x' in argv)) throw 'You forgot about -x';
|
||||
if (!('y' in argv)) throw 'You forgot about -y';
|
||||
})
|
||||
.argv;
|
||||
});
|
||||
t.same(r, {
|
||||
result : { x : 10, y : 20, _ : [], $0 : './usage' },
|
||||
errors : [],
|
||||
logs : [],
|
||||
exit : false,
|
||||
});
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('checkFail', function (t) {
|
||||
var r = checkUsage(function () {
|
||||
return optimist('-x 10 -z 20'.split(' '))
|
||||
.usage('Usage: $0 -x NUM -y NUM')
|
||||
.check(function (argv) {
|
||||
if (!('x' in argv)) throw 'You forgot about -x';
|
||||
if (!('y' in argv)) throw 'You forgot about -y';
|
||||
})
|
||||
.argv;
|
||||
});
|
||||
|
||||
t.same(
|
||||
r.result,
|
||||
{ x : 10, z : 20, _ : [], $0 : './usage' }
|
||||
);
|
||||
|
||||
t.same(
|
||||
r.errors.join('\n').split(/\n+/),
|
||||
[
|
||||
'Usage: ./usage -x NUM -y NUM',
|
||||
'You forgot about -y'
|
||||
]
|
||||
);
|
||||
|
||||
t.same(r.logs, []);
|
||||
t.ok(r.exit);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('checkCondPass', function (t) {
|
||||
function checker (argv) {
|
||||
return 'x' in argv && 'y' in argv;
|
||||
}
|
||||
|
||||
var r = checkUsage(function () {
|
||||
return optimist('-x 10 -y 20'.split(' '))
|
||||
.usage('Usage: $0 -x NUM -y NUM')
|
||||
.check(checker)
|
||||
.argv;
|
||||
});
|
||||
t.same(r, {
|
||||
result : { x : 10, y : 20, _ : [], $0 : './usage' },
|
||||
errors : [],
|
||||
logs : [],
|
||||
exit : false,
|
||||
});
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('checkCondFail', function (t) {
|
||||
function checker (argv) {
|
||||
return 'x' in argv && 'y' in argv;
|
||||
}
|
||||
|
||||
var r = checkUsage(function () {
|
||||
return optimist('-x 10 -z 20'.split(' '))
|
||||
.usage('Usage: $0 -x NUM -y NUM')
|
||||
.check(checker)
|
||||
.argv;
|
||||
});
|
||||
|
||||
t.same(
|
||||
r.result,
|
||||
{ x : 10, z : 20, _ : [], $0 : './usage' }
|
||||
);
|
||||
|
||||
t.same(
|
||||
r.errors.join('\n').split(/\n+/).join('\n'),
|
||||
'Usage: ./usage -x NUM -y NUM\n'
|
||||
+ 'Argument check failed: ' + checker.toString()
|
||||
);
|
||||
|
||||
t.same(r.logs, []);
|
||||
t.ok(r.exit);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('countPass', function (t) {
|
||||
var r = checkUsage(function () {
|
||||
return optimist('1 2 3 --moo'.split(' '))
|
||||
.usage('Usage: $0 [x] [y] [z] {OPTIONS}')
|
||||
.demand(3)
|
||||
.argv;
|
||||
});
|
||||
t.same(r, {
|
||||
result : { _ : [ '1', '2', '3' ], moo : true, $0 : './usage' },
|
||||
errors : [],
|
||||
logs : [],
|
||||
exit : false,
|
||||
});
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('countFail', function (t) {
|
||||
var r = checkUsage(function () {
|
||||
return optimist('1 2 --moo'.split(' '))
|
||||
.usage('Usage: $0 [x] [y] [z] {OPTIONS}')
|
||||
.demand(3)
|
||||
.argv;
|
||||
});
|
||||
t.same(
|
||||
r.result,
|
||||
{ _ : [ '1', '2' ], moo : true, $0 : './usage' }
|
||||
);
|
||||
|
||||
t.same(
|
||||
r.errors.join('\n').split(/\n+/),
|
||||
[
|
||||
'Usage: ./usage [x] [y] [z] {OPTIONS}',
|
||||
'Not enough non-option arguments: got 2, need at least 3',
|
||||
]
|
||||
);
|
||||
|
||||
t.same(r.logs, []);
|
||||
t.ok(r.exit);
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('defaultSingles', function (t) {
|
||||
var r = checkUsage(function () {
|
||||
return optimist('--foo 50 --baz 70 --powsy'.split(' '))
|
||||
.default('foo', 5)
|
||||
.default('bar', 6)
|
||||
.default('baz', 7)
|
||||
.argv
|
||||
;
|
||||
});
|
||||
t.same(r.result, {
|
||||
foo : '50',
|
||||
bar : 6,
|
||||
baz : '70',
|
||||
powsy : true,
|
||||
_ : [],
|
||||
$0 : './usage',
|
||||
});
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('defaultAliases', function (t) {
|
||||
var r = checkUsage(function () {
|
||||
return optimist('')
|
||||
.alias('f', 'foo')
|
||||
.default('f', 5)
|
||||
.argv
|
||||
;
|
||||
});
|
||||
t.same(r.result, {
|
||||
f : '5',
|
||||
foo : '5',
|
||||
_ : [],
|
||||
$0 : './usage',
|
||||
});
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('defaultHash', function (t) {
|
||||
var r = checkUsage(function () {
|
||||
return optimist('--foo 50 --baz 70'.split(' '))
|
||||
.default({ foo : 10, bar : 20, quux : 30 })
|
||||
.argv
|
||||
;
|
||||
});
|
||||
t.same(r.result, {
|
||||
_ : [],
|
||||
$0 : './usage',
|
||||
foo : 50,
|
||||
baz : 70,
|
||||
bar : 20,
|
||||
quux : 30,
|
||||
});
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('rebase', function (t) {
|
||||
t.equal(
|
||||
optimist.rebase('/home/substack', '/home/substack/foo/bar/baz'),
|
||||
'./foo/bar/baz'
|
||||
);
|
||||
t.equal(
|
||||
optimist.rebase('/home/substack/foo/bar/baz', '/home/substack'),
|
||||
'../../..'
|
||||
);
|
||||
t.equal(
|
||||
optimist.rebase('/home/substack/foo', '/home/substack/pow/zoom.txt'),
|
||||
'../pow/zoom.txt'
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
|
||||
function checkUsage (f) {
|
||||
|
||||
var exit = false;
|
||||
|
||||
process._exit = process.exit;
|
||||
process._env = process.env;
|
||||
process._argv = process.argv;
|
||||
|
||||
process.exit = function (t) { exit = true };
|
||||
process.env = Hash.merge(process.env, { _ : 'node' });
|
||||
process.argv = [ './usage' ];
|
||||
|
||||
var errors = [];
|
||||
var logs = [];
|
||||
|
||||
console._error = console.error;
|
||||
console.error = function (msg) { errors.push(msg) };
|
||||
console._log = console.log;
|
||||
console.log = function (msg) { logs.push(msg) };
|
||||
|
||||
var result = f();
|
||||
|
||||
process.exit = process._exit;
|
||||
process.env = process._env;
|
||||
process.argv = process._argv;
|
||||
|
||||
console.error = console._error;
|
||||
console.log = console._log;
|
||||
|
||||
return {
|
||||
errors : errors,
|
||||
logs : logs,
|
||||
exit : exit,
|
||||
result : result,
|
||||
};
|
||||
};
|
|
@ -0,0 +1 @@
|
|||
console.dir(require('./').argv);
|
|
@ -0,0 +1,4 @@
|
|||
.DS_Store
|
||||
.tmp*~
|
||||
*.local.*
|
||||
.pinf-*
|
|
@ -0,0 +1,981 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
|
||||
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
||||
lang="en" xml:lang="en">
|
||||
<head>
|
||||
<title>UglifyJS – a JavaScript parser/compressor/beautifier</title>
|
||||
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
|
||||
<meta name="generator" content="Org-mode"/>
|
||||
<meta name="generated" content="2011-12-09 14:59:08 EET"/>
|
||||
<meta name="author" content="Mihai Bazon"/>
|
||||
<meta name="description" content="a JavaScript parser/compressor/beautifier in JavaScript"/>
|
||||
<meta name="keywords" content="javascript, js, parser, compiler, compressor, mangle, minify, minifier"/>
|
||||
<style type="text/css">
|
||||
<!--/*--><![CDATA[/*><!--*/
|
||||
html { font-family: Times, serif; font-size: 12pt; }
|
||||
.title { text-align: center; }
|
||||
.todo { color: red; }
|
||||
.done { color: green; }
|
||||
.tag { background-color: #add8e6; font-weight:normal }
|
||||
.target { }
|
||||
.timestamp { color: #bebebe; }
|
||||
.timestamp-kwd { color: #5f9ea0; }
|
||||
.right {margin-left:auto; margin-right:0px; text-align:right;}
|
||||
.left {margin-left:0px; margin-right:auto; text-align:left;}
|
||||
.center {margin-left:auto; margin-right:auto; text-align:center;}
|
||||
p.verse { margin-left: 3% }
|
||||
pre {
|
||||
border: 1pt solid #AEBDCC;
|
||||
background-color: #F3F5F7;
|
||||
padding: 5pt;
|
||||
font-family: courier, monospace;
|
||||
font-size: 90%;
|
||||
overflow:auto;
|
||||
}
|
||||
table { border-collapse: collapse; }
|
||||
td, th { vertical-align: top; }
|
||||
th.right { text-align:center; }
|
||||
th.left { text-align:center; }
|
||||
th.center { text-align:center; }
|
||||
td.right { text-align:right; }
|
||||
td.left { text-align:left; }
|
||||
td.center { text-align:center; }
|
||||
dt { font-weight: bold; }
|
||||
div.figure { padding: 0.5em; }
|
||||
div.figure p { text-align: center; }
|
||||
div.inlinetask {
|
||||
padding:10px;
|
||||
border:2px solid gray;
|
||||
margin:10px;
|
||||
background: #ffffcc;
|
||||
}
|
||||
textarea { overflow-x: auto; }
|
||||
.linenr { font-size:smaller }
|
||||
.code-highlighted {background-color:#ffff00;}
|
||||
.org-info-js_info-navigation { border-style:none; }
|
||||
#org-info-js_console-label { font-size:10px; font-weight:bold;
|
||||
white-space:nowrap; }
|
||||
.org-info-js_search-highlight {background-color:#ffff00; color:#000000;
|
||||
font-weight:bold; }
|
||||
/*]]>*/-->
|
||||
</style>
|
||||
<link rel="stylesheet" type="text/css" href="docstyle.css" />
|
||||
<script type="text/javascript">
|
||||
<!--/*--><![CDATA[/*><!--*/
|
||||
function CodeHighlightOn(elem, id)
|
||||
{
|
||||
var target = document.getElementById(id);
|
||||
if(null != target) {
|
||||
elem.cacheClassElem = elem.className;
|
||||
elem.cacheClassTarget = target.className;
|
||||
target.className = "code-highlighted";
|
||||
elem.className = "code-highlighted";
|
||||
}
|
||||
}
|
||||
function CodeHighlightOff(elem, id)
|
||||
{
|
||||
var target = document.getElementById(id);
|
||||
if(elem.cacheClassElem)
|
||||
elem.className = elem.cacheClassElem;
|
||||
if(elem.cacheClassTarget)
|
||||
target.className = elem.cacheClassTarget;
|
||||
}
|
||||
/*]]>*///-->
|
||||
</script>
|
||||
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div id="preamble">
|
||||
|
||||
</div>
|
||||
|
||||
<div id="content">
|
||||
<h1 class="title">UglifyJS – a JavaScript parser/compressor/beautifier</h1>
|
||||
|
||||
|
||||
<div id="table-of-contents">
|
||||
<h2>Table of Contents</h2>
|
||||
<div id="text-table-of-contents">
|
||||
<ul>
|
||||
<li><a href="#sec-1">1 UglifyJS — a JavaScript parser/compressor/beautifier </a>
|
||||
<ul>
|
||||
<li><a href="#sec-1-1">1.1 Unsafe transformations </a>
|
||||
<ul>
|
||||
<li><a href="#sec-1-1-1">1.1.1 Calls involving the global Array constructor </a></li>
|
||||
<li><a href="#sec-1-1-2">1.1.2 <code>obj.toString()</code> ==> <code>obj+“”</code> </a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><a href="#sec-1-2">1.2 Install (NPM) </a></li>
|
||||
<li><a href="#sec-1-3">1.3 Install latest code from GitHub </a></li>
|
||||
<li><a href="#sec-1-4">1.4 Usage </a>
|
||||
<ul>
|
||||
<li><a href="#sec-1-4-1">1.4.1 API </a></li>
|
||||
<li><a href="#sec-1-4-2">1.4.2 Beautifier shortcoming – no more comments </a></li>
|
||||
<li><a href="#sec-1-4-3">1.4.3 Use as a code pre-processor </a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><a href="#sec-1-5">1.5 Compression – how good is it? </a></li>
|
||||
<li><a href="#sec-1-6">1.6 Bugs? </a></li>
|
||||
<li><a href="#sec-1-7">1.7 Links </a></li>
|
||||
<li><a href="#sec-1-8">1.8 License </a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="outline-container-1" class="outline-2">
|
||||
<h2 id="sec-1"><span class="section-number-2">1</span> UglifyJS — a JavaScript parser/compressor/beautifier </h2>
|
||||
<div class="outline-text-2" id="text-1">
|
||||
|
||||
|
||||
<p>
|
||||
This package implements a general-purpose JavaScript
|
||||
parser/compressor/beautifier toolkit. It is developed on <a href="http://nodejs.org/">NodeJS</a>, but it
|
||||
should work on any JavaScript platform supporting the CommonJS module system
|
||||
(and if your platform of choice doesn't support CommonJS, you can easily
|
||||
implement it, or discard the <code>exports.*</code> lines from UglifyJS sources).
|
||||
</p>
|
||||
<p>
|
||||
The tokenizer/parser generates an abstract syntax tree from JS code. You
|
||||
can then traverse the AST to learn more about the code, or do various
|
||||
manipulations on it. This part is implemented in <a href="../lib/parse-js.js">parse-js.js</a> and it's a
|
||||
port to JavaScript of the excellent <a href="http://marijn.haverbeke.nl/parse-js/">parse-js</a> Common Lisp library from <a href="http://marijn.haverbeke.nl/">Marijn Haverbeke</a>.
|
||||
</p>
|
||||
<p>
|
||||
( See <a href="http://github.com/mishoo/cl-uglify-js">cl-uglify-js</a> if you're looking for the Common Lisp version of
|
||||
UglifyJS. )
|
||||
</p>
|
||||
<p>
|
||||
The second part of this package, implemented in <a href="../lib/process.js">process.js</a>, inspects and
|
||||
manipulates the AST generated by the parser to provide the following:
|
||||
</p>
|
||||
<ul>
|
||||
<li>ability to re-generate JavaScript code from the AST. Optionally
|
||||
indented—you can use this if you want to “beautify” a program that has
|
||||
been compressed, so that you can inspect the source. But you can also run
|
||||
our code generator to print out an AST without any whitespace, so you
|
||||
achieve compression as well.
|
||||
|
||||
</li>
|
||||
<li>shorten variable names (usually to single characters). Our mangler will
|
||||
analyze the code and generate proper variable names, depending on scope
|
||||
and usage, and is smart enough to deal with globals defined elsewhere, or
|
||||
with <code>eval()</code> calls or <code>with{}</code> statements. In short, if <code>eval()</code> or
|
||||
<code>with{}</code> are used in some scope, then all variables in that scope and any
|
||||
variables in the parent scopes will remain unmangled, and any references
|
||||
to such variables remain unmangled as well.
|
||||
|
||||
</li>
|
||||
<li>various small optimizations that may lead to faster code but certainly
|
||||
lead to smaller code. Where possible, we do the following:
|
||||
|
||||
<ul>
|
||||
<li>foo["bar"] ==> foo.bar
|
||||
|
||||
</li>
|
||||
<li>remove block brackets <code>{}</code>
|
||||
|
||||
</li>
|
||||
<li>join consecutive var declarations:
|
||||
var a = 10; var b = 20; ==> var a=10,b=20;
|
||||
|
||||
</li>
|
||||
<li>resolve simple constant expressions: 1 +2 * 3 ==> 7. We only do the
|
||||
replacement if the result occupies less bytes; for example 1/3 would
|
||||
translate to 0.333333333333, so in this case we don't replace it.
|
||||
|
||||
</li>
|
||||
<li>consecutive statements in blocks are merged into a sequence; in many
|
||||
cases, this leaves blocks with a single statement, so then we can remove
|
||||
the block brackets.
|
||||
|
||||
</li>
|
||||
<li>various optimizations for IF statements:
|
||||
|
||||
<ul>
|
||||
<li>if (foo) bar(); else baz(); ==> foo?bar():baz();
|
||||
</li>
|
||||
<li>if (!foo) bar(); else baz(); ==> foo?baz():bar();
|
||||
</li>
|
||||
<li>if (foo) bar(); ==> foo&&bar();
|
||||
</li>
|
||||
<li>if (!foo) bar(); ==> foo||bar();
|
||||
</li>
|
||||
<li>if (foo) return bar(); else return baz(); ==> return foo?bar():baz();
|
||||
</li>
|
||||
<li>if (foo) return bar(); else something(); ==> {if(foo)return bar();something()}
|
||||
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</li>
|
||||
<li>remove some unreachable code and warn about it (code that follows a
|
||||
<code>return</code>, <code>throw</code>, <code>break</code> or <code>continue</code> statement, except
|
||||
function/variable declarations).
|
||||
|
||||
</li>
|
||||
<li>act a limited version of a pre-processor (c.f. the pre-processor of
|
||||
C/C++) to allow you to safely replace selected global symbols with
|
||||
specified values. When combined with the optimisations above this can
|
||||
make UglifyJS operate slightly more like a compilation process, in
|
||||
that when certain symbols are replaced by constant values, entire code
|
||||
blocks may be optimised away as unreachable.
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
<div id="outline-container-1-1" class="outline-3">
|
||||
<h3 id="sec-1-1"><span class="section-number-3">1.1</span> <span class="target">Unsafe transformations</span> </h3>
|
||||
<div class="outline-text-3" id="text-1-1">
|
||||
|
||||
|
||||
<p>
|
||||
The following transformations can in theory break code, although they're
|
||||
probably safe in most practical cases. To enable them you need to pass the
|
||||
<code>--unsafe</code> flag.
|
||||
</p>
|
||||
|
||||
</div>
|
||||
|
||||
<div id="outline-container-1-1-1" class="outline-4">
|
||||
<h4 id="sec-1-1-1"><span class="section-number-4">1.1.1</span> Calls involving the global Array constructor </h4>
|
||||
<div class="outline-text-4" id="text-1-1-1">
|
||||
|
||||
|
||||
<p>
|
||||
The following transformations occur:
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
<pre class="src src-js"><span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3, 4) => [1,2,3,4]
|
||||
Array(a, b, c) => [a,b,c]
|
||||
<span class="org-keyword">new</span> <span class="org-type">Array</span>(5) => Array(5)
|
||||
<span class="org-keyword">new</span> <span class="org-type">Array</span>(a) => Array(a)
|
||||
</pre>
|
||||
|
||||
|
||||
<p>
|
||||
These are all safe if the Array name isn't redefined. JavaScript does allow
|
||||
one to globally redefine Array (and pretty much everything, in fact) but I
|
||||
personally don't see why would anyone do that.
|
||||
</p>
|
||||
<p>
|
||||
UglifyJS does handle the case where Array is redefined locally, or even
|
||||
globally but with a <code>function</code> or <code>var</code> declaration. Therefore, in the
|
||||
following cases UglifyJS <b>doesn't touch</b> calls or instantiations of Array:
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
<pre class="src src-js"><span class="org-comment-delimiter">// </span><span class="org-comment">case 1. globally declared variable</span>
|
||||
<span class="org-keyword">var</span> <span class="org-variable-name">Array</span>;
|
||||
<span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3);
|
||||
Array(a, b);
|
||||
|
||||
<span class="org-comment-delimiter">// </span><span class="org-comment">or (can be declared later)</span>
|
||||
<span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3);
|
||||
<span class="org-keyword">var</span> <span class="org-variable-name">Array</span>;
|
||||
|
||||
<span class="org-comment-delimiter">// </span><span class="org-comment">or (can be a function)</span>
|
||||
<span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3);
|
||||
<span class="org-keyword">function</span> <span class="org-function-name">Array</span>() { ... }
|
||||
|
||||
<span class="org-comment-delimiter">// </span><span class="org-comment">case 2. declared in a function</span>
|
||||
(<span class="org-keyword">function</span>(){
|
||||
a = <span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3);
|
||||
b = Array(5, 6);
|
||||
<span class="org-keyword">var</span> <span class="org-variable-name">Array</span>;
|
||||
})();
|
||||
|
||||
<span class="org-comment-delimiter">// </span><span class="org-comment">or</span>
|
||||
(<span class="org-keyword">function</span>(<span class="org-variable-name">Array</span>){
|
||||
<span class="org-keyword">return</span> Array(5, 6, 7);
|
||||
})();
|
||||
|
||||
<span class="org-comment-delimiter">// </span><span class="org-comment">or</span>
|
||||
(<span class="org-keyword">function</span>(){
|
||||
<span class="org-keyword">return</span> <span class="org-keyword">new</span> <span class="org-type">Array</span>(1, 2, 3, 4);
|
||||
<span class="org-keyword">function</span> <span class="org-function-name">Array</span>() { ... }
|
||||
})();
|
||||
|
||||
<span class="org-comment-delimiter">// </span><span class="org-comment">etc.</span>
|
||||
</pre>
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div id="outline-container-1-1-2" class="outline-4">
|
||||
<h4 id="sec-1-1-2"><span class="section-number-4">1.1.2</span> <code>obj.toString()</code> ==> <code>obj+“”</code> </h4>
|
||||
<div class="outline-text-4" id="text-1-1-2">
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div id="outline-container-1-2" class="outline-3">
|
||||
<h3 id="sec-1-2"><span class="section-number-3">1.2</span> Install (NPM) </h3>
|
||||
<div class="outline-text-3" id="text-1-2">
|
||||
|
||||
|
||||
<p>
|
||||
UglifyJS is now available through NPM — <code>npm install uglify-js</code> should do
|
||||
the job.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div id="outline-container-1-3" class="outline-3">
|
||||
<h3 id="sec-1-3"><span class="section-number-3">1.3</span> Install latest code from GitHub </h3>
|
||||
<div class="outline-text-3" id="text-1-3">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<pre class="src src-sh"><span class="org-comment-delimiter">## </span><span class="org-comment">clone the repository</span>
|
||||
mkdir -p /where/you/wanna/put/it
|
||||
<span class="org-builtin">cd</span> /where/you/wanna/put/it
|
||||
git clone git://github.com/mishoo/UglifyJS.git
|
||||
|
||||
<span class="org-comment-delimiter">## </span><span class="org-comment">make the module available to Node</span>
|
||||
mkdir -p ~/.node_libraries/
|
||||
<span class="org-builtin">cd</span> ~/.node_libraries/
|
||||
ln -s /where/you/wanna/put/it/UglifyJS/uglify-js.js
|
||||
|
||||
<span class="org-comment-delimiter">## </span><span class="org-comment">and if you want the CLI script too:</span>
|
||||
mkdir -p ~/bin
|
||||
<span class="org-builtin">cd</span> ~/bin
|
||||
ln -s /where/you/wanna/put/it/UglifyJS/bin/uglifyjs
|
||||
<span class="org-comment-delimiter"># </span><span class="org-comment">(then add ~/bin to your $PATH if it's not there already)</span>
|
||||
</pre>
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div id="outline-container-1-4" class="outline-3">
|
||||
<h3 id="sec-1-4"><span class="section-number-3">1.4</span> Usage </h3>
|
||||
<div class="outline-text-3" id="text-1-4">
|
||||
|
||||
|
||||
<p>
|
||||
There is a command-line tool that exposes the functionality of this library
|
||||
for your shell-scripting needs:
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
<pre class="src src-sh">uglifyjs [ options... ] [ filename ]
|
||||
</pre>
|
||||
|
||||
|
||||
<p>
|
||||
<code>filename</code> should be the last argument and should name the file from which
|
||||
to read the JavaScript code. If you don't specify it, it will read code
|
||||
from STDIN.
|
||||
</p>
|
||||
<p>
|
||||
Supported options:
|
||||
</p>
|
||||
<ul>
|
||||
<li><code>-b</code> or <code>--beautify</code> — output indented code; when passed, additional
|
||||
options control the beautifier:
|
||||
|
||||
<ul>
|
||||
<li><code>-i N</code> or <code>--indent N</code> — indentation level (number of spaces)
|
||||
|
||||
</li>
|
||||
<li><code>-q</code> or <code>--quote-keys</code> — quote keys in literal objects (by default,
|
||||
only keys that cannot be identifier names will be quotes).
|
||||
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</li>
|
||||
<li><code>--ascii</code> — pass this argument to encode non-ASCII characters as
|
||||
<code>\uXXXX</code> sequences. By default UglifyJS won't bother to do it and will
|
||||
output Unicode characters instead. (the output is always encoded in UTF8,
|
||||
but if you pass this option you'll only get ASCII).
|
||||
|
||||
</li>
|
||||
<li><code>-nm</code> or <code>--no-mangle</code> — don't mangle names.
|
||||
|
||||
</li>
|
||||
<li><code>-nmf</code> or <code>--no-mangle-functions</code> – in case you want to mangle variable
|
||||
names, but not touch function names.
|
||||
|
||||
</li>
|
||||
<li><code>-ns</code> or <code>--no-squeeze</code> — don't call <code>ast_squeeze()</code> (which does various
|
||||
optimizations that result in smaller, less readable code).
|
||||
|
||||
</li>
|
||||
<li><code>-mt</code> or <code>--mangle-toplevel</code> — mangle names in the toplevel scope too
|
||||
(by default we don't do this).
|
||||
|
||||
</li>
|
||||
<li><code>--no-seqs</code> — when <code>ast_squeeze()</code> is called (thus, unless you pass
|
||||
<code>--no-squeeze</code>) it will reduce consecutive statements in blocks into a
|
||||
sequence. For example, "a = 10; b = 20; foo();" will be written as
|
||||
"a=10,b=20,foo();". In various occasions, this allows us to discard the
|
||||
block brackets (since the block becomes a single statement). This is ON
|
||||
by default because it seems safe and saves a few hundred bytes on some
|
||||
libs that I tested it on, but pass <code>--no-seqs</code> to disable it.
|
||||
|
||||
</li>
|
||||
<li><code>--no-dead-code</code> — by default, UglifyJS will remove code that is
|
||||
obviously unreachable (code that follows a <code>return</code>, <code>throw</code>, <code>break</code> or
|
||||
<code>continue</code> statement and is not a function/variable declaration). Pass
|
||||
this option to disable this optimization.
|
||||
|
||||
</li>
|
||||
<li><code>-nc</code> or <code>--no-copyright</code> — by default, <code>uglifyjs</code> will keep the initial
|
||||
comment tokens in the generated code (assumed to be copyright information
|
||||
etc.). If you pass this it will discard it.
|
||||
|
||||
</li>
|
||||
<li><code>-o filename</code> or <code>--output filename</code> — put the result in <code>filename</code>. If
|
||||
this isn't given, the result goes to standard output (or see next one).
|
||||
|
||||
</li>
|
||||
<li><code>--overwrite</code> — if the code is read from a file (not from STDIN) and you
|
||||
pass <code>--overwrite</code> then the output will be written in the same file.
|
||||
|
||||
</li>
|
||||
<li><code>--ast</code> — pass this if you want to get the Abstract Syntax Tree instead
|
||||
of JavaScript as output. Useful for debugging or learning more about the
|
||||
internals.
|
||||
|
||||
</li>
|
||||
<li><code>-v</code> or <code>--verbose</code> — output some notes on STDERR (for now just how long
|
||||
each operation takes).
|
||||
|
||||
</li>
|
||||
<li><code>-d SYMBOL[=VALUE]</code> or <code>--define SYMBOL[=VALUE]</code> — will replace
|
||||
all instances of the specified symbol where used as an identifier
|
||||
(except where symbol has properly declared by a var declaration or
|
||||
use as function parameter or similar) with the specified value. This
|
||||
argument may be specified multiple times to define multiple
|
||||
symbols - if no value is specified the symbol will be replaced with
|
||||
the value <code>true</code>, or you can specify a numeric value (such as
|
||||
<code>1024</code>), a quoted string value (such as ="object"= or
|
||||
='https://github.com'<code>), or the name of another symbol or keyword (such as =null</code> or <code>document</code>).
|
||||
This allows you, for example, to assign meaningful names to key
|
||||
constant values but discard the symbolic names in the uglified
|
||||
version for brevity/efficiency, or when used wth care, allows
|
||||
UglifyJS to operate as a form of <b>conditional compilation</b>
|
||||
whereby defining appropriate values may, by dint of the constant
|
||||
folding and dead code removal features above, remove entire
|
||||
superfluous code blocks (e.g. completely remove instrumentation or
|
||||
trace code for production use).
|
||||
Where string values are being defined, the handling of quotes are
|
||||
likely to be subject to the specifics of your command shell
|
||||
environment, so you may need to experiment with quoting styles
|
||||
depending on your platform, or you may find the option
|
||||
<code>--define-from-module</code> more suitable for use.
|
||||
|
||||
</li>
|
||||
<li><code>-define-from-module SOMEMODULE</code> — will load the named module (as
|
||||
per the NodeJS <code>require()</code> function) and iterate all the exported
|
||||
properties of the module defining them as symbol names to be defined
|
||||
(as if by the <code>--define</code> option) per the name of each property
|
||||
(i.e. without the module name prefix) and given the value of the
|
||||
property. This is a much easier way to handle and document groups of
|
||||
symbols to be defined rather than a large number of <code>--define</code>
|
||||
options.
|
||||
|
||||
</li>
|
||||
<li><code>--unsafe</code> — enable other additional optimizations that are known to be
|
||||
unsafe in some contrived situations, but could still be generally useful.
|
||||
For now only these:
|
||||
|
||||
<ul>
|
||||
<li>foo.toString() ==> foo+""
|
||||
</li>
|
||||
<li>new Array(x,…) ==> [x,…]
|
||||
</li>
|
||||
<li>new Array(x) ==> Array(x)
|
||||
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</li>
|
||||
<li><code>--max-line-len</code> (default 32K characters) — add a newline after around
|
||||
32K characters. I've seen both FF and Chrome croak when all the code was
|
||||
on a single line of around 670K. Pass –max-line-len 0 to disable this
|
||||
safety feature.
|
||||
|
||||
</li>
|
||||
<li><code>--reserved-names</code> — some libraries rely on certain names to be used, as
|
||||
pointed out in issue #92 and #81, so this option allow you to exclude such
|
||||
names from the mangler. For example, to keep names <code>require</code> and <code>$super</code>
|
||||
intact you'd specify –reserved-names "require,$super".
|
||||
|
||||
</li>
|
||||
<li><code>--inline-script</code> – when you want to include the output literally in an
|
||||
HTML <code><script></code> tag you can use this option to prevent <code></script</code> from
|
||||
showing up in the output.
|
||||
|
||||
</li>
|
||||
<li><code>--lift-vars</code> – when you pass this, UglifyJS will apply the following
|
||||
transformations (see the notes in API, <code>ast_lift_variables</code>):
|
||||
|
||||
<ul>
|
||||
<li>put all <code>var</code> declarations at the start of the scope
|
||||
</li>
|
||||
<li>make sure a variable is declared only once
|
||||
</li>
|
||||
<li>discard unused function arguments
|
||||
</li>
|
||||
<li>discard unused inner (named) functions
|
||||
</li>
|
||||
<li>finally, try to merge assignments into that one <code>var</code> declaration, if
|
||||
possible.
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
<div id="outline-container-1-4-1" class="outline-4">
|
||||
<h4 id="sec-1-4-1"><span class="section-number-4">1.4.1</span> API </h4>
|
||||
<div class="outline-text-4" id="text-1-4-1">
|
||||
|
||||
|
||||
<p>
|
||||
To use the library from JavaScript, you'd do the following (example for
|
||||
NodeJS):
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
<pre class="src src-js"><span class="org-keyword">var</span> <span class="org-variable-name">jsp</span> = require(<span class="org-string">"uglify-js"</span>).parser;
|
||||
<span class="org-keyword">var</span> <span class="org-variable-name">pro</span> = require(<span class="org-string">"uglify-js"</span>).uglify;
|
||||
|
||||
<span class="org-keyword">var</span> <span class="org-variable-name">orig_code</span> = <span class="org-string">"... JS code here"</span>;
|
||||
<span class="org-keyword">var</span> <span class="org-variable-name">ast</span> = jsp.parse(orig_code); <span class="org-comment-delimiter">// </span><span class="org-comment">parse code and get the initial AST</span>
|
||||
ast = pro.ast_mangle(ast); <span class="org-comment-delimiter">// </span><span class="org-comment">get a new AST with mangled names</span>
|
||||
ast = pro.ast_squeeze(ast); <span class="org-comment-delimiter">// </span><span class="org-comment">get an AST with compression optimizations</span>
|
||||
<span class="org-keyword">var</span> <span class="org-variable-name">final_code</span> = pro.gen_code(ast); <span class="org-comment-delimiter">// </span><span class="org-comment">compressed code here</span>
|
||||
</pre>
|
||||
|
||||
|
||||
<p>
|
||||
The above performs the full compression that is possible right now. As you
|
||||
can see, there are a sequence of steps which you can apply. For example if
|
||||
you want compressed output but for some reason you don't want to mangle
|
||||
variable names, you would simply skip the line that calls
|
||||
<code>pro.ast_mangle(ast)</code>.
|
||||
</p>
|
||||
<p>
|
||||
Some of these functions take optional arguments. Here's a description:
|
||||
</p>
|
||||
<ul>
|
||||
<li><code>jsp.parse(code, strict_semicolons)</code> – parses JS code and returns an AST.
|
||||
<code>strict_semicolons</code> is optional and defaults to <code>false</code>. If you pass
|
||||
<code>true</code> then the parser will throw an error when it expects a semicolon and
|
||||
it doesn't find it. For most JS code you don't want that, but it's useful
|
||||
if you want to strictly sanitize your code.
|
||||
|
||||
</li>
|
||||
<li><code>pro.ast_lift_variables(ast)</code> – merge and move <code>var</code> declarations to the
|
||||
scop of the scope; discard unused function arguments or variables; discard
|
||||
unused (named) inner functions. It also tries to merge assignments
|
||||
following the <code>var</code> declaration into it.
|
||||
|
||||
<p>
|
||||
If your code is very hand-optimized concerning <code>var</code> declarations, this
|
||||
lifting variable declarations might actually increase size. For me it
|
||||
helps out. On jQuery it adds 865 bytes (243 after gzip). YMMV. Also
|
||||
note that (since it's not enabled by default) this operation isn't yet
|
||||
heavily tested (please report if you find issues!).
|
||||
</p>
|
||||
<p>
|
||||
Note that although it might increase the image size (on jQuery it gains
|
||||
865 bytes, 243 after gzip) it's technically more correct: in certain
|
||||
situations, dead code removal might drop variable declarations, which
|
||||
would not happen if the variables are lifted in advance.
|
||||
</p>
|
||||
<p>
|
||||
Here's an example of what it does:
|
||||
</p></li>
|
||||
</ul>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<pre class="src src-js"><span class="org-keyword">function</span> <span class="org-function-name">f</span>(<span class="org-variable-name">a</span>, <span class="org-variable-name">b</span>, <span class="org-variable-name">c</span>, <span class="org-variable-name">d</span>, <span class="org-variable-name">e</span>) {
|
||||
<span class="org-keyword">var</span> <span class="org-variable-name">q</span>;
|
||||
<span class="org-keyword">var</span> <span class="org-variable-name">w</span>;
|
||||
w = 10;
|
||||
q = 20;
|
||||
<span class="org-keyword">for</span> (<span class="org-keyword">var</span> <span class="org-variable-name">i</span> = 1; i < 10; ++i) {
|
||||
<span class="org-keyword">var</span> <span class="org-variable-name">boo</span> = foo(a);
|
||||
}
|
||||
<span class="org-keyword">for</span> (<span class="org-keyword">var</span> <span class="org-variable-name">i</span> = 0; i < 1; ++i) {
|
||||
<span class="org-keyword">var</span> <span class="org-variable-name">boo</span> = bar(c);
|
||||
}
|
||||
<span class="org-keyword">function</span> <span class="org-function-name">foo</span>(){ ... }
|
||||
<span class="org-keyword">function</span> <span class="org-function-name">bar</span>(){ ... }
|
||||
<span class="org-keyword">function</span> <span class="org-function-name">baz</span>(){ ... }
|
||||
}
|
||||
|
||||
<span class="org-comment-delimiter">// </span><span class="org-comment">transforms into ==></span>
|
||||
|
||||
<span class="org-keyword">function</span> <span class="org-function-name">f</span>(<span class="org-variable-name">a</span>, <span class="org-variable-name">b</span>, <span class="org-variable-name">c</span>) {
|
||||
<span class="org-keyword">var</span> <span class="org-variable-name">i</span>, <span class="org-variable-name">boo</span>, <span class="org-variable-name">w</span> = 10, <span class="org-variable-name">q</span> = 20;
|
||||
<span class="org-keyword">for</span> (i = 1; i < 10; ++i) {
|
||||
boo = foo(a);
|
||||
}
|
||||
<span class="org-keyword">for</span> (i = 0; i < 1; ++i) {
|
||||
boo = bar(c);
|
||||
}
|
||||
<span class="org-keyword">function</span> <span class="org-function-name">foo</span>() { ... }
|
||||
<span class="org-keyword">function</span> <span class="org-function-name">bar</span>() { ... }
|
||||
}
|
||||
</pre>
|
||||
|
||||
|
||||
<ul>
|
||||
<li><code>pro.ast_mangle(ast, options)</code> – generates a new AST containing mangled
|
||||
(compressed) variable and function names. It supports the following
|
||||
options:
|
||||
|
||||
<ul>
|
||||
<li><code>toplevel</code> – mangle toplevel names (by default we don't touch them).
|
||||
</li>
|
||||
<li><code>except</code> – an array of names to exclude from compression.
|
||||
</li>
|
||||
<li><code>defines</code> – an object with properties named after symbols to
|
||||
replace (see the <code>--define</code> option for the script) and the values
|
||||
representing the AST replacement value.
|
||||
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</li>
|
||||
<li><code>pro.ast_squeeze(ast, options)</code> – employs further optimizations designed
|
||||
to reduce the size of the code that <code>gen_code</code> would generate from the
|
||||
AST. Returns a new AST. <code>options</code> can be a hash; the supported options
|
||||
are:
|
||||
|
||||
<ul>
|
||||
<li><code>make_seqs</code> (default true) which will cause consecutive statements in a
|
||||
block to be merged using the "sequence" (comma) operator
|
||||
|
||||
</li>
|
||||
<li><code>dead_code</code> (default true) which will remove unreachable code.
|
||||
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</li>
|
||||
<li><code>pro.gen_code(ast, options)</code> – generates JS code from the AST. By
|
||||
default it's minified, but using the <code>options</code> argument you can get nicely
|
||||
formatted output. <code>options</code> is, well, optional :-) and if you pass it it
|
||||
must be an object and supports the following properties (below you can see
|
||||
the default values):
|
||||
|
||||
<ul>
|
||||
<li><code>beautify: false</code> – pass <code>true</code> if you want indented output
|
||||
</li>
|
||||
<li><code>indent_start: 0</code> (only applies when <code>beautify</code> is <code>true</code>) – initial
|
||||
indentation in spaces
|
||||
</li>
|
||||
<li><code>indent_level: 4</code> (only applies when <code>beautify</code> is <code>true</code>) --
|
||||
indentation level, in spaces (pass an even number)
|
||||
</li>
|
||||
<li><code>quote_keys: false</code> – if you pass <code>true</code> it will quote all keys in
|
||||
literal objects
|
||||
</li>
|
||||
<li><code>space_colon: false</code> (only applies when <code>beautify</code> is <code>true</code>) – wether
|
||||
to put a space before the colon in object literals
|
||||
</li>
|
||||
<li><code>ascii_only: false</code> – pass <code>true</code> if you want to encode non-ASCII
|
||||
characters as <code>\uXXXX</code>.
|
||||
</li>
|
||||
<li><code>inline_script: false</code> – pass <code>true</code> to escape occurrences of
|
||||
<code></script</code> in strings
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div id="outline-container-1-4-2" class="outline-4">
|
||||
<h4 id="sec-1-4-2"><span class="section-number-4">1.4.2</span> Beautifier shortcoming – no more comments </h4>
|
||||
<div class="outline-text-4" id="text-1-4-2">
|
||||
|
||||
|
||||
<p>
|
||||
The beautifier can be used as a general purpose indentation tool. It's
|
||||
useful when you want to make a minified file readable. One limitation,
|
||||
though, is that it discards all comments, so you don't really want to use it
|
||||
to reformat your code, unless you don't have, or don't care about, comments.
|
||||
</p>
|
||||
<p>
|
||||
In fact it's not the beautifier who discards comments — they are dumped at
|
||||
the parsing stage, when we build the initial AST. Comments don't really
|
||||
make sense in the AST, and while we could add nodes for them, it would be
|
||||
inconvenient because we'd have to add special rules to ignore them at all
|
||||
the processing stages.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div id="outline-container-1-4-3" class="outline-4">
|
||||
<h4 id="sec-1-4-3"><span class="section-number-4">1.4.3</span> Use as a code pre-processor </h4>
|
||||
<div class="outline-text-4" id="text-1-4-3">
|
||||
|
||||
|
||||
<p>
|
||||
The <code>--define</code> option can be used, particularly when combined with the
|
||||
constant folding logic, as a form of pre-processor to enable or remove
|
||||
particular constructions, such as might be used for instrumenting
|
||||
development code, or to produce variations aimed at a specific
|
||||
platform.
|
||||
</p>
|
||||
<p>
|
||||
The code below illustrates the way this can be done, and how the
|
||||
symbol replacement is performed.
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
<pre class="src src-js">CLAUSE1: <span class="org-keyword">if</span> (<span class="org-keyword">typeof</span> DEVMODE === <span class="org-string">'undefined'</span>) {
|
||||
DEVMODE = <span class="org-constant">true</span>;
|
||||
}
|
||||
|
||||
<span class="org-function-name">CLAUSE2</span>: <span class="org-keyword">function</span> init() {
|
||||
<span class="org-keyword">if</span> (DEVMODE) {
|
||||
console.log(<span class="org-string">"init() called"</span>);
|
||||
}
|
||||
....
|
||||
DEVMODE &amp;&amp; console.log(<span class="org-string">"init() complete"</span>);
|
||||
}
|
||||
|
||||
<span class="org-function-name">CLAUSE3</span>: <span class="org-keyword">function</span> reportDeviceStatus(<span class="org-variable-name">device</span>) {
|
||||
<span class="org-keyword">var</span> <span class="org-variable-name">DEVMODE</span> = device.mode, <span class="org-variable-name">DEVNAME</span> = device.name;
|
||||
<span class="org-keyword">if</span> (DEVMODE === <span class="org-string">'open'</span>) {
|
||||
....
|
||||
}
|
||||
}
|
||||
</pre>
|
||||
|
||||
|
||||
<p>
|
||||
When the above code is normally executed, the undeclared global
|
||||
variable <code>DEVMODE</code> will be assigned the value <b>true</b> (see <code>CLAUSE1</code>)
|
||||
and so the <code>init()</code> function (<code>CLAUSE2</code>) will write messages to the
|
||||
console log when executed, but in <code>CLAUSE3</code> a locally declared
|
||||
variable will mask access to the <code>DEVMODE</code> global symbol.
|
||||
</p>
|
||||
<p>
|
||||
If the above code is processed by UglifyJS with an argument of
|
||||
<code>--define DEVMODE=false</code> then UglifyJS will replace <code>DEVMODE</code> with the
|
||||
boolean constant value <b>false</b> within <code>CLAUSE1</code> and <code>CLAUSE2</code>, but it
|
||||
will leave <code>CLAUSE3</code> as it stands because there <code>DEVMODE</code> resolves to
|
||||
a validly declared variable.
|
||||
</p>
|
||||
<p>
|
||||
And more so, the constant-folding features of UglifyJS will recognise
|
||||
that the <code>if</code> condition of <code>CLAUSE1</code> is thus always false, and so will
|
||||
remove the test and body of <code>CLAUSE1</code> altogether (including the
|
||||
otherwise slightly problematical statement <code>false = true;</code> which it
|
||||
will have formed by replacing <code>DEVMODE</code> in the body). Similarly,
|
||||
within <code>CLAUSE2</code> both calls to <code>console.log()</code> will be removed
|
||||
altogether.
|
||||
</p>
|
||||
<p>
|
||||
In this way you can mimic, to a limited degree, the functionality of
|
||||
the C/C++ pre-processor to enable or completely remove blocks
|
||||
depending on how certain symbols are defined - perhaps using UglifyJS
|
||||
to generate different versions of source aimed at different
|
||||
environments
|
||||
</p>
|
||||
<p>
|
||||
It is recommmended (but not made mandatory) that symbols designed for
|
||||
this purpose are given names consisting of <code>UPPER_CASE_LETTERS</code> to
|
||||
distinguish them from other (normal) symbols and avoid the sort of
|
||||
clash that <code>CLAUSE3</code> above illustrates.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div id="outline-container-1-5" class="outline-3">
|
||||
<h3 id="sec-1-5"><span class="section-number-3">1.5</span> Compression – how good is it? </h3>
|
||||
<div class="outline-text-3" id="text-1-5">
|
||||
|
||||
|
||||
<p>
|
||||
Here are updated statistics. (I also updated my Google Closure and YUI
|
||||
installations).
|
||||
</p>
|
||||
<p>
|
||||
We're still a lot better than YUI in terms of compression, though slightly
|
||||
slower. We're still a lot faster than Closure, and compression after gzip
|
||||
is comparable.
|
||||
</p>
|
||||
<table border="2" cellspacing="0" cellpadding="6" rules="groups" frame="hsides">
|
||||
<caption></caption>
|
||||
<colgroup><col class="left" /><col class="left" /><col class="right" /><col class="left" /><col class="right" /><col class="left" /><col class="right" />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr><th scope="col" class="left">File</th><th scope="col" class="left">UglifyJS</th><th scope="col" class="right">UglifyJS+gzip</th><th scope="col" class="left">Closure</th><th scope="col" class="right">Closure+gzip</th><th scope="col" class="left">YUI</th><th scope="col" class="right">YUI+gzip</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td class="left">jquery-1.6.2.js</td><td class="left">91001 (0:01.59)</td><td class="right">31896</td><td class="left">90678 (0:07.40)</td><td class="right">31979</td><td class="left">101527 (0:01.82)</td><td class="right">34646</td></tr>
|
||||
<tr><td class="left">paper.js</td><td class="left">142023 (0:01.65)</td><td class="right">43334</td><td class="left">134301 (0:07.42)</td><td class="right">42495</td><td class="left">173383 (0:01.58)</td><td class="right">48785</td></tr>
|
||||
<tr><td class="left">prototype.js</td><td class="left">88544 (0:01.09)</td><td class="right">26680</td><td class="left">86955 (0:06.97)</td><td class="right">26326</td><td class="left">92130 (0:00.79)</td><td class="right">28624</td></tr>
|
||||
<tr><td class="left">thelib-full.js (DynarchLIB)</td><td class="left">251939 (0:02.55)</td><td class="right">72535</td><td class="left">249911 (0:09.05)</td><td class="right">72696</td><td class="left">258869 (0:01.94)</td><td class="right">76584</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div id="outline-container-1-6" class="outline-3">
|
||||
<h3 id="sec-1-6"><span class="section-number-3">1.6</span> Bugs? </h3>
|
||||
<div class="outline-text-3" id="text-1-6">
|
||||
|
||||
|
||||
<p>
|
||||
Unfortunately, for the time being there is no automated test suite. But I
|
||||
ran the compressor manually on non-trivial code, and then I tested that the
|
||||
generated code works as expected. A few hundred times.
|
||||
</p>
|
||||
<p>
|
||||
DynarchLIB was started in times when there was no good JS minifier.
|
||||
Therefore I was quite religious about trying to write short code manually,
|
||||
and as such DL contains a lot of syntactic hacks<sup><a class="footref" name="fnr.1" href="#fn.1">1</a></sup> such as “foo == bar ? a
|
||||
= 10 : b = 20”, though the more readable version would clearly be to use
|
||||
“if/else”.
|
||||
</p>
|
||||
<p>
|
||||
Since the parser/compressor runs fine on DL and jQuery, I'm quite confident
|
||||
that it's solid enough for production use. If you can identify any bugs,
|
||||
I'd love to hear about them (<a href="http://groups.google.com/group/uglifyjs">use the Google Group</a> or email me directly).
|
||||
</p>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div id="outline-container-1-7" class="outline-3">
|
||||
<h3 id="sec-1-7"><span class="section-number-3">1.7</span> Links </h3>
|
||||
<div class="outline-text-3" id="text-1-7">
|
||||
|
||||
|
||||
<ul>
|
||||
<li>Twitter: <a href="http://twitter.com/UglifyJS">@UglifyJS</a>
|
||||
</li>
|
||||
<li>Project at GitHub: <a href="http://github.com/mishoo/UglifyJS">http://github.com/mishoo/UglifyJS</a>
|
||||
</li>
|
||||
<li>Google Group: <a href="http://groups.google.com/group/uglifyjs">http://groups.google.com/group/uglifyjs</a>
|
||||
</li>
|
||||
<li>Common Lisp JS parser: <a href="http://marijn.haverbeke.nl/parse-js/">http://marijn.haverbeke.nl/parse-js/</a>
|
||||
</li>
|
||||
<li>JS-to-Lisp compiler: <a href="http://github.com/marijnh/js">http://github.com/marijnh/js</a>
|
||||
</li>
|
||||
<li>Common Lisp JS uglifier: <a href="http://github.com/mishoo/cl-uglify-js">http://github.com/mishoo/cl-uglify-js</a>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div id="outline-container-1-8" class="outline-3">
|
||||
<h3 id="sec-1-8"><span class="section-number-3">1.8</span> License </h3>
|
||||
<div class="outline-text-3" id="text-1-8">
|
||||
|
||||
|
||||
<p>
|
||||
UglifyJS is released under the BSD license:
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
<pre class="example">Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
|
||||
Based on parse-js (http://marijn.haverbeke.nl/parse-js/).
|
||||
|
||||
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 HOLDER “AS IS” AND ANY
|
||||
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
|
||||
</pre>
|
||||
|
||||
|
||||
<div id="footnotes">
|
||||
<h2 class="footnotes">Footnotes: </h2>
|
||||
<div id="text-footnotes">
|
||||
<p class="footnote"><sup><a class="footnum" name="fn.1" href="#fnr.1">1</a></sup> I even reported a few bugs and suggested some fixes in the original
|
||||
<a href="http://marijn.haverbeke.nl/parse-js/">parse-js</a> library, and Marijn pushed fixes literally in minutes.
|
||||
</p></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="postamble">
|
||||
<p class="date">Date: 2011-12-09 14:59:08 EET</p>
|
||||
<p class="author">Author: Mihai Bazon</p>
|
||||
<p class="creator">Org version 7.7 with Emacs version 23</p>
|
||||
<a href="http://validator.w3.org/check?uri=referer">Validate XHTML 1.0</a>
|
||||
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,578 @@
|
|||
#+TITLE: UglifyJS -- a JavaScript parser/compressor/beautifier
|
||||
#+KEYWORDS: javascript, js, parser, compiler, compressor, mangle, minify, minifier
|
||||
#+DESCRIPTION: a JavaScript parser/compressor/beautifier in JavaScript
|
||||
#+STYLE: <link rel="stylesheet" type="text/css" href="docstyle.css" />
|
||||
#+AUTHOR: Mihai Bazon
|
||||
#+EMAIL: mihai.bazon@gmail.com
|
||||
|
||||
* UglifyJS --- a JavaScript parser/compressor/beautifier
|
||||
|
||||
This package implements a general-purpose JavaScript
|
||||
parser/compressor/beautifier toolkit. It is developed on [[http://nodejs.org/][NodeJS]], but it
|
||||
should work on any JavaScript platform supporting the CommonJS module system
|
||||
(and if your platform of choice doesn't support CommonJS, you can easily
|
||||
implement it, or discard the =exports.*= lines from UglifyJS sources).
|
||||
|
||||
The tokenizer/parser generates an abstract syntax tree from JS code. You
|
||||
can then traverse the AST to learn more about the code, or do various
|
||||
manipulations on it. This part is implemented in [[../lib/parse-js.js][parse-js.js]] and it's a
|
||||
port to JavaScript of the excellent [[http://marijn.haverbeke.nl/parse-js/][parse-js]] Common Lisp library from [[http://marijn.haverbeke.nl/][Marijn
|
||||
Haverbeke]].
|
||||
|
||||
( See [[http://github.com/mishoo/cl-uglify-js][cl-uglify-js]] if you're looking for the Common Lisp version of
|
||||
UglifyJS. )
|
||||
|
||||
The second part of this package, implemented in [[../lib/process.js][process.js]], inspects and
|
||||
manipulates the AST generated by the parser to provide the following:
|
||||
|
||||
- ability to re-generate JavaScript code from the AST. Optionally
|
||||
indented---you can use this if you want to “beautify” a program that has
|
||||
been compressed, so that you can inspect the source. But you can also run
|
||||
our code generator to print out an AST without any whitespace, so you
|
||||
achieve compression as well.
|
||||
|
||||
- shorten variable names (usually to single characters). Our mangler will
|
||||
analyze the code and generate proper variable names, depending on scope
|
||||
and usage, and is smart enough to deal with globals defined elsewhere, or
|
||||
with =eval()= calls or =with{}= statements. In short, if =eval()= or
|
||||
=with{}= are used in some scope, then all variables in that scope and any
|
||||
variables in the parent scopes will remain unmangled, and any references
|
||||
to such variables remain unmangled as well.
|
||||
|
||||
- various small optimizations that may lead to faster code but certainly
|
||||
lead to smaller code. Where possible, we do the following:
|
||||
|
||||
- foo["bar"] ==> foo.bar
|
||||
|
||||
- remove block brackets ={}=
|
||||
|
||||
- join consecutive var declarations:
|
||||
var a = 10; var b = 20; ==> var a=10,b=20;
|
||||
|
||||
- resolve simple constant expressions: 1 +2 * 3 ==> 7. We only do the
|
||||
replacement if the result occupies less bytes; for example 1/3 would
|
||||
translate to 0.333333333333, so in this case we don't replace it.
|
||||
|
||||
- consecutive statements in blocks are merged into a sequence; in many
|
||||
cases, this leaves blocks with a single statement, so then we can remove
|
||||
the block brackets.
|
||||
|
||||
- various optimizations for IF statements:
|
||||
|
||||
- if (foo) bar(); else baz(); ==> foo?bar():baz();
|
||||
- if (!foo) bar(); else baz(); ==> foo?baz():bar();
|
||||
- if (foo) bar(); ==> foo&&bar();
|
||||
- if (!foo) bar(); ==> foo||bar();
|
||||
- if (foo) return bar(); else return baz(); ==> return foo?bar():baz();
|
||||
- if (foo) return bar(); else something(); ==> {if(foo)return bar();something()}
|
||||
|
||||
- remove some unreachable code and warn about it (code that follows a
|
||||
=return=, =throw=, =break= or =continue= statement, except
|
||||
function/variable declarations).
|
||||
|
||||
- act a limited version of a pre-processor (c.f. the pre-processor of
|
||||
C/C++) to allow you to safely replace selected global symbols with
|
||||
specified values. When combined with the optimisations above this can
|
||||
make UglifyJS operate slightly more like a compilation process, in
|
||||
that when certain symbols are replaced by constant values, entire code
|
||||
blocks may be optimised away as unreachable.
|
||||
|
||||
** <<Unsafe transformations>>
|
||||
|
||||
The following transformations can in theory break code, although they're
|
||||
probably safe in most practical cases. To enable them you need to pass the
|
||||
=--unsafe= flag.
|
||||
|
||||
*** Calls involving the global Array constructor
|
||||
|
||||
The following transformations occur:
|
||||
|
||||
#+BEGIN_SRC js
|
||||
new Array(1, 2, 3, 4) => [1,2,3,4]
|
||||
Array(a, b, c) => [a,b,c]
|
||||
new Array(5) => Array(5)
|
||||
new Array(a) => Array(a)
|
||||
#+END_SRC
|
||||
|
||||
These are all safe if the Array name isn't redefined. JavaScript does allow
|
||||
one to globally redefine Array (and pretty much everything, in fact) but I
|
||||
personally don't see why would anyone do that.
|
||||
|
||||
UglifyJS does handle the case where Array is redefined locally, or even
|
||||
globally but with a =function= or =var= declaration. Therefore, in the
|
||||
following cases UglifyJS *doesn't touch* calls or instantiations of Array:
|
||||
|
||||
#+BEGIN_SRC js
|
||||
// case 1. globally declared variable
|
||||
var Array;
|
||||
new Array(1, 2, 3);
|
||||
Array(a, b);
|
||||
|
||||
// or (can be declared later)
|
||||
new Array(1, 2, 3);
|
||||
var Array;
|
||||
|
||||
// or (can be a function)
|
||||
new Array(1, 2, 3);
|
||||
function Array() { ... }
|
||||
|
||||
// case 2. declared in a function
|
||||
(function(){
|
||||
a = new Array(1, 2, 3);
|
||||
b = Array(5, 6);
|
||||
var Array;
|
||||
})();
|
||||
|
||||
// or
|
||||
(function(Array){
|
||||
return Array(5, 6, 7);
|
||||
})();
|
||||
|
||||
// or
|
||||
(function(){
|
||||
return new Array(1, 2, 3, 4);
|
||||
function Array() { ... }
|
||||
})();
|
||||
|
||||
// etc.
|
||||
#+END_SRC
|
||||
|
||||
*** =obj.toString()= ==> =obj+“”=
|
||||
|
||||
** Install (NPM)
|
||||
|
||||
UglifyJS is now available through NPM --- =npm install uglify-js= should do
|
||||
the job.
|
||||
|
||||
** Install latest code from GitHub
|
||||
|
||||
#+BEGIN_SRC sh
|
||||
## clone the repository
|
||||
mkdir -p /where/you/wanna/put/it
|
||||
cd /where/you/wanna/put/it
|
||||
git clone git://github.com/mishoo/UglifyJS.git
|
||||
|
||||
## make the module available to Node
|
||||
mkdir -p ~/.node_libraries/
|
||||
cd ~/.node_libraries/
|
||||
ln -s /where/you/wanna/put/it/UglifyJS/uglify-js.js
|
||||
|
||||
## and if you want the CLI script too:
|
||||
mkdir -p ~/bin
|
||||
cd ~/bin
|
||||
ln -s /where/you/wanna/put/it/UglifyJS/bin/uglifyjs
|
||||
# (then add ~/bin to your $PATH if it's not there already)
|
||||
#+END_SRC
|
||||
|
||||
** Usage
|
||||
|
||||
There is a command-line tool that exposes the functionality of this library
|
||||
for your shell-scripting needs:
|
||||
|
||||
#+BEGIN_SRC sh
|
||||
uglifyjs [ options... ] [ filename ]
|
||||
#+END_SRC
|
||||
|
||||
=filename= should be the last argument and should name the file from which
|
||||
to read the JavaScript code. If you don't specify it, it will read code
|
||||
from STDIN.
|
||||
|
||||
Supported options:
|
||||
|
||||
- =-b= or =--beautify= --- output indented code; when passed, additional
|
||||
options control the beautifier:
|
||||
|
||||
- =-i N= or =--indent N= --- indentation level (number of spaces)
|
||||
|
||||
- =-q= or =--quote-keys= --- quote keys in literal objects (by default,
|
||||
only keys that cannot be identifier names will be quotes).
|
||||
|
||||
- =-c= or =----consolidate-primitive-values= --- consolidates null, Boolean,
|
||||
and String values. Known as aliasing in the Closure Compiler. Worsens the
|
||||
data compression ratio of gzip.
|
||||
|
||||
- =--ascii= --- pass this argument to encode non-ASCII characters as
|
||||
=\uXXXX= sequences. By default UglifyJS won't bother to do it and will
|
||||
output Unicode characters instead. (the output is always encoded in UTF8,
|
||||
but if you pass this option you'll only get ASCII).
|
||||
|
||||
- =-nm= or =--no-mangle= --- don't mangle names.
|
||||
|
||||
- =-nmf= or =--no-mangle-functions= -- in case you want to mangle variable
|
||||
names, but not touch function names.
|
||||
|
||||
- =-ns= or =--no-squeeze= --- don't call =ast_squeeze()= (which does various
|
||||
optimizations that result in smaller, less readable code).
|
||||
|
||||
- =-mt= or =--mangle-toplevel= --- mangle names in the toplevel scope too
|
||||
(by default we don't do this).
|
||||
|
||||
- =--no-seqs= --- when =ast_squeeze()= is called (thus, unless you pass
|
||||
=--no-squeeze=) it will reduce consecutive statements in blocks into a
|
||||
sequence. For example, "a = 10; b = 20; foo();" will be written as
|
||||
"a=10,b=20,foo();". In various occasions, this allows us to discard the
|
||||
block brackets (since the block becomes a single statement). This is ON
|
||||
by default because it seems safe and saves a few hundred bytes on some
|
||||
libs that I tested it on, but pass =--no-seqs= to disable it.
|
||||
|
||||
- =--no-dead-code= --- by default, UglifyJS will remove code that is
|
||||
obviously unreachable (code that follows a =return=, =throw=, =break= or
|
||||
=continue= statement and is not a function/variable declaration). Pass
|
||||
this option to disable this optimization.
|
||||
|
||||
- =-nc= or =--no-copyright= --- by default, =uglifyjs= will keep the initial
|
||||
comment tokens in the generated code (assumed to be copyright information
|
||||
etc.). If you pass this it will discard it.
|
||||
|
||||
- =-o filename= or =--output filename= --- put the result in =filename=. If
|
||||
this isn't given, the result goes to standard output (or see next one).
|
||||
|
||||
- =--overwrite= --- if the code is read from a file (not from STDIN) and you
|
||||
pass =--overwrite= then the output will be written in the same file.
|
||||
|
||||
- =--ast= --- pass this if you want to get the Abstract Syntax Tree instead
|
||||
of JavaScript as output. Useful for debugging or learning more about the
|
||||
internals.
|
||||
|
||||
- =-v= or =--verbose= --- output some notes on STDERR (for now just how long
|
||||
each operation takes).
|
||||
|
||||
- =-d SYMBOL[=VALUE]= or =--define SYMBOL[=VALUE]= --- will replace
|
||||
all instances of the specified symbol where used as an identifier
|
||||
(except where symbol has properly declared by a var declaration or
|
||||
use as function parameter or similar) with the specified value. This
|
||||
argument may be specified multiple times to define multiple
|
||||
symbols - if no value is specified the symbol will be replaced with
|
||||
the value =true=, or you can specify a numeric value (such as
|
||||
=1024=), a quoted string value (such as ="object"= or
|
||||
='https://github.com'=), or the name of another symbol or keyword
|
||||
(such as =null= or =document=).
|
||||
This allows you, for example, to assign meaningful names to key
|
||||
constant values but discard the symbolic names in the uglified
|
||||
version for brevity/efficiency, or when used wth care, allows
|
||||
UglifyJS to operate as a form of *conditional compilation*
|
||||
whereby defining appropriate values may, by dint of the constant
|
||||
folding and dead code removal features above, remove entire
|
||||
superfluous code blocks (e.g. completely remove instrumentation or
|
||||
trace code for production use).
|
||||
Where string values are being defined, the handling of quotes are
|
||||
likely to be subject to the specifics of your command shell
|
||||
environment, so you may need to experiment with quoting styles
|
||||
depending on your platform, or you may find the option
|
||||
=--define-from-module= more suitable for use.
|
||||
|
||||
- =-define-from-module SOMEMODULE= --- will load the named module (as
|
||||
per the NodeJS =require()= function) and iterate all the exported
|
||||
properties of the module defining them as symbol names to be defined
|
||||
(as if by the =--define= option) per the name of each property
|
||||
(i.e. without the module name prefix) and given the value of the
|
||||
property. This is a much easier way to handle and document groups of
|
||||
symbols to be defined rather than a large number of =--define=
|
||||
options.
|
||||
|
||||
- =--unsafe= --- enable other additional optimizations that are known to be
|
||||
unsafe in some contrived situations, but could still be generally useful.
|
||||
For now only these:
|
||||
|
||||
- foo.toString() ==> foo+""
|
||||
- new Array(x,...) ==> [x,...]
|
||||
- new Array(x) ==> Array(x)
|
||||
|
||||
- =--max-line-len= (default 32K characters) --- add a newline after around
|
||||
32K characters. I've seen both FF and Chrome croak when all the code was
|
||||
on a single line of around 670K. Pass --max-line-len 0 to disable this
|
||||
safety feature.
|
||||
|
||||
- =--reserved-names= --- some libraries rely on certain names to be used, as
|
||||
pointed out in issue #92 and #81, so this option allow you to exclude such
|
||||
names from the mangler. For example, to keep names =require= and =$super=
|
||||
intact you'd specify --reserved-names "require,$super".
|
||||
|
||||
- =--inline-script= -- when you want to include the output literally in an
|
||||
HTML =<script>= tag you can use this option to prevent =</script= from
|
||||
showing up in the output.
|
||||
|
||||
- =--lift-vars= -- when you pass this, UglifyJS will apply the following
|
||||
transformations (see the notes in API, =ast_lift_variables=):
|
||||
|
||||
- put all =var= declarations at the start of the scope
|
||||
- make sure a variable is declared only once
|
||||
- discard unused function arguments
|
||||
- discard unused inner (named) functions
|
||||
- finally, try to merge assignments into that one =var= declaration, if
|
||||
possible.
|
||||
|
||||
*** API
|
||||
|
||||
To use the library from JavaScript, you'd do the following (example for
|
||||
NodeJS):
|
||||
|
||||
#+BEGIN_SRC js
|
||||
var jsp = require("uglify-js").parser;
|
||||
var pro = require("uglify-js").uglify;
|
||||
|
||||
var orig_code = "... JS code here";
|
||||
var ast = jsp.parse(orig_code); // parse code and get the initial AST
|
||||
ast = pro.ast_mangle(ast); // get a new AST with mangled names
|
||||
ast = pro.ast_squeeze(ast); // get an AST with compression optimizations
|
||||
var final_code = pro.gen_code(ast); // compressed code here
|
||||
#+END_SRC
|
||||
|
||||
The above performs the full compression that is possible right now. As you
|
||||
can see, there are a sequence of steps which you can apply. For example if
|
||||
you want compressed output but for some reason you don't want to mangle
|
||||
variable names, you would simply skip the line that calls
|
||||
=pro.ast_mangle(ast)=.
|
||||
|
||||
Some of these functions take optional arguments. Here's a description:
|
||||
|
||||
- =jsp.parse(code, strict_semicolons)= -- parses JS code and returns an AST.
|
||||
=strict_semicolons= is optional and defaults to =false=. If you pass
|
||||
=true= then the parser will throw an error when it expects a semicolon and
|
||||
it doesn't find it. For most JS code you don't want that, but it's useful
|
||||
if you want to strictly sanitize your code.
|
||||
|
||||
- =pro.ast_lift_variables(ast)= -- merge and move =var= declarations to the
|
||||
scop of the scope; discard unused function arguments or variables; discard
|
||||
unused (named) inner functions. It also tries to merge assignments
|
||||
following the =var= declaration into it.
|
||||
|
||||
If your code is very hand-optimized concerning =var= declarations, this
|
||||
lifting variable declarations might actually increase size. For me it
|
||||
helps out. On jQuery it adds 865 bytes (243 after gzip). YMMV. Also
|
||||
note that (since it's not enabled by default) this operation isn't yet
|
||||
heavily tested (please report if you find issues!).
|
||||
|
||||
Note that although it might increase the image size (on jQuery it gains
|
||||
865 bytes, 243 after gzip) it's technically more correct: in certain
|
||||
situations, dead code removal might drop variable declarations, which
|
||||
would not happen if the variables are lifted in advance.
|
||||
|
||||
Here's an example of what it does:
|
||||
|
||||
#+BEGIN_SRC js
|
||||
function f(a, b, c, d, e) {
|
||||
var q;
|
||||
var w;
|
||||
w = 10;
|
||||
q = 20;
|
||||
for (var i = 1; i < 10; ++i) {
|
||||
var boo = foo(a);
|
||||
}
|
||||
for (var i = 0; i < 1; ++i) {
|
||||
var boo = bar(c);
|
||||
}
|
||||
function foo(){ ... }
|
||||
function bar(){ ... }
|
||||
function baz(){ ... }
|
||||
}
|
||||
|
||||
// transforms into ==>
|
||||
|
||||
function f(a, b, c) {
|
||||
var i, boo, w = 10, q = 20;
|
||||
for (i = 1; i < 10; ++i) {
|
||||
boo = foo(a);
|
||||
}
|
||||
for (i = 0; i < 1; ++i) {
|
||||
boo = bar(c);
|
||||
}
|
||||
function foo() { ... }
|
||||
function bar() { ... }
|
||||
}
|
||||
#+END_SRC
|
||||
|
||||
- =pro.ast_mangle(ast, options)= -- generates a new AST containing mangled
|
||||
(compressed) variable and function names. It supports the following
|
||||
options:
|
||||
|
||||
- =toplevel= -- mangle toplevel names (by default we don't touch them).
|
||||
- =except= -- an array of names to exclude from compression.
|
||||
- =defines= -- an object with properties named after symbols to
|
||||
replace (see the =--define= option for the script) and the values
|
||||
representing the AST replacement value.
|
||||
|
||||
- =pro.ast_squeeze(ast, options)= -- employs further optimizations designed
|
||||
to reduce the size of the code that =gen_code= would generate from the
|
||||
AST. Returns a new AST. =options= can be a hash; the supported options
|
||||
are:
|
||||
|
||||
- =make_seqs= (default true) which will cause consecutive statements in a
|
||||
block to be merged using the "sequence" (comma) operator
|
||||
|
||||
- =dead_code= (default true) which will remove unreachable code.
|
||||
|
||||
- =pro.gen_code(ast, options)= -- generates JS code from the AST. By
|
||||
default it's minified, but using the =options= argument you can get nicely
|
||||
formatted output. =options= is, well, optional :-) and if you pass it it
|
||||
must be an object and supports the following properties (below you can see
|
||||
the default values):
|
||||
|
||||
- =beautify: false= -- pass =true= if you want indented output
|
||||
- =indent_start: 0= (only applies when =beautify= is =true=) -- initial
|
||||
indentation in spaces
|
||||
- =indent_level: 4= (only applies when =beautify= is =true=) --
|
||||
indentation level, in spaces (pass an even number)
|
||||
- =quote_keys: false= -- if you pass =true= it will quote all keys in
|
||||
literal objects
|
||||
- =space_colon: false= (only applies when =beautify= is =true=) -- wether
|
||||
to put a space before the colon in object literals
|
||||
- =ascii_only: false= -- pass =true= if you want to encode non-ASCII
|
||||
characters as =\uXXXX=.
|
||||
- =inline_script: false= -- pass =true= to escape occurrences of
|
||||
=</script= in strings
|
||||
|
||||
*** Beautifier shortcoming -- no more comments
|
||||
|
||||
The beautifier can be used as a general purpose indentation tool. It's
|
||||
useful when you want to make a minified file readable. One limitation,
|
||||
though, is that it discards all comments, so you don't really want to use it
|
||||
to reformat your code, unless you don't have, or don't care about, comments.
|
||||
|
||||
In fact it's not the beautifier who discards comments --- they are dumped at
|
||||
the parsing stage, when we build the initial AST. Comments don't really
|
||||
make sense in the AST, and while we could add nodes for them, it would be
|
||||
inconvenient because we'd have to add special rules to ignore them at all
|
||||
the processing stages.
|
||||
|
||||
*** Use as a code pre-processor
|
||||
|
||||
The =--define= option can be used, particularly when combined with the
|
||||
constant folding logic, as a form of pre-processor to enable or remove
|
||||
particular constructions, such as might be used for instrumenting
|
||||
development code, or to produce variations aimed at a specific
|
||||
platform.
|
||||
|
||||
The code below illustrates the way this can be done, and how the
|
||||
symbol replacement is performed.
|
||||
|
||||
#+BEGIN_SRC js
|
||||
CLAUSE1: if (typeof DEVMODE === 'undefined') {
|
||||
DEVMODE = true;
|
||||
}
|
||||
|
||||
CLAUSE2: function init() {
|
||||
if (DEVMODE) {
|
||||
console.log("init() called");
|
||||
}
|
||||
....
|
||||
DEVMODE && console.log("init() complete");
|
||||
}
|
||||
|
||||
CLAUSE3: function reportDeviceStatus(device) {
|
||||
var DEVMODE = device.mode, DEVNAME = device.name;
|
||||
if (DEVMODE === 'open') {
|
||||
....
|
||||
}
|
||||
}
|
||||
#+END_SRC
|
||||
|
||||
When the above code is normally executed, the undeclared global
|
||||
variable =DEVMODE= will be assigned the value *true* (see =CLAUSE1=)
|
||||
and so the =init()= function (=CLAUSE2=) will write messages to the
|
||||
console log when executed, but in =CLAUSE3= a locally declared
|
||||
variable will mask access to the =DEVMODE= global symbol.
|
||||
|
||||
If the above code is processed by UglifyJS with an argument of
|
||||
=--define DEVMODE=false= then UglifyJS will replace =DEVMODE= with the
|
||||
boolean constant value *false* within =CLAUSE1= and =CLAUSE2=, but it
|
||||
will leave =CLAUSE3= as it stands because there =DEVMODE= resolves to
|
||||
a validly declared variable.
|
||||
|
||||
And more so, the constant-folding features of UglifyJS will recognise
|
||||
that the =if= condition of =CLAUSE1= is thus always false, and so will
|
||||
remove the test and body of =CLAUSE1= altogether (including the
|
||||
otherwise slightly problematical statement =false = true;= which it
|
||||
will have formed by replacing =DEVMODE= in the body). Similarly,
|
||||
within =CLAUSE2= both calls to =console.log()= will be removed
|
||||
altogether.
|
||||
|
||||
In this way you can mimic, to a limited degree, the functionality of
|
||||
the C/C++ pre-processor to enable or completely remove blocks
|
||||
depending on how certain symbols are defined - perhaps using UglifyJS
|
||||
to generate different versions of source aimed at different
|
||||
environments
|
||||
|
||||
It is recommmended (but not made mandatory) that symbols designed for
|
||||
this purpose are given names consisting of =UPPER_CASE_LETTERS= to
|
||||
distinguish them from other (normal) symbols and avoid the sort of
|
||||
clash that =CLAUSE3= above illustrates.
|
||||
|
||||
** Compression -- how good is it?
|
||||
|
||||
Here are updated statistics. (I also updated my Google Closure and YUI
|
||||
installations).
|
||||
|
||||
We're still a lot better than YUI in terms of compression, though slightly
|
||||
slower. We're still a lot faster than Closure, and compression after gzip
|
||||
is comparable.
|
||||
|
||||
| File | UglifyJS | UglifyJS+gzip | Closure | Closure+gzip | YUI | YUI+gzip |
|
||||
|-----------------------------+------------------+---------------+------------------+--------------+------------------+----------|
|
||||
| jquery-1.6.2.js | 91001 (0:01.59) | 31896 | 90678 (0:07.40) | 31979 | 101527 (0:01.82) | 34646 |
|
||||
| paper.js | 142023 (0:01.65) | 43334 | 134301 (0:07.42) | 42495 | 173383 (0:01.58) | 48785 |
|
||||
| prototype.js | 88544 (0:01.09) | 26680 | 86955 (0:06.97) | 26326 | 92130 (0:00.79) | 28624 |
|
||||
| thelib-full.js (DynarchLIB) | 251939 (0:02.55) | 72535 | 249911 (0:09.05) | 72696 | 258869 (0:01.94) | 76584 |
|
||||
|
||||
** Bugs?
|
||||
|
||||
Unfortunately, for the time being there is no automated test suite. But I
|
||||
ran the compressor manually on non-trivial code, and then I tested that the
|
||||
generated code works as expected. A few hundred times.
|
||||
|
||||
DynarchLIB was started in times when there was no good JS minifier.
|
||||
Therefore I was quite religious about trying to write short code manually,
|
||||
and as such DL contains a lot of syntactic hacks[1] such as “foo == bar ? a
|
||||
= 10 : b = 20”, though the more readable version would clearly be to use
|
||||
“if/else”.
|
||||
|
||||
Since the parser/compressor runs fine on DL and jQuery, I'm quite confident
|
||||
that it's solid enough for production use. If you can identify any bugs,
|
||||
I'd love to hear about them ([[http://groups.google.com/group/uglifyjs][use the Google Group]] or email me directly).
|
||||
|
||||
[1] I even reported a few bugs and suggested some fixes in the original
|
||||
[[http://marijn.haverbeke.nl/parse-js/][parse-js]] library, and Marijn pushed fixes literally in minutes.
|
||||
|
||||
** Links
|
||||
|
||||
- Twitter: [[http://twitter.com/UglifyJS][@UglifyJS]]
|
||||
- Project at GitHub: [[http://github.com/mishoo/UglifyJS][http://github.com/mishoo/UglifyJS]]
|
||||
- Google Group: [[http://groups.google.com/group/uglifyjs][http://groups.google.com/group/uglifyjs]]
|
||||
- Common Lisp JS parser: [[http://marijn.haverbeke.nl/parse-js/][http://marijn.haverbeke.nl/parse-js/]]
|
||||
- JS-to-Lisp compiler: [[http://github.com/marijnh/js][http://github.com/marijnh/js]]
|
||||
- Common Lisp JS uglifier: [[http://github.com/mishoo/cl-uglify-js][http://github.com/mishoo/cl-uglify-js]]
|
||||
|
||||
** License
|
||||
|
||||
UglifyJS is released under the BSD license:
|
||||
|
||||
#+BEGIN_EXAMPLE
|
||||
Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
|
||||
Based on parse-js (http://marijn.haverbeke.nl/parse-js/).
|
||||
|
||||
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 HOLDER “AS IS” AND ANY
|
||||
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
|
||||
#+END_EXAMPLE
|
|
@ -0,0 +1,332 @@
|
|||
#!/usr/bin/env node
|
||||
// -*- js -*-
|
||||
|
||||
global.sys = require(/^v0\.[012]/.test(process.version) ? "sys" : "util");
|
||||
var fs = require("fs");
|
||||
var uglify = require("uglify-js"), // symlink ~/.node_libraries/uglify-js.js to ../uglify-js.js
|
||||
consolidator = uglify.consolidator,
|
||||
jsp = uglify.parser,
|
||||
pro = uglify.uglify;
|
||||
|
||||
var options = {
|
||||
ast: false,
|
||||
consolidate: false,
|
||||
mangle: true,
|
||||
mangle_toplevel: false,
|
||||
no_mangle_functions: false,
|
||||
squeeze: true,
|
||||
make_seqs: true,
|
||||
dead_code: true,
|
||||
verbose: false,
|
||||
show_copyright: true,
|
||||
out_same_file: false,
|
||||
max_line_length: 32 * 1024,
|
||||
unsafe: false,
|
||||
reserved_names: null,
|
||||
defines: { },
|
||||
lift_vars: false,
|
||||
codegen_options: {
|
||||
ascii_only: false,
|
||||
beautify: false,
|
||||
indent_level: 4,
|
||||
indent_start: 0,
|
||||
quote_keys: false,
|
||||
space_colon: false,
|
||||
inline_script: false
|
||||
},
|
||||
make: false,
|
||||
output: true // stdout
|
||||
};
|
||||
|
||||
var args = jsp.slice(process.argv, 2);
|
||||
var filename;
|
||||
|
||||
out: while (args.length > 0) {
|
||||
var v = args.shift();
|
||||
switch (v) {
|
||||
case "-b":
|
||||
case "--beautify":
|
||||
options.codegen_options.beautify = true;
|
||||
break;
|
||||
case "-c":
|
||||
case "--consolidate-primitive-values":
|
||||
options.consolidate = true;
|
||||
break;
|
||||
case "-i":
|
||||
case "--indent":
|
||||
options.codegen_options.indent_level = args.shift();
|
||||
break;
|
||||
case "-q":
|
||||
case "--quote-keys":
|
||||
options.codegen_options.quote_keys = true;
|
||||
break;
|
||||
case "-mt":
|
||||
case "--mangle-toplevel":
|
||||
options.mangle_toplevel = true;
|
||||
break;
|
||||
case "-nmf":
|
||||
case "--no-mangle-functions":
|
||||
options.no_mangle_functions = true;
|
||||
break;
|
||||
case "--no-mangle":
|
||||
case "-nm":
|
||||
options.mangle = false;
|
||||
break;
|
||||
case "--no-squeeze":
|
||||
case "-ns":
|
||||
options.squeeze = false;
|
||||
break;
|
||||
case "--no-seqs":
|
||||
options.make_seqs = false;
|
||||
break;
|
||||
case "--no-dead-code":
|
||||
options.dead_code = false;
|
||||
break;
|
||||
case "--no-copyright":
|
||||
case "-nc":
|
||||
options.show_copyright = false;
|
||||
break;
|
||||
case "-o":
|
||||
case "--output":
|
||||
options.output = args.shift();
|
||||
break;
|
||||
case "--overwrite":
|
||||
options.out_same_file = true;
|
||||
break;
|
||||
case "-v":
|
||||
case "--verbose":
|
||||
options.verbose = true;
|
||||
break;
|
||||
case "--ast":
|
||||
options.ast = true;
|
||||
break;
|
||||
case "--unsafe":
|
||||
options.unsafe = true;
|
||||
break;
|
||||
case "--max-line-len":
|
||||
options.max_line_length = parseInt(args.shift(), 10);
|
||||
break;
|
||||
case "--reserved-names":
|
||||
options.reserved_names = args.shift().split(",");
|
||||
break;
|
||||
case "--lift-vars":
|
||||
options.lift_vars = true;
|
||||
break;
|
||||
case "-d":
|
||||
case "--define":
|
||||
var defarg = args.shift();
|
||||
try {
|
||||
var defsym = function(sym) {
|
||||
// KEYWORDS_ATOM doesn't include NaN or Infinity - should we check
|
||||
// for them too ?? We don't check reserved words and the like as the
|
||||
// define values are only substituted AFTER parsing
|
||||
if (jsp.KEYWORDS_ATOM.hasOwnProperty(sym)) {
|
||||
throw "Don't define values for inbuilt constant '"+sym+"'";
|
||||
}
|
||||
return sym;
|
||||
},
|
||||
defval = function(v) {
|
||||
if (v.match(/^"(.*)"$/) || v.match(/^'(.*)'$/)) {
|
||||
return [ "string", RegExp.$1 ];
|
||||
}
|
||||
else if (!isNaN(parseFloat(v))) {
|
||||
return [ "num", parseFloat(v) ];
|
||||
}
|
||||
else if (v.match(/^[a-z\$_][a-z\$_0-9]*$/i)) {
|
||||
return [ "name", v ];
|
||||
}
|
||||
else if (!v.match(/"/)) {
|
||||
return [ "string", v ];
|
||||
}
|
||||
else if (!v.match(/'/)) {
|
||||
return [ "string", v ];
|
||||
}
|
||||
throw "Can't understand the specified value: "+v;
|
||||
};
|
||||
if (defarg.match(/^([a-z_\$][a-z_\$0-9]*)(=(.*))?$/i)) {
|
||||
var sym = defsym(RegExp.$1),
|
||||
val = RegExp.$2 ? defval(RegExp.$2.substr(1)) : [ 'name', 'true' ];
|
||||
options.defines[sym] = val;
|
||||
}
|
||||
else {
|
||||
throw "The --define option expects SYMBOL[=value]";
|
||||
}
|
||||
} catch(ex) {
|
||||
sys.print("ERROR: In option --define "+defarg+"\n"+ex+"\n");
|
||||
process.exit(1);
|
||||
}
|
||||
break;
|
||||
case "--define-from-module":
|
||||
var defmodarg = args.shift(),
|
||||
defmodule = require(defmodarg),
|
||||
sym,
|
||||
val;
|
||||
for (sym in defmodule) {
|
||||
if (defmodule.hasOwnProperty(sym)) {
|
||||
options.defines[sym] = function(val) {
|
||||
if (typeof val == "string")
|
||||
return [ "string", val ];
|
||||
if (typeof val == "number")
|
||||
return [ "num", val ];
|
||||
if (val === true)
|
||||
return [ 'name', 'true' ];
|
||||
if (val === false)
|
||||
return [ 'name', 'false' ];
|
||||
if (val === null)
|
||||
return [ 'name', 'null' ];
|
||||
if (val === undefined)
|
||||
return [ 'name', 'undefined' ];
|
||||
sys.print("ERROR: In option --define-from-module "+defmodarg+"\n");
|
||||
sys.print("ERROR: Unknown object type for: "+sym+"="+val+"\n");
|
||||
process.exit(1);
|
||||
return null;
|
||||
}(defmodule[sym]);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "--ascii":
|
||||
options.codegen_options.ascii_only = true;
|
||||
break;
|
||||
case "--make":
|
||||
options.make = true;
|
||||
break;
|
||||
case "--inline-script":
|
||||
options.codegen_options.inline_script = true;
|
||||
break;
|
||||
default:
|
||||
filename = v;
|
||||
break out;
|
||||
}
|
||||
}
|
||||
|
||||
if (options.verbose) {
|
||||
pro.set_logger(function(msg){
|
||||
sys.debug(msg);
|
||||
});
|
||||
}
|
||||
|
||||
jsp.set_logger(function(msg){
|
||||
sys.debug(msg);
|
||||
});
|
||||
|
||||
if (options.make) {
|
||||
options.out_same_file = false; // doesn't make sense in this case
|
||||
var makefile = JSON.parse(fs.readFileSync(filename || "Makefile.uglify.js").toString());
|
||||
output(makefile.files.map(function(file){
|
||||
var code = fs.readFileSync(file.name);
|
||||
if (file.module) {
|
||||
code = "!function(exports, global){global = this;\n" + code + "\n;this." + file.module + " = exports;}({})";
|
||||
}
|
||||
else if (file.hide) {
|
||||
code = "(function(){" + code + "}());";
|
||||
}
|
||||
return squeeze_it(code);
|
||||
}).join("\n"));
|
||||
}
|
||||
else if (filename) {
|
||||
fs.readFile(filename, "utf8", function(err, text){
|
||||
if (err) throw err;
|
||||
output(squeeze_it(text));
|
||||
});
|
||||
}
|
||||
else {
|
||||
var stdin = process.openStdin();
|
||||
stdin.setEncoding("utf8");
|
||||
var text = "";
|
||||
stdin.on("data", function(chunk){
|
||||
text += chunk;
|
||||
});
|
||||
stdin.on("end", function() {
|
||||
output(squeeze_it(text));
|
||||
});
|
||||
}
|
||||
|
||||
function output(text) {
|
||||
var out;
|
||||
if (options.out_same_file && filename)
|
||||
options.output = filename;
|
||||
if (options.output === true) {
|
||||
out = process.stdout;
|
||||
} else {
|
||||
out = fs.createWriteStream(options.output, {
|
||||
flags: "w",
|
||||
encoding: "utf8",
|
||||
mode: 0644
|
||||
});
|
||||
}
|
||||
out.write(text.replace(/;*$/, ";"));
|
||||
if (options.output !== true) {
|
||||
out.end();
|
||||
}
|
||||
};
|
||||
|
||||
// --------- main ends here.
|
||||
|
||||
function show_copyright(comments) {
|
||||
var ret = "";
|
||||
for (var i = 0; i < comments.length; ++i) {
|
||||
var c = comments[i];
|
||||
if (c.type == "comment1") {
|
||||
ret += "//" + c.value + "\n";
|
||||
} else {
|
||||
ret += "/*" + c.value + "*/";
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
|
||||
function squeeze_it(code) {
|
||||
var result = "";
|
||||
if (options.show_copyright) {
|
||||
var tok = jsp.tokenizer(code), c;
|
||||
c = tok();
|
||||
result += show_copyright(c.comments_before);
|
||||
}
|
||||
try {
|
||||
var ast = time_it("parse", function(){ return jsp.parse(code); });
|
||||
if (options.consolidate) ast = time_it("consolidate", function(){
|
||||
return consolidator.ast_consolidate(ast);
|
||||
});
|
||||
if (options.lift_vars) {
|
||||
ast = time_it("lift", function(){ return pro.ast_lift_variables(ast); });
|
||||
}
|
||||
if (options.mangle) ast = time_it("mangle", function(){
|
||||
return pro.ast_mangle(ast, {
|
||||
toplevel : options.mangle_toplevel,
|
||||
defines : options.defines,
|
||||
except : options.reserved_names,
|
||||
no_functions : options.no_mangle_functions
|
||||
});
|
||||
});
|
||||
if (options.squeeze) ast = time_it("squeeze", function(){
|
||||
ast = pro.ast_squeeze(ast, {
|
||||
make_seqs : options.make_seqs,
|
||||
dead_code : options.dead_code,
|
||||
keep_comps : !options.unsafe
|
||||
});
|
||||
if (options.unsafe)
|
||||
ast = pro.ast_squeeze_more(ast);
|
||||
return ast;
|
||||
});
|
||||
if (options.ast)
|
||||
return sys.inspect(ast, null, null);
|
||||
result += time_it("generate", function(){ return pro.gen_code(ast, options.codegen_options) });
|
||||
if (!options.codegen_options.beautify && options.max_line_length) {
|
||||
result = time_it("split", function(){ return pro.split_lines(result, options.max_line_length) });
|
||||
}
|
||||
return result;
|
||||
} catch(ex) {
|
||||
sys.debug(ex.stack);
|
||||
sys.debug(sys.inspect(ex));
|
||||
sys.debug(JSON.stringify(ex));
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
function time_it(name, cont) {
|
||||
if (!options.verbose)
|
||||
return cont();
|
||||
var t1 = new Date().getTime();
|
||||
try { return cont(); }
|
||||
finally { sys.debug("// " + name + ": " + ((new Date().getTime() - t1) / 1000).toFixed(3) + " sec."); }
|
||||
};
|
|
@ -0,0 +1,75 @@
|
|||
html { font-family: "Lucida Grande","Trebuchet MS",sans-serif; font-size: 12pt; }
|
||||
body { max-width: 60em; }
|
||||
.title { text-align: center; }
|
||||
.todo { color: red; }
|
||||
.done { color: green; }
|
||||
.tag { background-color:lightblue; font-weight:normal }
|
||||
.target { }
|
||||
.timestamp { color: grey }
|
||||
.timestamp-kwd { color: CadetBlue }
|
||||
p.verse { margin-left: 3% }
|
||||
pre {
|
||||
border: 1pt solid #AEBDCC;
|
||||
background-color: #F3F5F7;
|
||||
padding: 5pt;
|
||||
font-family: monospace;
|
||||
font-size: 90%;
|
||||
overflow:auto;
|
||||
}
|
||||
pre.src {
|
||||
background-color: #eee; color: #112; border: 1px solid #000;
|
||||
}
|
||||
table { border-collapse: collapse; }
|
||||
td, th { vertical-align: top; }
|
||||
dt { font-weight: bold; }
|
||||
div.figure { padding: 0.5em; }
|
||||
div.figure p { text-align: center; }
|
||||
.linenr { font-size:smaller }
|
||||
.code-highlighted {background-color:#ffff00;}
|
||||
.org-info-js_info-navigation { border-style:none; }
|
||||
#org-info-js_console-label { font-size:10px; font-weight:bold;
|
||||
white-space:nowrap; }
|
||||
.org-info-js_search-highlight {background-color:#ffff00; color:#000000;
|
||||
font-weight:bold; }
|
||||
|
||||
sup {
|
||||
vertical-align: baseline;
|
||||
position: relative;
|
||||
top: -0.5em;
|
||||
font-size: 80%;
|
||||
}
|
||||
|
||||
sup a:link, sup a:visited {
|
||||
text-decoration: none;
|
||||
color: #c00;
|
||||
}
|
||||
|
||||
sup a:before { content: "["; color: #999; }
|
||||
sup a:after { content: "]"; color: #999; }
|
||||
|
||||
h1.title { border-bottom: 4px solid #000; padding-bottom: 5px; margin-bottom: 2em; }
|
||||
|
||||
#postamble {
|
||||
color: #777;
|
||||
font-size: 90%;
|
||||
padding-top: 1em; padding-bottom: 1em; border-top: 1px solid #999;
|
||||
margin-top: 2em;
|
||||
padding-left: 2em;
|
||||
padding-right: 2em;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
#postamble p { margin: 0; }
|
||||
|
||||
#footnotes { border-top: 1px solid #000; }
|
||||
|
||||
h1 { font-size: 200% }
|
||||
h2 { font-size: 175% }
|
||||
h3 { font-size: 150% }
|
||||
h4 { font-size: 125% }
|
||||
|
||||
h1, h2, h3, h4 { font-family: "Bookman",Georgia,"Times New Roman",serif; font-weight: normal; }
|
||||
|
||||
@media print {
|
||||
html { font-size: 11pt; }
|
||||
}
|
2599
node_modules/handlebars/node_modules/uglify-js/lib/consolidator.js
generated
vendored
Normal file
2599
node_modules/handlebars/node_modules/uglify-js/lib/consolidator.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,75 @@
|
|||
var jsp = require("./parse-js"),
|
||||
pro = require("./process");
|
||||
|
||||
var BY_TYPE = {};
|
||||
|
||||
function HOP(obj, prop) {
|
||||
return Object.prototype.hasOwnProperty.call(obj, prop);
|
||||
};
|
||||
|
||||
function AST_Node(parent) {
|
||||
this.parent = parent;
|
||||
};
|
||||
|
||||
AST_Node.prototype.init = function(){};
|
||||
|
||||
function DEFINE_NODE_CLASS(type, props, methods) {
|
||||
var base = methods && methods.BASE || AST_Node;
|
||||
if (!base) base = AST_Node;
|
||||
function D(parent, data) {
|
||||
base.apply(this, arguments);
|
||||
if (props) props.forEach(function(name, i){
|
||||
this["_" + name] = data[i];
|
||||
});
|
||||
this.init();
|
||||
};
|
||||
var P = D.prototype = new AST_Node;
|
||||
P.node_type = function(){ return type };
|
||||
if (props) props.forEach(function(name){
|
||||
var propname = "_" + name;
|
||||
P["set_" + name] = function(val) {
|
||||
this[propname] = val;
|
||||
return this;
|
||||
};
|
||||
P["get_" + name] = function() {
|
||||
return this[propname];
|
||||
};
|
||||
});
|
||||
if (type != null) BY_TYPE[type] = D;
|
||||
if (methods) for (var i in methods) if (HOP(methods, i)) {
|
||||
P[i] = methods[i];
|
||||
}
|
||||
return D;
|
||||
};
|
||||
|
||||
var AST_String_Node = DEFINE_NODE_CLASS("string", ["value"]);
|
||||
var AST_Number_Node = DEFINE_NODE_CLASS("num", ["value"]);
|
||||
var AST_Name_Node = DEFINE_NODE_CLASS("name", ["value"]);
|
||||
|
||||
var AST_Statlist_Node = DEFINE_NODE_CLASS(null, ["body"]);
|
||||
var AST_Root_Node = DEFINE_NODE_CLASS("toplevel", null, { BASE: AST_Statlist_Node });
|
||||
var AST_Block_Node = DEFINE_NODE_CLASS("block", null, { BASE: AST_Statlist_Node });
|
||||
var AST_Splice_Node = DEFINE_NODE_CLASS("splice", null, { BASE: AST_Statlist_Node });
|
||||
|
||||
var AST_Var_Node = DEFINE_NODE_CLASS("var", ["definitions"]);
|
||||
var AST_Const_Node = DEFINE_NODE_CLASS("const", ["definitions"]);
|
||||
|
||||
var AST_Try_Node = DEFINE_NODE_CLASS("try", ["body", "catch", "finally"]);
|
||||
var AST_Throw_Node = DEFINE_NODE_CLASS("throw", ["exception"]);
|
||||
|
||||
var AST_New_Node = DEFINE_NODE_CLASS("new", ["constructor", "arguments"]);
|
||||
|
||||
var AST_Switch_Node = DEFINE_NODE_CLASS("switch", ["expression", "branches"]);
|
||||
var AST_Switch_Branch_Node = DEFINE_NODE_CLASS(null, ["expression", "body"]);
|
||||
|
||||
var AST_Break_Node = DEFINE_NODE_CLASS("break", ["label"]);
|
||||
var AST_Continue_Node = DEFINE_NODE_CLASS("continue", ["label"]);
|
||||
var AST_Assign_Node = DEFINE_NODE_CLASS("assign", ["operator", "lvalue", "rvalue"]);
|
||||
var AST_Dot_Node = DEFINE_NODE_CLASS("dot", ["expression", "name"]);
|
||||
var AST_Call_Node = DEFINE_NODE_CLASS("call", ["function", "arguments"]);
|
||||
|
||||
var AST_Lambda_Node = DEFINE_NODE_CLASS(null, ["name", "arguments", "body"])
|
||||
var AST_Function_Node = DEFINE_NODE_CLASS("function", null, AST_Lambda_Node);
|
||||
var AST_Defun_Node = DEFINE_NODE_CLASS("defun", null, AST_Lambda_Node);
|
||||
|
||||
var AST_If_Node = DEFINE_NODE_CLASS("if", ["condition", "then", "else"]);
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
73
node_modules/handlebars/node_modules/uglify-js/lib/squeeze-more.js
generated
vendored
Normal file
73
node_modules/handlebars/node_modules/uglify-js/lib/squeeze-more.js
generated
vendored
Normal file
|
@ -0,0 +1,73 @@
|
|||
var jsp = require("./parse-js"),
|
||||
pro = require("./process"),
|
||||
slice = jsp.slice,
|
||||
member = jsp.member,
|
||||
curry = jsp.curry,
|
||||
MAP = pro.MAP,
|
||||
PRECEDENCE = jsp.PRECEDENCE,
|
||||
OPERATORS = jsp.OPERATORS;
|
||||
|
||||
function ast_squeeze_more(ast) {
|
||||
var w = pro.ast_walker(), walk = w.walk, scope;
|
||||
function with_scope(s, cont) {
|
||||
var save = scope, ret;
|
||||
scope = s;
|
||||
ret = cont();
|
||||
scope = save;
|
||||
return ret;
|
||||
};
|
||||
function _lambda(name, args, body) {
|
||||
return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ];
|
||||
};
|
||||
return w.with_walkers({
|
||||
"toplevel": function(body) {
|
||||
return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ];
|
||||
},
|
||||
"function": _lambda,
|
||||
"defun": _lambda,
|
||||
"new": function(ctor, args) {
|
||||
if (ctor[0] == "name") {
|
||||
if (ctor[1] == "Array" && !scope.has("Array")) {
|
||||
if (args.length != 1) {
|
||||
return [ "array", args ];
|
||||
} else {
|
||||
return walk([ "call", [ "name", "Array" ], args ]);
|
||||
}
|
||||
} else if (ctor[1] == "Object" && !scope.has("Object")) {
|
||||
if (!args.length) {
|
||||
return [ "object", [] ];
|
||||
} else {
|
||||
return walk([ "call", [ "name", "Object" ], args ]);
|
||||
}
|
||||
} else if ((ctor[1] == "RegExp" || ctor[1] == "Function" || ctor[1] == "Error") && !scope.has(ctor[1])) {
|
||||
return walk([ "call", [ "name", ctor[1] ], args]);
|
||||
}
|
||||
}
|
||||
},
|
||||
"call": function(expr, args) {
|
||||
if (expr[0] == "dot" && expr[1][0] == "string" && args.length == 1
|
||||
&& (args[0][1] > 0 && expr[2] == "substring" || expr[2] == "substr")) {
|
||||
return [ "call", [ "dot", expr[1], "slice"], args];
|
||||
}
|
||||
if (expr[0] == "dot" && expr[2] == "toString" && args.length == 0) {
|
||||
// foo.toString() ==> foo+""
|
||||
return [ "binary", "+", expr[1], [ "string", "" ]];
|
||||
}
|
||||
if (expr[0] == "name") {
|
||||
if (expr[1] == "Array" && args.length != 1 && !scope.has("Array")) {
|
||||
return [ "array", args ];
|
||||
}
|
||||
if (expr[1] == "Object" && !args.length && !scope.has("Object")) {
|
||||
return [ "object", [] ];
|
||||
}
|
||||
if (expr[1] == "String" && !scope.has("String")) {
|
||||
return [ "binary", "+", args[0], [ "string", "" ]];
|
||||
}
|
||||
}
|
||||
}
|
||||
}, function() {
|
||||
return walk(pro.ast_add_scope(ast));
|
||||
});
|
||||
};
|
||||
|
||||
exports.ast_squeeze_more = ast_squeeze_more;
|
|
@ -0,0 +1,30 @@
|
|||
{
|
||||
"name": "uglify-js",
|
||||
"description": "JavaScript parser and compressor/beautifier toolkit",
|
||||
"author": {
|
||||
"name": "Mihai Bazon",
|
||||
"email": "mihai.bazon@gmail.com",
|
||||
"url": "http://mihai.bazon.net/blog"
|
||||
},
|
||||
"version": "1.2.6",
|
||||
"main": "./uglify-js.js",
|
||||
"bin": {
|
||||
"uglifyjs": "./bin/uglifyjs"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git@github.com:mishoo/UglifyJS.git"
|
||||
},
|
||||
"_id": "uglify-js@1.2.6",
|
||||
"dependencies": {},
|
||||
"devDependencies": {},
|
||||
"optionalDependencies": {},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
},
|
||||
"_engineSupported": true,
|
||||
"_npmVersion": "1.1.4",
|
||||
"_nodeVersion": "v0.6.19",
|
||||
"_defaultsLoaded": true,
|
||||
"_from": "uglify-js@~1.2"
|
||||
}
|
28
node_modules/handlebars/node_modules/uglify-js/test/beautify.js
generated
vendored
Executable file
28
node_modules/handlebars/node_modules/uglify-js/test/beautify.js
generated
vendored
Executable file
|
@ -0,0 +1,28 @@
|
|||
#! /usr/bin/env node
|
||||
|
||||
global.sys = require("sys");
|
||||
var fs = require("fs");
|
||||
|
||||
var jsp = require("../lib/parse-js");
|
||||
var pro = require("../lib/process");
|
||||
|
||||
var filename = process.argv[2];
|
||||
fs.readFile(filename, "utf8", function(err, text){
|
||||
try {
|
||||
var ast = time_it("parse", function(){ return jsp.parse(text); });
|
||||
ast = time_it("mangle", function(){ return pro.ast_mangle(ast); });
|
||||
ast = time_it("squeeze", function(){ return pro.ast_squeeze(ast); });
|
||||
var gen = time_it("generate", function(){ return pro.gen_code(ast, false); });
|
||||
sys.puts(gen);
|
||||
} catch(ex) {
|
||||
sys.debug(ex.stack);
|
||||
sys.debug(sys.inspect(ex));
|
||||
sys.debug(JSON.stringify(ex));
|
||||
}
|
||||
});
|
||||
|
||||
function time_it(name, cont) {
|
||||
var t1 = new Date().getTime();
|
||||
try { return cont(); }
|
||||
finally { sys.debug("// " + name + ": " + ((new Date().getTime() - t1) / 1000).toFixed(3) + " sec."); }
|
||||
};
|
403
node_modules/handlebars/node_modules/uglify-js/test/testparser.js
generated
vendored
Executable file
403
node_modules/handlebars/node_modules/uglify-js/test/testparser.js
generated
vendored
Executable file
|
@ -0,0 +1,403 @@
|
|||
#! /usr/bin/env node
|
||||
|
||||
var parseJS = require("../lib/parse-js");
|
||||
var sys = require("sys");
|
||||
|
||||
// write debug in a very straightforward manner
|
||||
var debug = function(){
|
||||
sys.log(Array.prototype.slice.call(arguments).join(', '));
|
||||
};
|
||||
|
||||
ParserTestSuite(function(i, input, desc){
|
||||
try {
|
||||
parseJS.parse(input);
|
||||
debug("ok " + i + ": " + desc);
|
||||
} catch(e){
|
||||
debug("FAIL " + i + " " + desc + " (" + e + ")");
|
||||
}
|
||||
});
|
||||
|
||||
function ParserTestSuite(callback){
|
||||
var inps = [
|
||||
["var abc;", "Regular variable statement w/o assignment"],
|
||||
["var abc = 5;", "Regular variable statement with assignment"],
|
||||
["/* */;", "Multiline comment"],
|
||||
['/** **/;', 'Double star multiline comment'],
|
||||
["var f = function(){;};", "Function expression in var assignment"],
|
||||
['hi; // moo\n;', 'single line comment'],
|
||||
['var varwithfunction;', 'Dont match keywords as substrings'], // difference between `var withsomevar` and `"str"` (local search and lits)
|
||||
['a + b;', 'addition'],
|
||||
["'a';", 'single string literal'],
|
||||
["'a\\n';", 'single string literal with escaped return'],
|
||||
['"a";', 'double string literal'],
|
||||
['"a\\n";', 'double string literal with escaped return'],
|
||||
['"var";', 'string is a keyword'],
|
||||
['"variable";', 'string starts with a keyword'],
|
||||
['"somevariable";', 'string contains a keyword'],
|
||||
['"somevar";', 'string ends with a keyword'],
|
||||
['500;', 'int literal'],
|
||||
['500.;', 'float literal w/o decimals'],
|
||||
['500.432;', 'float literal with decimals'],
|
||||
['.432432;', 'float literal w/o int'],
|
||||
['(a,b,c);', 'parens and comma'],
|
||||
['[1,2,abc];', 'array literal'],
|
||||
['var o = {a:1};', 'object literal unquoted key'],
|
||||
['var o = {"b":2};', 'object literal quoted key'], // opening curly may not be at the start of a statement...
|
||||
['var o = {c:c};', 'object literal keyname is identifier'],
|
||||
['var o = {a:1,"b":2,c:c};', 'object literal combinations'],
|
||||
['var x;\nvar y;', 'two lines'],
|
||||
['var x;\nfunction n(){; }', 'function def'],
|
||||
['var x;\nfunction n(abc){; }', 'function def with arg'],
|
||||
['var x;\nfunction n(abc, def){ ;}', 'function def with args'],
|
||||
['function n(){ "hello"; }', 'function def with body'],
|
||||
['/a/;', 'regex literal'],
|
||||
['/a/b;', 'regex literal with flag'],
|
||||
['/a/ / /b/;', 'regex div regex'],
|
||||
['a/b/c;', 'triple division looks like regex'],
|
||||
['+function(){/regex/;};', 'regex at start of function body'],
|
||||
// http://code.google.com/p/es-lab/source/browse/trunk/tests/parser/parsertests.js?r=86
|
||||
// http://code.google.com/p/es-lab/source/browse/trunk/tests/parser/parsertests.js?r=430
|
||||
|
||||
// first tests for the lexer, should also parse as program (when you append a semi)
|
||||
|
||||
// comments
|
||||
['//foo!@#^&$1234\nbar;', 'single line comment'],
|
||||
['/* abcd!@#@$* { } && null*/;', 'single line multi line comment'],
|
||||
['/*foo\nbar*/;','multi line comment'],
|
||||
['/*x*x*/;','multi line comment with *'],
|
||||
['/**/;','empty comment'],
|
||||
// identifiers
|
||||
["x;",'1 identifier'],
|
||||
["_x;",'2 identifier'],
|
||||
["xyz;",'3 identifier'],
|
||||
["$x;",'4 identifier'],
|
||||
["x$;",'5 identifier'],
|
||||
["_;",'6 identifier'],
|
||||
["x5;",'7 identifier'],
|
||||
["x_y;",'8 identifier'],
|
||||
["x+5;",'9 identifier'],
|
||||
["xyz123;",'10 identifier'],
|
||||
["x1y1z1;",'11 identifier'],
|
||||
["foo\\u00D8bar;",'12 identifier unicode escape'],
|
||||
//["foo<6F>bar;",'13 identifier unicode embedded (might fail)'],
|
||||
// numbers
|
||||
["5;", '1 number'],
|
||||
["5.5;", '2 number'],
|
||||
["0;", '3 number'],
|
||||
["0.0;", '4 number'],
|
||||
["0.001;", '5 number'],
|
||||
["1.e2;", '6 number'],
|
||||
["1.e-2;", '7 number'],
|
||||
["1.E2;", '8 number'],
|
||||
["1.E-2;", '9 number'],
|
||||
[".5;", '10 number'],
|
||||
[".5e3;", '11 number'],
|
||||
[".5e-3;", '12 number'],
|
||||
["0.5e3;", '13 number'],
|
||||
["55;", '14 number'],
|
||||
["123;", '15 number'],
|
||||
["55.55;", '16 number'],
|
||||
["55.55e10;", '17 number'],
|
||||
["123.456;", '18 number'],
|
||||
["1+e;", '20 number'],
|
||||
["0x01;", '22 number'],
|
||||
["0XCAFE;", '23 number'],
|
||||
["0x12345678;", '24 number'],
|
||||
["0x1234ABCD;", '25 number'],
|
||||
["0x0001;", '26 number'],
|
||||
// strings
|
||||
["\"foo\";", '1 string'],
|
||||
["\'foo\';", '2 string'],
|
||||
["\"x\";", '3 string'],
|
||||
["\'\';", '4 string'],
|
||||
["\"foo\\tbar\";", '5 string'],
|
||||
["\"!@#$%^&*()_+{}[]\";", '6 string'],
|
||||
["\"/*test*/\";", '7 string'],
|
||||
["\"//test\";", '8 string'],
|
||||
["\"\\\\\";", '9 string'],
|
||||
["\"\\u0001\";", '10 string'],
|
||||
["\"\\uFEFF\";", '11 string'],
|
||||
["\"\\u10002\";", '12 string'],
|
||||
["\"\\x55\";", '13 string'],
|
||||
["\"\\x55a\";", '14 string'],
|
||||
["\"a\\\\nb\";", '15 string'],
|
||||
['";"', '16 string: semi in a string'],
|
||||
['"a\\\nb";', '17 string: line terminator escape'],
|
||||
// literals
|
||||
["null;", "null"],
|
||||
["true;", "true"],
|
||||
["false;", "false"],
|
||||
// regex
|
||||
["/a/;", "1 regex"],
|
||||
["/abc/;", "2 regex"],
|
||||
["/abc[a-z]*def/g;", "3 regex"],
|
||||
["/\\b/;", "4 regex"],
|
||||
["/[a-zA-Z]/;", "5 regex"],
|
||||
|
||||
// program tests (for as far as they havent been covered above)
|
||||
|
||||
// regexp
|
||||
["/foo(.*)/g;", "another regexp"],
|
||||
// arrays
|
||||
["[];", "1 array"],
|
||||
["[ ];", "2 array"],
|
||||
["[1];", "3 array"],
|
||||
["[1,2];", "4 array"],
|
||||
["[1,2,,];", "5 array"],
|
||||
["[1,2,3];", "6 array"],
|
||||
["[1,2,3,,,];", "7 array"],
|
||||
// objects
|
||||
["{};", "1 object"],
|
||||
["({x:5});", "2 object"],
|
||||
["({x:5,y:6});", "3 object"],
|
||||
["({x:5,});", "4 object"],
|
||||
["({if:5});", "5 object"],
|
||||
["({ get x() {42;} });", "6 object"],
|
||||
["({ set y(a) {1;} });", "7 object"],
|
||||
// member expression
|
||||
["o.m;", "1 member expression"],
|
||||
["o['m'];", "2 member expression"],
|
||||
["o['n']['m'];", "3 member expression"],
|
||||
["o.n.m;", "4 member expression"],
|
||||
["o.if;", "5 member expression"],
|
||||
// call and invoke expressions
|
||||
["f();", "1 call/invoke expression"],
|
||||
["f(x);", "2 call/invoke expression"],
|
||||
["f(x,y);", "3 call/invoke expression"],
|
||||
["o.m();", "4 call/invoke expression"],
|
||||
["o['m'];", "5 call/invoke expression"],
|
||||
["o.m(x);", "6 call/invoke expression"],
|
||||
["o['m'](x);", "7 call/invoke expression"],
|
||||
["o.m(x,y);", "8 call/invoke expression"],
|
||||
["o['m'](x,y);", "9 call/invoke expression"],
|
||||
["f(x)(y);", "10 call/invoke expression"],
|
||||
["f().x;", "11 call/invoke expression"],
|
||||
|
||||
// eval
|
||||
["eval('x');", "1 eval"],
|
||||
["(eval)('x');", "2 eval"],
|
||||
["(1,eval)('x');", "3 eval"],
|
||||
["eval(x,y);", "4 eval"],
|
||||
// new expression
|
||||
["new f();", "1 new expression"],
|
||||
["new o;", "2 new expression"],
|
||||
["new o.m;", "3 new expression"],
|
||||
["new o.m(x);", "4 new expression"],
|
||||
["new o.m(x,y);", "5 new expression"],
|
||||
// prefix/postfix
|
||||
["++x;", "1 pre/postfix"],
|
||||
["x++;", "2 pre/postfix"],
|
||||
["--x;", "3 pre/postfix"],
|
||||
["x--;", "4 pre/postfix"],
|
||||
["x ++;", "5 pre/postfix"],
|
||||
["x /* comment */ ++;", "6 pre/postfix"],
|
||||
["++ /* comment */ x;", "7 pre/postfix"],
|
||||
// unary operators
|
||||
["delete x;", "1 unary operator"],
|
||||
["void x;", "2 unary operator"],
|
||||
["+ x;", "3 unary operator"],
|
||||
["-x;", "4 unary operator"],
|
||||
["~x;", "5 unary operator"],
|
||||
["!x;", "6 unary operator"],
|
||||
// meh
|
||||
["new Date++;", "new date ++"],
|
||||
["+x++;", " + x ++"],
|
||||
// expression expressions
|
||||
["1 * 2;", "1 expression expressions"],
|
||||
["1 / 2;", "2 expression expressions"],
|
||||
["1 % 2;", "3 expression expressions"],
|
||||
["1 + 2;", "4 expression expressions"],
|
||||
["1 - 2;", "5 expression expressions"],
|
||||
["1 << 2;", "6 expression expressions"],
|
||||
["1 >>> 2;", "7 expression expressions"],
|
||||
["1 >> 2;", "8 expression expressions"],
|
||||
["1 * 2 + 3;", "9 expression expressions"],
|
||||
["(1+2)*3;", "10 expression expressions"],
|
||||
["1*(2+3);", "11 expression expressions"],
|
||||
["x<y;", "12 expression expressions"],
|
||||
["x>y;", "13 expression expressions"],
|
||||
["x<=y;", "14 expression expressions"],
|
||||
["x>=y;", "15 expression expressions"],
|
||||
["x instanceof y;", "16 expression expressions"],
|
||||
["x in y;", "17 expression expressions"],
|
||||
["x&y;", "18 expression expressions"],
|
||||
["x^y;", "19 expression expressions"],
|
||||
["x|y;", "20 expression expressions"],
|
||||
["x+y<z;", "21 expression expressions"],
|
||||
["x<y+z;", "22 expression expressions"],
|
||||
["x+y+z;", "23 expression expressions"],
|
||||
["x+y<z;", "24 expression expressions"],
|
||||
["x<y+z;", "25 expression expressions"],
|
||||
["x&y|z;", "26 expression expressions"],
|
||||
["x&&y;", "27 expression expressions"],
|
||||
["x||y;", "28 expression expressions"],
|
||||
["x&&y||z;", "29 expression expressions"],
|
||||
["x||y&&z;", "30 expression expressions"],
|
||||
["x<y?z:w;", "31 expression expressions"],
|
||||
// assignment
|
||||
["x >>>= y;", "1 assignment"],
|
||||
["x <<= y;", "2 assignment"],
|
||||
["x = y;", "3 assignment"],
|
||||
["x += y;", "4 assignment"],
|
||||
["x /= y;", "5 assignment"],
|
||||
// comma
|
||||
["x, y;", "comma"],
|
||||
// block
|
||||
["{};", "1 block"],
|
||||
["{x;};", "2 block"],
|
||||
["{x;y;};", "3 block"],
|
||||
// vars
|
||||
["var x;", "1 var"],
|
||||
["var x,y;", "2 var"],
|
||||
["var x=1,y=2;", "3 var"],
|
||||
["var x,y=2;", "4 var"],
|
||||
// empty
|
||||
[";", "1 empty"],
|
||||
["\n;", "2 empty"],
|
||||
// expression statement
|
||||
["x;", "1 expression statement"],
|
||||
["5;", "2 expression statement"],
|
||||
["1+2;", "3 expression statement"],
|
||||
// if
|
||||
["if (c) x; else y;", "1 if statement"],
|
||||
["if (c) x;", "2 if statement"],
|
||||
["if (c) {} else {};", "3 if statement"],
|
||||
["if (c1) if (c2) s1; else s2;", "4 if statement"],
|
||||
// while
|
||||
["do s; while (e);", "1 while statement"],
|
||||
["do { s; } while (e);", "2 while statement"],
|
||||
["while (e) s;", "3 while statement"],
|
||||
["while (e) { s; };", "4 while statement"],
|
||||
// for
|
||||
["for (;;) ;", "1 for statement"],
|
||||
["for (;c;x++) x;", "2 for statement"],
|
||||
["for (i;i<len;++i){};", "3 for statement"],
|
||||
["for (var i=0;i<len;++i) {};", "4 for statement"],
|
||||
["for (var i=0,j=0;;){};", "5 for statement"],
|
||||
//["for (x in b; c; u) {};", "6 for statement"],
|
||||
["for ((x in b); c; u) {};", "7 for statement"],
|
||||
["for (x in a);", "8 for statement"],
|
||||
["for (var x in a){};", "9 for statement"],
|
||||
["for (var x=5 in a) {};", "10 for statement"],
|
||||
["for (var x = a in b in c) {};", "11 for statement"],
|
||||
["for (var x=function(){a+b;}; a<b; ++i) some;", "11 for statement, testing for parsingForHeader reset with the function"],
|
||||
["for (var x=function(){for (x=0; x<15; ++x) alert(foo); }; a<b; ++i) some;", "11 for statement, testing for parsingForHeader reset with the function"],
|
||||
// flow statements
|
||||
["while(1){ continue; }", "1 flow statement"],
|
||||
["label: while(1){ continue label; }", "2 flow statement"],
|
||||
["while(1){ break; }", "3 flow statement"],
|
||||
["somewhere: while(1){ break somewhere; }", "4 flow statement"],
|
||||
["while(1){ continue /* comment */ ; }", "5 flow statement"],
|
||||
["while(1){ continue \n; }", "6 flow statement"],
|
||||
["(function(){ return; })()", "7 flow statement"],
|
||||
["(function(){ return 0; })()", "8 flow statement"],
|
||||
["(function(){ return 0 + \n 1; })()", "9 flow statement"],
|
||||
// with
|
||||
["with (e) s;", "with statement"],
|
||||
// switch
|
||||
["switch (e) { case x: s; };", "1 switch statement"],
|
||||
["switch (e) { case x: s1;s2; default: s3; case y: s4; };", "2 switch statement"],
|
||||
["switch (e) { default: s1; case x: s2; case y: s3; };", "3 switch statement"],
|
||||
["switch (e) { default: s; };", "4 switch statement"],
|
||||
["switch (e) { case x: s1; case y: s2; };", "5 switch statement"],
|
||||
// labels
|
||||
["foo : x;", " flow statement"],
|
||||
// throw
|
||||
["throw x;", "1 throw statement"],
|
||||
["throw x\n;", "2 throw statement"],
|
||||
// try catch finally
|
||||
["try { s1; } catch (e) { s2; };", "1 trycatchfinally statement"],
|
||||
["try { s1; } finally { s2; };", "2 trycatchfinally statement"],
|
||||
["try { s1; } catch (e) { s2; } finally { s3; };", "3 trycatchfinally statement"],
|
||||
// debugger
|
||||
["debugger;", "debuger statement"],
|
||||
// function decl
|
||||
["function f(x) { e; return x; };", "1 function declaration"],
|
||||
["function f() { x; y; };", "2 function declaration"],
|
||||
["function f(x,y) { var z; return x; };", "3 function declaration"],
|
||||
// function exp
|
||||
["(function f(x) { return x; });", "1 function expression"],
|
||||
["(function empty() {;});", "2 function expression"],
|
||||
["(function empty() {;});", "3 function expression"],
|
||||
["(function (x) {; });", "4 function expression"],
|
||||
// program
|
||||
["var x; function f(){;}; null;", "1 program"],
|
||||
[";;", "2 program"],
|
||||
["{ x; y; z; }", "3 program"],
|
||||
["function f(){ function g(){;}};", "4 program"],
|
||||
["x;\n/*foo*/\n ;", "5 program"],
|
||||
|
||||
// asi
|
||||
["foo: while(1){ continue \n foo; }", "1 asi"],
|
||||
["foo: while(1){ break \n foo; }", "2 asi"],
|
||||
["(function(){ return\nfoo; })()", "3 asi"],
|
||||
["var x; { 1 \n 2 } 3", "4 asi"],
|
||||
["ab /* hi */\ncd", "5 asi"],
|
||||
["ab/*\n*/cd", "6 asi (multi line multilinecomment counts as eol)"],
|
||||
["foo: while(1){ continue /* wtf \n busta */ foo; }", "7 asi illegal with multi line comment"],
|
||||
["function f() { s }", "8 asi"],
|
||||
["function f() { return }", "9 asi"],
|
||||
|
||||
// use strict
|
||||
// XXX: some of these should actually fail?
|
||||
// no support for "use strict" yet...
|
||||
['"use strict"; \'bla\'\n; foo;', "1 directive"],
|
||||
['(function() { "use strict"; \'bla\';\n foo; });', "2 directive"],
|
||||
['"use\\n strict";', "3 directive"],
|
||||
['foo; "use strict";', "4 directive"],
|
||||
|
||||
// tests from http://es5conform.codeplex.com/
|
||||
|
||||
['"use strict"; var o = { eval: 42};', "8.7.2-3-1-s: the use of eval as property name is allowed"],
|
||||
['({foo:0,foo:1});', 'Duplicate property name allowed in not strict mode'],
|
||||
['function foo(a,a){}', 'Duplicate parameter name allowed in not strict mode'],
|
||||
['(function foo(eval){})', 'Eval allowed as parameter name in non strict mode'],
|
||||
['(function foo(arguments){})', 'Arguments allowed as parameter name in non strict mode'],
|
||||
|
||||
// empty programs
|
||||
|
||||
['', '1 Empty program'],
|
||||
['// test', '2 Empty program'],
|
||||
['//test\n', '3 Empty program'],
|
||||
['\n// test', '4 Empty program'],
|
||||
['\n// test\n', '5 Empty program'],
|
||||
['/* */', '6 Empty program'],
|
||||
['/*\ns,fd\n*/', '7 Empty program'],
|
||||
['/*\ns,fd\n*/\n', '8 Empty program'],
|
||||
[' ', '9 Empty program'],
|
||||
[' /*\nsmeh*/ \n ', '10 Empty program'],
|
||||
|
||||
// trailing whitespace
|
||||
|
||||
['a ', '1 Trailing whitespace'],
|
||||
['a /* something */', '2 Trailing whitespace'],
|
||||
['a\n // hah', '3 Trailing whitespace'],
|
||||
['/abc/de//f', '4 Trailing whitespace'],
|
||||
['/abc/de/*f*/\n ', '5 Trailing whitespace'],
|
||||
|
||||
// things the parser tripped over at one point or the other (prevents regression bugs)
|
||||
['for (x;function(){ a\nb };z) x;', 'for header with function body forcing ASI'],
|
||||
['c=function(){return;return};', 'resetting noAsi after literal'],
|
||||
['d\nd()', 'asi exception causing token overflow'],
|
||||
['for(;;){x=function(){}}', 'function expression in a for header'],
|
||||
['for(var k;;){}', 'parser failing due to ASI accepting the incorrect "for" rule'],
|
||||
['({get foo(){ }})', 'getter with empty function body'],
|
||||
['\nreturnr', 'eol causes return statement to ignore local search requirement'],
|
||||
[' / /', '1 whitespace before regex causes regex to fail?'],
|
||||
['/ // / /', '2 whitespace before regex causes regex to fail?'],
|
||||
['/ / / / /', '3 whitespace before regex causes regex to fail?'],
|
||||
|
||||
['\n\t// Used for trimming whitespace\n\ttrimLeft = /^\\s+/;\n\ttrimRight = /\\s+$/;\t\n','turned out this didnt crash (the test below did), but whatever.'],
|
||||
['/[\\/]/;', 'escaped forward slash inside class group (would choke on fwd slash)'],
|
||||
['/[/]/;', 'also broke but is valid in es5 (not es3)'],
|
||||
['({get:5});','get property name thats not a getter'],
|
||||
['({set:5});','set property name thats not a setter'],
|
||||
['l !== "px" && (d.style(h, c, (k || 1) + l), j = (k || 1) / f.cur() * j, d.style(h, c, j + l)), i[1] && (k = (i[1] === "-=" ? -1 : 1) * k + j), f.custom(j, k, l)', 'this choked regex/div at some point'],
|
||||
['(/\'/g, \'\\\\\\\'\') + "\'";', 'the sequence of escaped characters confused the tokenizer'],
|
||||
['if (true) /=a/.test("a");', 'regexp starting with "=" in not obvious context (not implied by preceding token)']
|
||||
];
|
||||
|
||||
for (var i=0; i<inps.length; ++i) {
|
||||
callback(i, inps[i][0], inps[i][1]);
|
||||
};
|
||||
};
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/array1.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/array1.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
[],Array(1),[1,2,3]
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/array2.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/array2.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
(function(){var a=function(){};return new a(1,2,3,4)})()
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/array3.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/array3.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
(function(){function a(){}return new a(1,2,3,4)})()
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/array4.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/array4.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
(function(){function a(){}(function(){return new a(1,2,3)})()})()
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/assignment.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/assignment.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
a=1,b=a,c=1,d=b,e=d,longname=2;if(longname+1){x=3;if(x)var z=7}z=1,y=1,x=1,g+=1,h=g,++i,j=i,i++,j=i+17
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/concatstring.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/concatstring.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
var a=a+"a"+"b"+1+c,b=a+"c"+"ds"+123+c,c=a+"c"+123+d+"ds"+c
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/const.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/const.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
var a=13,b=1/3
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/empty-blocks.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/empty-blocks.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
function bar(){return--x}function foo(){while(bar());}function mak(){for(;;);}var x=5
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/forstatement.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/forstatement.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
a=func(),b=z;for(a++;i<10;i++)alert(i);var z=1;g=2;for(;i<10;i++)alert(i);var a=2;for(var i=1;i<10;i++)alert(i)
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/if.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/if.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
var a=1;a==1?a=2:a=17
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/ifreturn.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/ifreturn.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
function a(a){return a==1?2:17}
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/ifreturn2.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/ifreturn2.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
function x(a){return typeof a=="object"?a:a===42?0:a*2}function y(a){return typeof a=="object"?a:null}
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue10.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue10.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
function f(){var a;return(a="a")?a:a}f()
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue11.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue11.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
new(A,B),new(A||B),new(X?A:B)
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue13.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue13.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
var a=/^(?:(\w+):)?(?:\/\/(?:(?:([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#])(?::(\d))?)?(..?$|(?:[^?#\/]\/))([^?#]*)(?:\?([^#]))?(?:#(.))?/
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue14.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue14.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
var a={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"}
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue16.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue16.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
var a=3250441966
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue17.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue17.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
var a=function(b){b(),a()}
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue20.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue20.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
1
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue21.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue21.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
var a=0;switch(a){case 0:a++}
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue25.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue25.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
a:break a;console.log(1)
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue27.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue27.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
(a?b:c)?d:e
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue278.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue278.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
if(!x)debugger
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue28.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue28.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
o={".5":.5},o={.5:.5},o={.5:.5}
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue29.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue29.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
result=function(){return 1}()
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue30.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue30.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
var a=8,b=4,c=4
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue34.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue34.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
var a={};a["this"]=1,a.that=2
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue4.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue4.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
var a=2e3,b=.002,c=2e-5
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue48.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue48.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
var s,i;s="",i=0
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue50.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue50.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
function bar(a){try{foo()}catch(b){alert("Exception caught (foo not defined)")}alert(a)}bar(10)
|
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue53.js
generated
vendored
Normal file
1
node_modules/handlebars/node_modules/uglify-js/test/unit/compress/expected/issue53.js
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
x=(y,z)
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue