diff --git a/node_modules/.bin/handlebars b/node_modules/.bin/handlebars
new file mode 120000
index 0000000000..fb7d090fcc
--- /dev/null
+++ b/node_modules/.bin/handlebars
@@ -0,0 +1 @@
+../handlebars/bin/handlebars
\ No newline at end of file
diff --git a/node_modules/handlebars/.jshintrc b/node_modules/handlebars/.jshintrc
new file mode 100644
index 0000000000..f37931784a
--- /dev/null
+++ b/node_modules/handlebars/.jshintrc
@@ -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
+}
diff --git a/node_modules/handlebars/.npmignore b/node_modules/handlebars/.npmignore
new file mode 100644
index 0000000000..2f42c9f441
--- /dev/null
+++ b/node_modules/handlebars/.npmignore
@@ -0,0 +1,10 @@
+.DS_Store
+.gitignore
+.rvmrc
+Gemfile
+Gemfile.lock
+Rakefile
+bench/*
+spec/*
+src/*
+vendor/*
diff --git a/node_modules/handlebars/.rspec b/node_modules/handlebars/.rspec
new file mode 100644
index 0000000000..62c58f0492
--- /dev/null
+++ b/node_modules/handlebars/.rspec
@@ -0,0 +1 @@
+-cfs
diff --git a/node_modules/handlebars/LICENSE b/node_modules/handlebars/LICENSE
new file mode 100644
index 0000000000..f466a93fd3
--- /dev/null
+++ b/node_modules/handlebars/LICENSE
@@ -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.
diff --git a/node_modules/handlebars/README.markdown b/node_modules/handlebars/README.markdown
new file mode 100644
index 0000000000..56042f4d36
--- /dev/null
+++ b/node_modules/handlebars/README.markdown
@@ -0,0 +1,317 @@
+[](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 = "
Hello, my name is {{name}}. I am from {{hometown}}. I have " +
+ "{{kids.length}} kids:
Hello, my name is Alan. I am from Somewhere, TX. I have 2 kids:
+//
+//
Jimmy is 12
+//
Sally is 4
+//
+```
+
+
+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 "" + context.body + "";
+});
+
+var context = { posts: [{url: "/hello-world", body: "Hello World!"}] };
+var source = "
+```
+
+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 "" + title + "!"
+});
+
+var context = { posts: [{url: "/hello-world", body: "Hello World!"}] };
+var source = '
+```
+
+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 = "
+```
+
+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 = "
+```
+
+### 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
+
+ {{! This comment will not end up in the output }}
+
+
+```
+
+
+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
+
+
+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]
+
+
+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.
diff --git a/node_modules/handlebars/bin/handlebars b/node_modules/handlebars/bin/handlebars
new file mode 100755
index 0000000000..6d83cef89f
--- /dev/null
+++ b/node_modules/handlebars/bin/handlebars
@@ -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);
+}
diff --git a/node_modules/handlebars/dist/handlebars.js b/node_modules/handlebars/dist/handlebars.js
new file mode 100644
index 0000000000..26d9207785
--- /dev/null
+++ b/node_modules/handlebars/dist/handlebars.js
@@ -0,0 +1,2202 @@
+/*
+
+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 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;
+})();;
+// lib/handlebars/compiler/base.js
+
+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);
+};;
+// lib/handlebars/compiler/ast.js
+(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 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;
+ };
+
+})();;
+// 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/compiler/compiler.js
+
+/*jshint eqnull:true*/
+Handlebars.Compiler = function() {};
+Handlebars.JavaScriptCompiler = function() {};
+
+(function(Compiler, JavaScriptCompiler) {
+ // the foundHelper register will disambiguate helper lookup from finding a
+ // function in a context. This is necessary for mustache compatibility, which
+ // requires that context functions in blocks are evaluated by blockHelperMissing,
+ // and then proceed as if the resulting value was provided to blockHelperMissing.
+
+ Compiler.prototype = {
+ compiler: Compiler,
+
+ disassemble: function() {
+ var opcodes = this.opcodes, opcode, out = [], params, param;
+
+ for (var i=0, l=opcodes.length; i 0) {
+ this.source[1] = this.source[1] + ", " + locals.join(", ");
+ }
+
+ // Generate minimizer alias mappings
+ if (!this.isChild) {
+ for (var alias in this.context.aliases) {
+ this.source[1] = this.source[1] + ', ' + alias + '=' + this.context.aliases[alias];
+ }
+ }
+
+ if (this.source[1]) {
+ this.source[1] = "var " + this.source[1].substring(2) + ";";
+ }
+
+ // Merge children
+ if (!this.isChild) {
+ this.source[1] += '\n' + this.context.programs.join('\n') + '\n';
+ }
+
+ if (!this.environment.isSimple) {
+ this.source.push("return buffer;");
+ }
+
+ var params = this.isChild ? ["depth0", "data"] : ["Handlebars", "depth0", "helpers", "partials", "data"];
+
+ for(var i=0, l=this.environment.depths.list.length; i this.stackVars.length) { this.stackVars.push("stack" + this.stackSlot); }
+ return this.topStackName();
+ },
+ topStackName: function() {
+ return "stack" + this.stackSlot;
+ },
+ flushInline: function() {
+ var inlineStack = this.inlineStack;
+ if (inlineStack.length) {
+ this.inlineStack = [];
+ for (var i = 0, len = inlineStack.length; i < len; i++) {
+ var entry = inlineStack[i];
+ if (entry instanceof Literal) {
+ this.compileStack.push(entry);
+ } else {
+ this.pushStack(entry);
+ }
+ }
+ }
+ },
+ isInline: function() {
+ return this.inlineStack.length;
+ },
+
+ popStack: function(wrapped) {
+ var inline = this.isInline(),
+ item = (inline ? this.inlineStack : this.compileStack).pop();
+
+ if (!wrapped && (item instanceof Literal)) {
+ return item.value;
+ } else {
+ if (!inline) {
+ this.stackSlot--;
+ }
+ return item;
+ }
+ },
+
+ topStack: function(wrapped) {
+ var stack = (this.isInline() ? this.inlineStack : this.compileStack),
+ item = stack[stack.length - 1];
+
+ if (!wrapped && (item instanceof Literal)) {
+ return item.value;
+ } else {
+ return item;
+ }
+ },
+
+ quotedString: function(str) {
+ return '"' + str
+ .replace(/\\/g, '\\\\')
+ .replace(/"/g, '\\"')
+ .replace(/\n/g, '\\n')
+ .replace(/\r/g, '\\r') + '"';
+ },
+
+ setupHelper: function(paramSize, name, missingParams) {
+ var params = [];
+ this.setupParams(paramSize, params, missingParams);
+ var foundHelper = this.nameLookup('helpers', name, 'helper');
+
+ return {
+ params: params,
+ name: foundHelper,
+ callParams: ["depth0"].concat(params).join(", "),
+ helperMissingParams: missingParams && ["depth0", this.quotedString(name)].concat(params).join(", ")
+ };
+ },
+
+ // the params and contexts arguments are passed in arrays
+ // to fill in
+ setupParams: function(paramSize, params, useRegister) {
+ var options = [], contexts = [], types = [], param, inverse, program;
+
+ options.push("hash:" + this.popStack());
+
+ inverse = this.popStack();
+ program = this.popStack();
+
+ // Avoid setting fn and inverse if neither are set. This allows
+ // helpers to do a check for `if (options.fn)`
+ if (program || inverse) {
+ if (!program) {
+ this.context.aliases.self = "this";
+ program = "self.noop";
+ }
+
+ if (!inverse) {
+ this.context.aliases.self = "this";
+ inverse = "self.noop";
+ }
+
+ options.push("inverse:" + inverse);
+ options.push("fn:" + program);
+ }
+
+ for(var i=0; i= 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": ">",
+ '"': """,
+ "'": "'",
+ "`": "`"
+ };
+
+ 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;
+;
diff --git a/node_modules/handlebars/lib/handlebars.js b/node_modules/handlebars/lib/handlebars.js
new file mode 100644
index 0000000000..7d85c26104
--- /dev/null
+++ b/node_modules/handlebars/lib/handlebars.js
@@ -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();
diff --git a/node_modules/handlebars/lib/handlebars/base.js b/node_modules/handlebars/lib/handlebars/base.js
new file mode 100644
index 0000000000..1a25b5cc89
--- /dev/null
+++ b/node_modules/handlebars/lib/handlebars/base.js
@@ -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 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;
+};
+
diff --git a/node_modules/handlebars/lib/handlebars/compiler/base.js b/node_modules/handlebars/lib/handlebars/compiler/base.js
new file mode 100644
index 0000000000..8ff1101d5c
--- /dev/null
+++ b/node_modules/handlebars/lib/handlebars/compiler/base.js
@@ -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;
+};
diff --git a/node_modules/handlebars/lib/handlebars/compiler/compiler.js b/node_modules/handlebars/lib/handlebars/compiler/compiler.js
new file mode 100644
index 0000000000..84008043c9
--- /dev/null
+++ b/node_modules/handlebars/lib/handlebars/compiler/compiler.js
@@ -0,0 +1,1277 @@
+var compilerbase = require("./base");
+
+exports.attach = function(Handlebars) {
+
+compilerbase.attach(Handlebars);
+
+// BEGIN(BROWSER)
+
+/*jshint eqnull:true*/
+Handlebars.Compiler = function() {};
+Handlebars.JavaScriptCompiler = function() {};
+
+(function(Compiler, JavaScriptCompiler) {
+ // the foundHelper register will disambiguate helper lookup from finding a
+ // function in a context. This is necessary for mustache compatibility, which
+ // requires that context functions in blocks are evaluated by blockHelperMissing,
+ // and then proceed as if the resulting value was provided to blockHelperMissing.
+
+ Compiler.prototype = {
+ compiler: Compiler,
+
+ disassemble: function() {
+ var opcodes = this.opcodes, opcode, out = [], params, param;
+
+ for (var i=0, l=opcodes.length; i 0) {
+ this.source[1] = this.source[1] + ", " + locals.join(", ");
+ }
+
+ // Generate minimizer alias mappings
+ if (!this.isChild) {
+ for (var alias in this.context.aliases) {
+ this.source[1] = this.source[1] + ', ' + alias + '=' + this.context.aliases[alias];
+ }
+ }
+
+ if (this.source[1]) {
+ this.source[1] = "var " + this.source[1].substring(2) + ";";
+ }
+
+ // Merge children
+ if (!this.isChild) {
+ this.source[1] += '\n' + this.context.programs.join('\n') + '\n';
+ }
+
+ if (!this.environment.isSimple) {
+ this.source.push("return buffer;");
+ }
+
+ var params = this.isChild ? ["depth0", "data"] : ["Handlebars", "depth0", "helpers", "partials", "data"];
+
+ for(var i=0, l=this.environment.depths.list.length; i this.stackVars.length) { this.stackVars.push("stack" + this.stackSlot); }
+ return this.topStackName();
+ },
+ topStackName: function() {
+ return "stack" + this.stackSlot;
+ },
+ flushInline: function() {
+ var inlineStack = this.inlineStack;
+ if (inlineStack.length) {
+ this.inlineStack = [];
+ for (var i = 0, len = inlineStack.length; i < len; i++) {
+ var entry = inlineStack[i];
+ if (entry instanceof Literal) {
+ this.compileStack.push(entry);
+ } else {
+ this.pushStack(entry);
+ }
+ }
+ }
+ },
+ isInline: function() {
+ return this.inlineStack.length;
+ },
+
+ popStack: function(wrapped) {
+ var inline = this.isInline(),
+ item = (inline ? this.inlineStack : this.compileStack).pop();
+
+ if (!wrapped && (item instanceof Literal)) {
+ return item.value;
+ } else {
+ if (!inline) {
+ this.stackSlot--;
+ }
+ return item;
+ }
+ },
+
+ topStack: function(wrapped) {
+ var stack = (this.isInline() ? this.inlineStack : this.compileStack),
+ item = stack[stack.length - 1];
+
+ if (!wrapped && (item instanceof Literal)) {
+ return item.value;
+ } else {
+ return item;
+ }
+ },
+
+ quotedString: function(str) {
+ return '"' + str
+ .replace(/\\/g, '\\\\')
+ .replace(/"/g, '\\"')
+ .replace(/\n/g, '\\n')
+ .replace(/\r/g, '\\r') + '"';
+ },
+
+ setupHelper: function(paramSize, name, missingParams) {
+ var params = [];
+ this.setupParams(paramSize, params, missingParams);
+ var foundHelper = this.nameLookup('helpers', name, 'helper');
+
+ return {
+ params: params,
+ name: foundHelper,
+ callParams: ["depth0"].concat(params).join(", "),
+ helperMissingParams: missingParams && ["depth0", this.quotedString(name)].concat(params).join(", ")
+ };
+ },
+
+ // the params and contexts arguments are passed in arrays
+ // to fill in
+ setupParams: function(paramSize, params, useRegister) {
+ var options = [], contexts = [], types = [], param, inverse, program;
+
+ options.push("hash:" + this.popStack());
+
+ inverse = this.popStack();
+ program = this.popStack();
+
+ // Avoid setting fn and inverse if neither are set. This allows
+ // helpers to do a check for `if (options.fn)`
+ if (program || inverse) {
+ if (!program) {
+ this.context.aliases.self = "this";
+ program = "self.noop";
+ }
+
+ if (!inverse) {
+ this.context.aliases.self = "this";
+ inverse = "self.noop";
+ }
+
+ options.push("inverse:" + inverse);
+ options.push("fn:" + program);
+ }
+
+ for(var i=0; i 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;
diff --git a/node_modules/handlebars/lib/handlebars/compiler/printer.js b/node_modules/handlebars/lib/handlebars/compiler/printer.js
new file mode 100644
index 0000000000..1d96a91f83
--- /dev/null
+++ b/node_modules/handlebars/lib/handlebars/compiler/printer.js
@@ -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 " + content + " }}");
+};
+
+Handlebars.PrintVisitor.prototype.hash = function(hash) {
+ var pairs = hash.pairs;
+ var joinedPairs = [], left, right;
+
+ for(var i=0, l=pairs.length; i 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;
+};
+
diff --git a/node_modules/handlebars/lib/handlebars/compiler/visitor.js b/node_modules/handlebars/lib/handlebars/compiler/visitor.js
new file mode 100644
index 0000000000..5d07314079
--- /dev/null
+++ b/node_modules/handlebars/lib/handlebars/compiler/visitor.js
@@ -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;
+};
+
+
diff --git a/node_modules/handlebars/lib/handlebars/runtime.js b/node_modules/handlebars/lib/handlebars/runtime.js
new file mode 100644
index 0000000000..805e10fbd0
--- /dev/null
+++ b/node_modules/handlebars/lib/handlebars/runtime.js
@@ -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;
+
+};
diff --git a/node_modules/handlebars/lib/handlebars/utils.js b/node_modules/handlebars/lib/handlebars/utils.js
new file mode 100644
index 0000000000..2a7861afe8
--- /dev/null
+++ b/node_modules/handlebars/lib/handlebars/utils.js
@@ -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;
+};
diff --git a/node_modules/handlebars/node_modules/.bin/uglifyjs b/node_modules/handlebars/node_modules/.bin/uglifyjs
new file mode 120000
index 0000000000..fef3468b6f
--- /dev/null
+++ b/node_modules/handlebars/node_modules/.bin/uglifyjs
@@ -0,0 +1 @@
+../uglify-js/bin/uglifyjs
\ No newline at end of file
diff --git a/node_modules/handlebars/node_modules/optimist/.travis.yml b/node_modules/handlebars/node_modules/optimist/.travis.yml
new file mode 100644
index 0000000000..895dbd3623
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/.travis.yml
@@ -0,0 +1,4 @@
+language: node_js
+node_js:
+ - 0.6
+ - 0.8
diff --git a/node_modules/handlebars/node_modules/optimist/LICENSE b/node_modules/handlebars/node_modules/optimist/LICENSE
new file mode 100644
index 0000000000..432d1aeb01
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/LICENSE
@@ -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.
diff --git a/node_modules/handlebars/node_modules/optimist/README.markdown b/node_modules/handlebars/node_modules/optimist/README.markdown
new file mode 100644
index 0000000000..ad9d3fd68f
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/README.markdown
@@ -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).
+
+[](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
+
+
+
+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).
diff --git a/node_modules/handlebars/node_modules/optimist/example/bool.js b/node_modules/handlebars/node_modules/optimist/example/bool.js
new file mode 100644
index 0000000000..a998fb7ab7
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/example/bool.js
@@ -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 ? '.' : '')
+);
diff --git a/node_modules/handlebars/node_modules/optimist/example/boolean_double.js b/node_modules/handlebars/node_modules/optimist/example/boolean_double.js
new file mode 100644
index 0000000000..a35a7e6d33
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/example/boolean_double.js
@@ -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._);
diff --git a/node_modules/handlebars/node_modules/optimist/example/boolean_single.js b/node_modules/handlebars/node_modules/optimist/example/boolean_single.js
new file mode 100644
index 0000000000..017bb6893c
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/example/boolean_single.js
@@ -0,0 +1,7 @@
+#!/usr/bin/env node
+var argv = require('optimist')
+ .boolean('v')
+ .argv
+;
+console.dir(argv.v);
+console.dir(argv._);
diff --git a/node_modules/handlebars/node_modules/optimist/example/default_hash.js b/node_modules/handlebars/node_modules/optimist/example/default_hash.js
new file mode 100644
index 0000000000..ade77681dd
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/example/default_hash.js
@@ -0,0 +1,8 @@
+#!/usr/bin/env node
+
+var argv = require('optimist')
+ .default({ x : 10, y : 10 })
+ .argv
+;
+
+console.log(argv.x + argv.y);
diff --git a/node_modules/handlebars/node_modules/optimist/example/default_singles.js b/node_modules/handlebars/node_modules/optimist/example/default_singles.js
new file mode 100644
index 0000000000..d9b1ff458a
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/example/default_singles.js
@@ -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);
diff --git a/node_modules/handlebars/node_modules/optimist/example/divide.js b/node_modules/handlebars/node_modules/optimist/example/divide.js
new file mode 100644
index 0000000000..5e2ee82ff0
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/example/divide.js
@@ -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);
diff --git a/node_modules/handlebars/node_modules/optimist/example/line_count.js b/node_modules/handlebars/node_modules/optimist/example/line_count.js
new file mode 100644
index 0000000000..b5f95bf6d2
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/example/line_count.js
@@ -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);
+});
diff --git a/node_modules/handlebars/node_modules/optimist/example/line_count_options.js b/node_modules/handlebars/node_modules/optimist/example/line_count_options.js
new file mode 100644
index 0000000000..d9ac709044
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/example/line_count_options.js
@@ -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));
+});
diff --git a/node_modules/handlebars/node_modules/optimist/example/line_count_wrap.js b/node_modules/handlebars/node_modules/optimist/example/line_count_wrap.js
new file mode 100644
index 0000000000..426751112d
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/example/line_count_wrap.js
@@ -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));
+});
diff --git a/node_modules/handlebars/node_modules/optimist/example/nonopt.js b/node_modules/handlebars/node_modules/optimist/example/nonopt.js
new file mode 100644
index 0000000000..ee633eedcd
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/example/nonopt.js
@@ -0,0 +1,4 @@
+#!/usr/bin/env node
+var argv = require('optimist').argv;
+console.log('(%d,%d)', argv.x, argv.y);
+console.log(argv._);
diff --git a/node_modules/handlebars/node_modules/optimist/example/reflect.js b/node_modules/handlebars/node_modules/optimist/example/reflect.js
new file mode 100644
index 0000000000..816b3e111c
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/example/reflect.js
@@ -0,0 +1,2 @@
+#!/usr/bin/env node
+console.dir(require('optimist').argv);
diff --git a/node_modules/handlebars/node_modules/optimist/example/short.js b/node_modules/handlebars/node_modules/optimist/example/short.js
new file mode 100644
index 0000000000..1db0ad0f8b
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/example/short.js
@@ -0,0 +1,3 @@
+#!/usr/bin/env node
+var argv = require('optimist').argv;
+console.log('(%d,%d)', argv.x, argv.y);
diff --git a/node_modules/handlebars/node_modules/optimist/example/string.js b/node_modules/handlebars/node_modules/optimist/example/string.js
new file mode 100644
index 0000000000..a8e5aeb231
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/example/string.js
@@ -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' ]
+*/
diff --git a/node_modules/handlebars/node_modules/optimist/example/usage-options.js b/node_modules/handlebars/node_modules/optimist/example/usage-options.js
new file mode 100644
index 0000000000..b999977679
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/example/usage-options.js
@@ -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);
\ No newline at end of file
diff --git a/node_modules/handlebars/node_modules/optimist/example/xup.js b/node_modules/handlebars/node_modules/optimist/example/xup.js
new file mode 100644
index 0000000000..8f6ecd2012
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/example/xup.js
@@ -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');
+}
+
diff --git a/node_modules/handlebars/node_modules/optimist/index.js b/node_modules/handlebars/node_modules/optimist/index.js
new file mode 100644
index 0000000000..e69bef9a59
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/index.js
@@ -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 ];
+ }
+}
diff --git a/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/.npmignore b/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/.npmignore
new file mode 100644
index 0000000000..3c3629e647
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/.npmignore
@@ -0,0 +1 @@
+node_modules
diff --git a/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/README.markdown b/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/README.markdown
new file mode 100644
index 0000000000..346374e0d4
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/README.markdown
@@ -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"`.
diff --git a/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/example/center.js b/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/example/center.js
new file mode 100644
index 0000000000..a3fbaae988
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/example/center.js
@@ -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.'
+));
diff --git a/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/example/meat.js b/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/example/meat.js
new file mode 100644
index 0000000000..a4665e1058
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/example/meat.js
@@ -0,0 +1,3 @@
+var wrap = require('wordwrap')(15);
+
+console.log(wrap('You and your whole family are made out of meat.'));
diff --git a/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/index.js b/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/index.js
new file mode 100644
index 0000000000..c9bc94521d
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/index.js
@@ -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' });
+};
diff --git a/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/package.json b/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/package.json
new file mode 100644
index 0000000000..a3f2dc858b
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/package.json
@@ -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"
+}
diff --git a/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/break.js b/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/break.js
new file mode 100644
index 0000000000..749292ecc1
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/break.js
@@ -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, ''));
+};
diff --git a/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/idleness.txt b/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/idleness.txt
new file mode 100644
index 0000000000..aa3f4907fe
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/idleness.txt
@@ -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.
diff --git a/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/wrap.js b/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/wrap.js
new file mode 100644
index 0000000000..0cfb76d178
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/wrap.js
@@ -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(' '));
+ });
+};
diff --git a/node_modules/handlebars/node_modules/optimist/package.json b/node_modules/handlebars/node_modules/optimist/package.json
new file mode 100644
index 0000000000..5b5c16f2e8
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/package.json
@@ -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"
+}
diff --git a/node_modules/handlebars/node_modules/optimist/test/_.js b/node_modules/handlebars/node_modules/optimist/test/_.js
new file mode 100644
index 0000000000..d9c58b3688
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/test/_.js
@@ -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();
+ });
+ };
+}
diff --git a/node_modules/handlebars/node_modules/optimist/test/_/argv.js b/node_modules/handlebars/node_modules/optimist/test/_/argv.js
new file mode 100644
index 0000000000..3d096062ca
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/test/_/argv.js
@@ -0,0 +1,2 @@
+#!/usr/bin/env node
+console.log(JSON.stringify(process.argv));
diff --git a/node_modules/handlebars/node_modules/optimist/test/_/bin.js b/node_modules/handlebars/node_modules/optimist/test/_/bin.js
new file mode 100755
index 0000000000..4a18d85f3c
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/test/_/bin.js
@@ -0,0 +1,3 @@
+#!/usr/bin/env node
+var argv = require('../../index').argv
+console.log(JSON.stringify(argv._));
diff --git a/node_modules/handlebars/node_modules/optimist/test/parse.js b/node_modules/handlebars/node_modules/optimist/test/parse.js
new file mode 100644
index 0000000000..a6ce9f113a
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/test/parse.js
@@ -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();
+});
diff --git a/node_modules/handlebars/node_modules/optimist/test/usage.js b/node_modules/handlebars/node_modules/optimist/test/usage.js
new file mode 100644
index 0000000000..300454c1e6
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/test/usage.js
@@ -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,
+ };
+};
diff --git a/node_modules/handlebars/node_modules/optimist/x.js b/node_modules/handlebars/node_modules/optimist/x.js
new file mode 100644
index 0000000000..6c006d062e
--- /dev/null
+++ b/node_modules/handlebars/node_modules/optimist/x.js
@@ -0,0 +1 @@
+console.dir(require('./').argv);
diff --git a/node_modules/handlebars/node_modules/uglify-js/.npmignore b/node_modules/handlebars/node_modules/uglify-js/.npmignore
new file mode 100644
index 0000000000..d97eaa09bf
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/.npmignore
@@ -0,0 +1,4 @@
+.DS_Store
+.tmp*~
+*.local.*
+.pinf-*
\ No newline at end of file
diff --git a/node_modules/handlebars/node_modules/uglify-js/README.html b/node_modules/handlebars/node_modules/uglify-js/README.html
new file mode 100644
index 0000000000..5f37ac0f0c
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/README.html
@@ -0,0 +1,981 @@
+
+
+
+
+UglifyJS – a JavaScript parser/compressor/beautifier
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
UglifyJS – a JavaScript parser/compressor/beautifier
1 UglifyJS — a JavaScript parser/compressor/beautifier
+
+
+
+
+This package implements a general-purpose JavaScript
+parser/compressor/beautifier toolkit. It is developed on 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 parse-js.js and it's a
+port to JavaScript of the excellent parse-js Common Lisp library from Marijn Haverbeke.
+
+
+( See cl-uglify-js if you're looking for the Common Lisp version of
+UglifyJS. )
+
+
+The second part of this package, implemented in 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();
+
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.
+
+
+
+
+
+
+
+
+
+
+
+
1.1Unsafe 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.
+
+
+
+
+
+
1.1.1 Calls involving the global Array constructor
+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:
+
+
+
+
+
// case 1. globally declared variable
+ varArray;
+ newArray(1, 2, 3);
+ Array(a, b);
+
+ // or (can be declared later)
+ newArray(1, 2, 3);
+ varArray;
+
+ // or (can be a function)
+ newArray(1, 2, 3);
+ functionArray() { ... }
+
+// case 2. declared in a function
+ (function(){
+ a = newArray(1, 2, 3);
+ b = Array(5, 6);
+ varArray;
+ })();
+
+ // or
+ (function(Array){
+ return Array(5, 6, 7);
+ })();
+
+ // or
+ (function(){
+ returnnewArray(1, 2, 3, 4);
+ functionArray() { ... }
+ })();
+
+ // etc.
+
+
+
+
+
+
+
+
+
1.1.2obj.toString() ==> obj+“”
+
+
+
+
+
+
+
+
+
+
1.2 Install (NPM)
+
+
+
+
+UglifyJS is now available through NPM — npm install uglify-js should do
+the job.
+
+
+
+
+
+
+
1.3 Install latest code from GitHub
+
+
+
+
+
+
+
## 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)
+
+
+
+
+
+
+
+
+
1.4 Usage
+
+
+
+
+There is a command-line tool that exposes the functionality of this library
+for your shell-scripting needs:
+
+
+
+
+
uglifyjs [ options... ] [ filename ]
+
+
+
+
+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).
+
+
+
+
+
+
--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.
+
+
+
+
+
+
+
+
+
+
+
+
1.4.1 API
+
+
+
+
+To use the library from JavaScript, you'd do the following (example for
+NodeJS):
+
+
+
+
+
varjsp = require("uglify-js").parser;
+varpro = require("uglify-js").uglify;
+
+varorig_code = "... JS code here";
+varast = 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
+varfinal_code = pro.gen_code(ast); // compressed code here
+
+
+
+
+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:
+
+
+
+
+
+
+
+
functionf(a, b, c, d, e) {
+ varq;
+ varw;
+ w = 10;
+ q = 20;
+ for (vari = 1; i < 10; ++i) {
+ varboo = foo(a);
+ }
+ for (vari = 0; i < 1; ++i) {
+ varboo = bar(c);
+ }
+ functionfoo(){ ... }
+ functionbar(){ ... }
+ functionbaz(){ ... }
+}
+
+// transforms into ==>
+
+functionf(a, b, c) {
+ vari, boo, w = 10, q = 20;
+ for (i = 1; i < 10; ++i) {
+ boo = foo(a);
+ }
+ for (i = 0; i < 1; ++i) {
+ boo = bar(c);
+ }
+ functionfoo() { ... }
+ functionbar() { ... }
+}
+
+
+
+
+
pro.ast_mangle(ast, options) – generates a new AST containing mangled
+ (compressed) variable and function names. It supports the following
+ options:
+
+
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
+
+
+
+
+
+
+
+
+
+
+
+
+
1.4.2 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.
+
+
+
+
+
+
+
1.4.3 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.
+
+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.
+
+
+
+
+
+
+
+
1.5 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
+
+
+
+
+
+
+
+
+
+
1.6 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 hacks1 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 (use the Google Group or email me directly).
+
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.
+
+
+
+
+
Footnotes:
+
+
1 I even reported a few bugs and suggested some fixes in the original
+ parse-js library, and Marijn pushed fixes literally in minutes.
+
+
+
diff --git a/node_modules/handlebars/node_modules/uglify-js/README.org b/node_modules/handlebars/node_modules/uglify-js/README.org
new file mode 100644
index 0000000000..d36b6b26f0
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/README.org
@@ -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:
+#+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.
+
+** <>
+
+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 =
+
+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
+ =
+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
diff --git a/node_modules/handlebars/node_modules/uglify-js/bin/uglifyjs b/node_modules/handlebars/node_modules/uglify-js/bin/uglifyjs
new file mode 100755
index 0000000000..df5201daae
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/bin/uglifyjs
@@ -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."); }
+};
diff --git a/node_modules/handlebars/node_modules/uglify-js/docstyle.css b/node_modules/handlebars/node_modules/uglify-js/docstyle.css
new file mode 100644
index 0000000000..412481fe66
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/docstyle.css
@@ -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; }
+}
diff --git a/node_modules/handlebars/node_modules/uglify-js/lib/consolidator.js b/node_modules/handlebars/node_modules/uglify-js/lib/consolidator.js
new file mode 100644
index 0000000000..d39674d2e1
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/lib/consolidator.js
@@ -0,0 +1,2599 @@
+/**
+ * @preserve Copyright 2012 Robert Gust-Bardon .
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
+ */
+
+/**
+ * @fileoverview Enhances UglifyJS with consolidation of null, Boolean, and String values.
+ *
Also known as aliasing, this feature has been deprecated in the Closure Compiler since its
+ * initial release, where it is unavailable from the CLI. The Closure Compiler allows one to log and
+ * influence this process. In contrast, this implementation does not introduce
+ * any variable declarations in global code and derives String values from
+ * identifier names used as property accessors.
+ *
Consolidating literals may worsen the data compression ratio when an encoding
+ * transformation is applied. For instance, jQuery 1.7.1 takes 248235 bytes.
+ * Building it with
+ * UglifyJS v1.2.5 results in 93647 bytes (37.73% of the original) which are
+ * then compressed to 33154 bytes (13.36% of the original) using gzip(1). Building it with the same
+ * version of UglifyJS 1.2.5 patched with the implementation of consolidation
+ * results in 80784 bytes (a decrease of 12863 bytes, i.e. 13.74%, in comparison
+ * to the aforementioned 93647 bytes) which are then compressed to 34013 bytes
+ * (an increase of 859 bytes, i.e. 2.59%, in comparison to the aforementioned
+ * 33154 bytes).
+ */
+
+/*global console:false, exports:true, module:false, require:false */
+/*jshint sub:true */
+/**
+ * Consolidates null, Boolean, and String values found inside an AST.
+ * @param {!TSyntacticCodeUnit} oAbstractSyntaxTree An array-like object
+ * representing an AST.
+ * @return {!TSyntacticCodeUnit} An array-like object representing an AST with its null, Boolean, and
+ * String values consolidated.
+ */
+// TODO(user) Consolidation of mathematical values found in numeric literals.
+// TODO(user) Unconsolidation.
+// TODO(user) Consolidation of ECMA-262 6th Edition programs.
+// TODO(user) Rewrite in ECMA-262 6th Edition.
+exports['ast_consolidate'] = function(oAbstractSyntaxTree) {
+ 'use strict';
+ /*jshint bitwise:true, curly:true, eqeqeq:true, forin:true, immed:true,
+ latedef:true, newcap:true, noarge:true, noempty:true, nonew:true,
+ onevar:true, plusplus:true, regexp:true, undef:true, strict:true,
+ sub:false, trailing:true */
+
+ var _,
+ /**
+ * A record consisting of data about one or more source elements.
+ * @constructor
+ * @nosideeffects
+ */
+ TSourceElementsData = function() {
+ /**
+ * The category of the elements.
+ * @type {number}
+ * @see ESourceElementCategories
+ */
+ this.nCategory = ESourceElementCategories.N_OTHER;
+ /**
+ * The number of occurrences (within the elements) of each primitive
+ * value that could be consolidated.
+ * @type {!Array.>}
+ */
+ this.aCount = [];
+ this.aCount[EPrimaryExpressionCategories.N_IDENTIFIER_NAMES] = {};
+ this.aCount[EPrimaryExpressionCategories.N_STRING_LITERALS] = {};
+ this.aCount[EPrimaryExpressionCategories.N_NULL_AND_BOOLEAN_LITERALS] =
+ {};
+ /**
+ * Identifier names found within the elements.
+ * @type {!Array.}
+ */
+ this.aIdentifiers = [];
+ /**
+ * Prefixed representation Strings of each primitive value that could be
+ * consolidated within the elements.
+ * @type {!Array.}
+ */
+ this.aPrimitiveValues = [];
+ },
+ /**
+ * A record consisting of data about a primitive value that could be
+ * consolidated.
+ * @constructor
+ * @nosideeffects
+ */
+ TPrimitiveValue = function() {
+ /**
+ * The difference in the number of terminal symbols between the original
+ * source text and the one with the primitive value consolidated. If the
+ * difference is positive, the primitive value is considered worthwhile.
+ * @type {number}
+ */
+ this.nSaving = 0;
+ /**
+ * An identifier name of the variable that will be declared and assigned
+ * the primitive value if the primitive value is consolidated.
+ * @type {string}
+ */
+ this.sName = '';
+ },
+ /**
+ * A record consisting of data on what to consolidate within the range of
+ * source elements that is currently being considered.
+ * @constructor
+ * @nosideeffects
+ */
+ TSolution = function() {
+ /**
+ * An object whose keys are prefixed representation Strings of each
+ * primitive value that could be consolidated within the elements and
+ * whose values are corresponding data about those primitive values.
+ * @type {!Object.}
+ * @see TPrimitiveValue
+ */
+ this.oPrimitiveValues = {};
+ /**
+ * The difference in the number of terminal symbols between the original
+ * source text and the one with all the worthwhile primitive values
+ * consolidated.
+ * @type {number}
+ * @see TPrimitiveValue#nSaving
+ */
+ this.nSavings = 0;
+ },
+ /**
+ * The processor of ASTs found
+ * in UglifyJS.
+ * @namespace
+ * @type {!TProcessor}
+ */
+ oProcessor = (/** @type {!TProcessor} */ require('./process')),
+ /**
+ * A record consisting of a number of constants that represent the
+ * difference in the number of terminal symbols between a source text with
+ * a modified syntactic code unit and the original one.
+ * @namespace
+ * @type {!Object.}
+ */
+ oWeights = {
+ /**
+ * The difference in the number of punctuators required by the bracket
+ * notation and the dot notation.
+ *
'[]'.length - '.'.length
+ * @const
+ * @type {number}
+ */
+ N_PROPERTY_ACCESSOR: 1,
+ /**
+ * The number of punctuators required by a variable declaration with an
+ * initialiser.
+ *
':'.length + ';'.length
+ * @const
+ * @type {number}
+ */
+ N_VARIABLE_DECLARATION: 2,
+ /**
+ * The number of terminal symbols required to introduce a variable
+ * statement (excluding its variable declaration list).
+ *
'var '.length
+ * @const
+ * @type {number}
+ */
+ N_VARIABLE_STATEMENT_AFFIXATION: 4,
+ /**
+ * The number of terminal symbols needed to enclose source elements
+ * within a function call with no argument values to a function with an
+ * empty parameter list.
+ *
'(function(){}());'.length
+ * @const
+ * @type {number}
+ */
+ N_CLOSURE: 17
+ },
+ /**
+ * Categories of primary expressions from which primitive values that
+ * could be consolidated are derivable.
+ * @namespace
+ * @enum {number}
+ */
+ EPrimaryExpressionCategories = {
+ /**
+ * Identifier names used as property accessors.
+ * @type {number}
+ */
+ N_IDENTIFIER_NAMES: 0,
+ /**
+ * String literals.
+ * @type {number}
+ */
+ N_STRING_LITERALS: 1,
+ /**
+ * Null and Boolean literals.
+ * @type {number}
+ */
+ N_NULL_AND_BOOLEAN_LITERALS: 2
+ },
+ /**
+ * Prefixes of primitive values that could be consolidated.
+ * The String values of the prefixes must have same number of characters.
+ * The prefixes must not be used in any properties defined in any version
+ * of ECMA-262.
+ * @namespace
+ * @enum {string}
+ */
+ EValuePrefixes = {
+ /**
+ * Identifies String values.
+ * @type {string}
+ */
+ S_STRING: '#S',
+ /**
+ * Identifies null and Boolean values.
+ * @type {string}
+ */
+ S_SYMBOLIC: '#O'
+ },
+ /**
+ * Categories of source elements in terms of their appropriateness of
+ * having their primitive values consolidated.
+ * @namespace
+ * @enum {number}
+ */
+ ESourceElementCategories = {
+ /**
+ * Identifies a source element that includes the {@code with} statement.
+ * @type {number}
+ */
+ N_WITH: 0,
+ /**
+ * Identifies a source element that includes the {@code eval} identifier name.
+ * @type {number}
+ */
+ N_EVAL: 1,
+ /**
+ * Identifies a source element that must be excluded from the process
+ * unless its whole scope is examined.
+ * @type {number}
+ */
+ N_EXCLUDABLE: 2,
+ /**
+ * Identifies source elements not posing any problems.
+ * @type {number}
+ */
+ N_OTHER: 3
+ },
+ /**
+ * The list of literals (other than the String ones) whose primitive
+ * values can be consolidated.
+ * @const
+ * @type {!Array.}
+ */
+ A_OTHER_SUBSTITUTABLE_LITERALS = [
+ 'null', // The null literal.
+ 'false', // The Boolean literal {@code false}.
+ 'true' // The Boolean literal {@code true}.
+ ];
+
+ (/**
+ * Consolidates all worthwhile primitive values in a syntactic code unit.
+ * @param {!TSyntacticCodeUnit} oSyntacticCodeUnit An array-like object
+ * representing the branch of the abstract syntax tree representing the
+ * syntactic code unit along with its scope.
+ * @see TPrimitiveValue#nSaving
+ */
+ function fExamineSyntacticCodeUnit(oSyntacticCodeUnit) {
+ var _,
+ /**
+ * Indicates whether the syntactic code unit represents global code.
+ * @type {boolean}
+ */
+ bIsGlobal = 'toplevel' === oSyntacticCodeUnit[0],
+ /**
+ * Indicates whether the whole scope is being examined.
+ * @type {boolean}
+ */
+ bIsWhollyExaminable = !bIsGlobal,
+ /**
+ * An array-like object representing source elements that constitute a
+ * syntactic code unit.
+ * @type {!TSyntacticCodeUnit}
+ */
+ oSourceElements,
+ /**
+ * A record consisting of data about the source element that is
+ * currently being examined.
+ * @type {!TSourceElementsData}
+ */
+ oSourceElementData,
+ /**
+ * The scope of the syntactic code unit.
+ * @type {!TScope}
+ */
+ oScope,
+ /**
+ * An instance of an object that allows the traversal of an AST.
+ * @type {!TWalker}
+ */
+ oWalker,
+ /**
+ * An object encompassing collections of functions used during the
+ * traversal of an AST.
+ * @namespace
+ * @type {!Object.>}
+ */
+ oWalkers = {
+ /**
+ * A collection of functions used during the surveyance of source
+ * elements.
+ * @namespace
+ * @type {!Object.}
+ */
+ oSurveySourceElement: {
+ /**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
+ /**
+ * Classifies the source element as excludable if it does not
+ * contain a {@code with} statement or the {@code eval} identifier
+ * name. Adds the identifier of the function and its formal
+ * parameters to the list of identifier names found.
+ * @param {string} sIdentifier The identifier of the function.
+ * @param {!Array.} aFormalParameterList Formal parameters.
+ * @param {!TSyntacticCodeUnit} oFunctionBody Function code.
+ */
+ 'defun': function(
+ sIdentifier,
+ aFormalParameterList,
+ oFunctionBody) {
+ fClassifyAsExcludable();
+ fAddIdentifier(sIdentifier);
+ aFormalParameterList.forEach(fAddIdentifier);
+ },
+ /**
+ * Increments the count of the number of occurrences of the String
+ * value that is equivalent to the sequence of terminal symbols
+ * that constitute the encountered identifier name.
+ * @param {!TSyntacticCodeUnit} oExpression The nonterminal
+ * MemberExpression.
+ * @param {string} sIdentifierName The identifier name used as the
+ * property accessor.
+ * @return {!Array} The encountered branch of an AST with its nonterminal
+ * MemberExpression traversed.
+ */
+ 'dot': function(oExpression, sIdentifierName) {
+ fCountPrimaryExpression(
+ EPrimaryExpressionCategories.N_IDENTIFIER_NAMES,
+ EValuePrefixes.S_STRING + sIdentifierName);
+ return ['dot', oWalker.walk(oExpression), sIdentifierName];
+ },
+ /**
+ * Adds the optional identifier of the function and its formal
+ * parameters to the list of identifier names found.
+ * @param {?string} sIdentifier The optional identifier of the
+ * function.
+ * @param {!Array.} aFormalParameterList Formal parameters.
+ * @param {!TSyntacticCodeUnit} oFunctionBody Function code.
+ */
+ 'function': function(
+ sIdentifier,
+ aFormalParameterList,
+ oFunctionBody) {
+ if ('string' === typeof sIdentifier) {
+ fAddIdentifier(sIdentifier);
+ }
+ aFormalParameterList.forEach(fAddIdentifier);
+ },
+ /**
+ * Either increments the count of the number of occurrences of the
+ * encountered null or Boolean value or classifies a source element
+ * as containing the {@code eval} identifier name.
+ * @param {string} sIdentifier The identifier encountered.
+ */
+ 'name': function(sIdentifier) {
+ if (-1 !== A_OTHER_SUBSTITUTABLE_LITERALS.indexOf(sIdentifier)) {
+ fCountPrimaryExpression(
+ EPrimaryExpressionCategories.N_NULL_AND_BOOLEAN_LITERALS,
+ EValuePrefixes.S_SYMBOLIC + sIdentifier);
+ } else {
+ if ('eval' === sIdentifier) {
+ oSourceElementData.nCategory =
+ ESourceElementCategories.N_EVAL;
+ }
+ fAddIdentifier(sIdentifier);
+ }
+ },
+ /**
+ * Classifies the source element as excludable if it does not
+ * contain a {@code with} statement or the {@code eval} identifier
+ * name.
+ * @param {TSyntacticCodeUnit} oExpression The expression whose
+ * value is to be returned.
+ */
+ 'return': function(oExpression) {
+ fClassifyAsExcludable();
+ },
+ /**
+ * Increments the count of the number of occurrences of the
+ * encountered String value.
+ * @param {string} sStringValue The String value of the string
+ * literal encountered.
+ */
+ 'string': function(sStringValue) {
+ if (sStringValue.length > 0) {
+ fCountPrimaryExpression(
+ EPrimaryExpressionCategories.N_STRING_LITERALS,
+ EValuePrefixes.S_STRING + sStringValue);
+ }
+ },
+ /**
+ * Adds the identifier reserved for an exception to the list of
+ * identifier names found.
+ * @param {!TSyntacticCodeUnit} oTry A block of code in which an
+ * exception can occur.
+ * @param {Array} aCatch The identifier reserved for an exception
+ * and a block of code to handle the exception.
+ * @param {TSyntacticCodeUnit} oFinally An optional block of code
+ * to be evaluated regardless of whether an exception occurs.
+ */
+ 'try': function(oTry, aCatch, oFinally) {
+ if (Array.isArray(aCatch)) {
+ fAddIdentifier(aCatch[0]);
+ }
+ },
+ /**
+ * Classifies the source element as excludable if it does not
+ * contain a {@code with} statement or the {@code eval} identifier
+ * name. Adds the identifier of each declared variable to the list
+ * of identifier names found.
+ * @param {!Array.} aVariableDeclarationList Variable
+ * declarations.
+ */
+ 'var': function(aVariableDeclarationList) {
+ fClassifyAsExcludable();
+ aVariableDeclarationList.forEach(fAddVariable);
+ },
+ /**
+ * Classifies a source element as containing the {@code with}
+ * statement.
+ * @param {!TSyntacticCodeUnit} oExpression An expression whose
+ * value is to be converted to a value of type Object and
+ * become the binding object of a new object environment
+ * record of a new lexical environment in which the statement
+ * is to be executed.
+ * @param {!TSyntacticCodeUnit} oStatement The statement to be
+ * executed in the augmented lexical environment.
+ * @return {!Array} An empty array to stop the traversal.
+ */
+ 'with': function(oExpression, oStatement) {
+ oSourceElementData.nCategory = ESourceElementCategories.N_WITH;
+ return [];
+ }
+ /**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
+ },
+ /**
+ * A collection of functions used while looking for nested functions.
+ * @namespace
+ * @type {!Object.}
+ */
+ oExamineFunctions: {
+ /**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
+ /**
+ * Orders an examination of a nested function declaration.
+ * @this {!TSyntacticCodeUnit} An array-like object representing
+ * the branch of an AST representing the syntactic code unit along with
+ * its scope.
+ * @return {!Array} An empty array to stop the traversal.
+ */
+ 'defun': function() {
+ fExamineSyntacticCodeUnit(this);
+ return [];
+ },
+ /**
+ * Orders an examination of a nested function expression.
+ * @this {!TSyntacticCodeUnit} An array-like object representing
+ * the branch of an AST representing the syntactic code unit along with
+ * its scope.
+ * @return {!Array} An empty array to stop the traversal.
+ */
+ 'function': function() {
+ fExamineSyntacticCodeUnit(this);
+ return [];
+ }
+ /**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
+ }
+ },
+ /**
+ * Records containing data about source elements.
+ * @type {Array.}
+ */
+ aSourceElementsData = [],
+ /**
+ * The index (in the source text order) of the source element
+ * immediately following a Directive Prologue.
+ * @type {number}
+ */
+ nAfterDirectivePrologue = 0,
+ /**
+ * The index (in the source text order) of the source element that is
+ * currently being considered.
+ * @type {number}
+ */
+ nPosition,
+ /**
+ * The index (in the source text order) of the source element that is
+ * the last element of the range of source elements that is currently
+ * being considered.
+ * @type {(undefined|number)}
+ */
+ nTo,
+ /**
+ * Initiates the traversal of a source element.
+ * @param {!TWalker} oWalker An instance of an object that allows the
+ * traversal of an abstract syntax tree.
+ * @param {!TSyntacticCodeUnit} oSourceElement A source element from
+ * which the traversal should commence.
+ * @return {function(): !TSyntacticCodeUnit} A function that is able to
+ * initiate the traversal from a given source element.
+ */
+ cContext = function(oWalker, oSourceElement) {
+ /**
+ * @return {!TSyntacticCodeUnit} A function that is able to
+ * initiate the traversal from a given source element.
+ */
+ var fLambda = function() {
+ return oWalker.walk(oSourceElement);
+ };
+
+ return fLambda;
+ },
+ /**
+ * Classifies the source element as excludable if it does not
+ * contain a {@code with} statement or the {@code eval} identifier
+ * name.
+ */
+ fClassifyAsExcludable = function() {
+ if (oSourceElementData.nCategory ===
+ ESourceElementCategories.N_OTHER) {
+ oSourceElementData.nCategory =
+ ESourceElementCategories.N_EXCLUDABLE;
+ }
+ },
+ /**
+ * Adds an identifier to the list of identifier names found.
+ * @param {string} sIdentifier The identifier to be added.
+ */
+ fAddIdentifier = function(sIdentifier) {
+ if (-1 === oSourceElementData.aIdentifiers.indexOf(sIdentifier)) {
+ oSourceElementData.aIdentifiers.push(sIdentifier);
+ }
+ },
+ /**
+ * Adds the identifier of a variable to the list of identifier names
+ * found.
+ * @param {!Array} aVariableDeclaration A variable declaration.
+ */
+ fAddVariable = function(aVariableDeclaration) {
+ fAddIdentifier(/** @type {string} */ aVariableDeclaration[0]);
+ },
+ /**
+ * Increments the count of the number of occurrences of the prefixed
+ * String representation attributed to the primary expression.
+ * @param {number} nCategory The category of the primary expression.
+ * @param {string} sName The prefixed String representation attributed
+ * to the primary expression.
+ */
+ fCountPrimaryExpression = function(nCategory, sName) {
+ if (!oSourceElementData.aCount[nCategory].hasOwnProperty(sName)) {
+ oSourceElementData.aCount[nCategory][sName] = 0;
+ if (-1 === oSourceElementData.aPrimitiveValues.indexOf(sName)) {
+ oSourceElementData.aPrimitiveValues.push(sName);
+ }
+ }
+ oSourceElementData.aCount[nCategory][sName] += 1;
+ },
+ /**
+ * Consolidates all worthwhile primitive values in a range of source
+ * elements.
+ * @param {number} nFrom The index (in the source text order) of the
+ * source element that is the first element of the range.
+ * @param {number} nTo The index (in the source text order) of the
+ * source element that is the last element of the range.
+ * @param {boolean} bEnclose Indicates whether the range should be
+ * enclosed within a function call with no argument values to a
+ * function with an empty parameter list if any primitive values
+ * are consolidated.
+ * @see TPrimitiveValue#nSaving
+ */
+ fExamineSourceElements = function(nFrom, nTo, bEnclose) {
+ var _,
+ /**
+ * The index of the last mangled name.
+ * @type {number}
+ */
+ nIndex = oScope.cname,
+ /**
+ * The index of the source element that is currently being
+ * considered.
+ * @type {number}
+ */
+ nPosition,
+ /**
+ * A collection of functions used during the consolidation of
+ * primitive values and identifier names used as property
+ * accessors.
+ * @namespace
+ * @type {!Object.}
+ */
+ oWalkersTransformers = {
+ /**
+ * If the String value that is equivalent to the sequence of
+ * terminal symbols that constitute the encountered identifier
+ * name is worthwhile, a syntactic conversion from the dot
+ * notation to the bracket notation ensues with that sequence
+ * being substituted by an identifier name to which the value
+ * is assigned.
+ * Applies to property accessors that use the dot notation.
+ * @param {!TSyntacticCodeUnit} oExpression The nonterminal
+ * MemberExpression.
+ * @param {string} sIdentifierName The identifier name used as
+ * the property accessor.
+ * @return {!Array} A syntactic code unit that is equivalent to
+ * the one encountered.
+ * @see TPrimitiveValue#nSaving
+ */
+ 'dot': function(oExpression, sIdentifierName) {
+ /**
+ * The prefixed String value that is equivalent to the
+ * sequence of terminal symbols that constitute the
+ * encountered identifier name.
+ * @type {string}
+ */
+ var sPrefixed = EValuePrefixes.S_STRING + sIdentifierName;
+
+ return oSolutionBest.oPrimitiveValues.hasOwnProperty(
+ sPrefixed) &&
+ oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
+ ['sub',
+ oWalker.walk(oExpression),
+ ['name',
+ oSolutionBest.oPrimitiveValues[sPrefixed].sName]] :
+ ['dot', oWalker.walk(oExpression), sIdentifierName];
+ },
+ /**
+ * If the encountered identifier is a null or Boolean literal
+ * and its value is worthwhile, the identifier is substituted
+ * by an identifier name to which that value is assigned.
+ * Applies to identifier names.
+ * @param {string} sIdentifier The identifier encountered.
+ * @return {!Array} A syntactic code unit that is equivalent to
+ * the one encountered.
+ * @see TPrimitiveValue#nSaving
+ */
+ 'name': function(sIdentifier) {
+ /**
+ * The prefixed representation String of the identifier.
+ * @type {string}
+ */
+ var sPrefixed = EValuePrefixes.S_SYMBOLIC + sIdentifier;
+
+ return [
+ 'name',
+ oSolutionBest.oPrimitiveValues.hasOwnProperty(sPrefixed) &&
+ oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
+ oSolutionBest.oPrimitiveValues[sPrefixed].sName :
+ sIdentifier
+ ];
+ },
+ /**
+ * If the encountered String value is worthwhile, it is
+ * substituted by an identifier name to which that value is
+ * assigned.
+ * Applies to String values.
+ * @param {string} sStringValue The String value of the string
+ * literal encountered.
+ * @return {!Array} A syntactic code unit that is equivalent to
+ * the one encountered.
+ * @see TPrimitiveValue#nSaving
+ */
+ 'string': function(sStringValue) {
+ /**
+ * The prefixed representation String of the primitive value
+ * of the literal.
+ * @type {string}
+ */
+ var sPrefixed =
+ EValuePrefixes.S_STRING + sStringValue;
+
+ return oSolutionBest.oPrimitiveValues.hasOwnProperty(
+ sPrefixed) &&
+ oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
+ ['name',
+ oSolutionBest.oPrimitiveValues[sPrefixed].sName] :
+ ['string', sStringValue];
+ }
+ },
+ /**
+ * Such data on what to consolidate within the range of source
+ * elements that is currently being considered that lead to the
+ * greatest known reduction of the number of the terminal symbols
+ * in comparison to the original source text.
+ * @type {!TSolution}
+ */
+ oSolutionBest = new TSolution(),
+ /**
+ * Data representing an ongoing attempt to find a better
+ * reduction of the number of the terminal symbols in comparison
+ * to the original source text than the best one that is
+ * currently known.
+ * @type {!TSolution}
+ * @see oSolutionBest
+ */
+ oSolutionCandidate = new TSolution(),
+ /**
+ * A record consisting of data about the range of source elements
+ * that is currently being examined.
+ * @type {!TSourceElementsData}
+ */
+ oSourceElementsData = new TSourceElementsData(),
+ /**
+ * Variable declarations for each primitive value that is to be
+ * consolidated within the elements.
+ * @type {!Array.}
+ */
+ aVariableDeclarations = [],
+ /**
+ * Augments a list with a prefixed representation String.
+ * @param {!Array.} aList A list that is to be augmented.
+ * @return {function(string)} A function that augments a list
+ * with a prefixed representation String.
+ */
+ cAugmentList = function(aList) {
+ /**
+ * @param {string} sPrefixed Prefixed representation String of
+ * a primitive value that could be consolidated within the
+ * elements.
+ */
+ var fLambda = function(sPrefixed) {
+ if (-1 === aList.indexOf(sPrefixed)) {
+ aList.push(sPrefixed);
+ }
+ };
+
+ return fLambda;
+ },
+ /**
+ * Adds the number of occurrences of a primitive value of a given
+ * category that could be consolidated in the source element with
+ * a given index to the count of occurrences of that primitive
+ * value within the range of source elements that is currently
+ * being considered.
+ * @param {number} nPosition The index (in the source text order)
+ * of a source element.
+ * @param {number} nCategory The category of the primary
+ * expression from which the primitive value is derived.
+ * @return {function(string)} A function that performs the
+ * addition.
+ * @see cAddOccurrencesInCategory
+ */
+ cAddOccurrences = function(nPosition, nCategory) {
+ /**
+ * @param {string} sPrefixed The prefixed representation String
+ * of a primitive value.
+ */
+ var fLambda = function(sPrefixed) {
+ if (!oSourceElementsData.aCount[nCategory].hasOwnProperty(
+ sPrefixed)) {
+ oSourceElementsData.aCount[nCategory][sPrefixed] = 0;
+ }
+ oSourceElementsData.aCount[nCategory][sPrefixed] +=
+ aSourceElementsData[nPosition].aCount[nCategory][
+ sPrefixed];
+ };
+
+ return fLambda;
+ },
+ /**
+ * Adds the number of occurrences of each primitive value of a
+ * given category that could be consolidated in the source
+ * element with a given index to the count of occurrences of that
+ * primitive values within the range of source elements that is
+ * currently being considered.
+ * @param {number} nPosition The index (in the source text order)
+ * of a source element.
+ * @return {function(number)} A function that performs the
+ * addition.
+ * @see fAddOccurrences
+ */
+ cAddOccurrencesInCategory = function(nPosition) {
+ /**
+ * @param {number} nCategory The category of the primary
+ * expression from which the primitive value is derived.
+ */
+ var fLambda = function(nCategory) {
+ Object.keys(
+ aSourceElementsData[nPosition].aCount[nCategory]
+ ).forEach(cAddOccurrences(nPosition, nCategory));
+ };
+
+ return fLambda;
+ },
+ /**
+ * Adds the number of occurrences of each primitive value that
+ * could be consolidated in the source element with a given index
+ * to the count of occurrences of that primitive values within
+ * the range of source elements that is currently being
+ * considered.
+ * @param {number} nPosition The index (in the source text order)
+ * of a source element.
+ */
+ fAddOccurrences = function(nPosition) {
+ Object.keys(aSourceElementsData[nPosition].aCount).forEach(
+ cAddOccurrencesInCategory(nPosition));
+ },
+ /**
+ * Creates a variable declaration for a primitive value if that
+ * primitive value is to be consolidated within the elements.
+ * @param {string} sPrefixed Prefixed representation String of a
+ * primitive value that could be consolidated within the
+ * elements.
+ * @see aVariableDeclarations
+ */
+ cAugmentVariableDeclarations = function(sPrefixed) {
+ if (oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0) {
+ aVariableDeclarations.push([
+ oSolutionBest.oPrimitiveValues[sPrefixed].sName,
+ [0 === sPrefixed.indexOf(EValuePrefixes.S_SYMBOLIC) ?
+ 'name' : 'string',
+ sPrefixed.substring(EValuePrefixes.S_SYMBOLIC.length)]
+ ]);
+ }
+ },
+ /**
+ * Sorts primitive values with regard to the difference in the
+ * number of terminal symbols between the original source text
+ * and the one with those primitive values consolidated.
+ * @param {string} sPrefixed0 The prefixed representation String
+ * of the first of the two primitive values that are being
+ * compared.
+ * @param {string} sPrefixed1 The prefixed representation String
+ * of the second of the two primitive values that are being
+ * compared.
+ * @return {number}
+ *
+ *
-1
+ *
if the first primitive value must be placed before
+ * the other one,
+ *
0
+ *
if the first primitive value may be placed before
+ * the other one,
+ *
1
+ *
if the first primitive value must not be placed
+ * before the other one.
the difference in the number of terminal symbols
+ * between the original source text and the one with the
+ * first primitive value consolidated, and
+ *
the difference in the number of terminal symbols
+ * between the original source text and the one with the
+ * second primitive value consolidated.
+ *
+ * @type {number}
+ */
+ var nDifference =
+ oSolutionCandidate.oPrimitiveValues[sPrefixed0].nSaving -
+ oSolutionCandidate.oPrimitiveValues[sPrefixed1].nSaving;
+
+ return nDifference > 0 ? -1 : nDifference < 0 ? 1 : 0;
+ },
+ /**
+ * Assigns an identifier name to a primitive value and calculates
+ * whether instances of that primitive value are worth
+ * consolidating.
+ * @param {string} sPrefixed The prefixed representation String
+ * of a primitive value that is being evaluated.
+ */
+ fEvaluatePrimitiveValue = function(sPrefixed) {
+ var _,
+ /**
+ * The index of the last mangled name.
+ * @type {number}
+ */
+ nIndex,
+ /**
+ * The representation String of the primitive value that is
+ * being evaluated.
+ * @type {string}
+ */
+ sName =
+ sPrefixed.substring(EValuePrefixes.S_SYMBOLIC.length),
+ /**
+ * The number of source characters taken up by the
+ * representation String of the primitive value that is
+ * being evaluated.
+ * @type {number}
+ */
+ nLengthOriginal = sName.length,
+ /**
+ * The number of source characters taken up by the
+ * identifier name that could substitute the primitive
+ * value that is being evaluated.
+ * substituted.
+ * @type {number}
+ */
+ nLengthSubstitution,
+ /**
+ * The number of source characters taken up by by the
+ * representation String of the primitive value that is
+ * being evaluated when it is represented by a string
+ * literal.
+ * @type {number}
+ */
+ nLengthString = oProcessor.make_string(sName).length;
+
+ oSolutionCandidate.oPrimitiveValues[sPrefixed] =
+ new TPrimitiveValue();
+ do { // Find an identifier unused in this or any nested scope.
+ nIndex = oScope.cname;
+ oSolutionCandidate.oPrimitiveValues[sPrefixed].sName =
+ oScope.next_mangled();
+ } while (-1 !== oSourceElementsData.aIdentifiers.indexOf(
+ oSolutionCandidate.oPrimitiveValues[sPrefixed].sName));
+ nLengthSubstitution = oSolutionCandidate.oPrimitiveValues[
+ sPrefixed].sName.length;
+ if (0 === sPrefixed.indexOf(EValuePrefixes.S_SYMBOLIC)) {
+ // foo:null, or foo:null;
+ oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving -=
+ nLengthSubstitution + nLengthOriginal +
+ oWeights.N_VARIABLE_DECLARATION;
+ // null vs foo
+ oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
+ oSourceElementsData.aCount[
+ EPrimaryExpressionCategories.
+ N_NULL_AND_BOOLEAN_LITERALS][sPrefixed] *
+ (nLengthOriginal - nLengthSubstitution);
+ } else {
+ // foo:'fromCharCode';
+ oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving -=
+ nLengthSubstitution + nLengthString +
+ oWeights.N_VARIABLE_DECLARATION;
+ // .fromCharCode vs [foo]
+ if (oSourceElementsData.aCount[
+ EPrimaryExpressionCategories.N_IDENTIFIER_NAMES
+ ].hasOwnProperty(sPrefixed)) {
+ oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
+ oSourceElementsData.aCount[
+ EPrimaryExpressionCategories.N_IDENTIFIER_NAMES
+ ][sPrefixed] *
+ (nLengthOriginal - nLengthSubstitution -
+ oWeights.N_PROPERTY_ACCESSOR);
+ }
+ // 'fromCharCode' vs foo
+ if (oSourceElementsData.aCount[
+ EPrimaryExpressionCategories.N_STRING_LITERALS
+ ].hasOwnProperty(sPrefixed)) {
+ oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
+ oSourceElementsData.aCount[
+ EPrimaryExpressionCategories.N_STRING_LITERALS
+ ][sPrefixed] *
+ (nLengthString - nLengthSubstitution);
+ }
+ }
+ if (oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving >
+ 0) {
+ oSolutionCandidate.nSavings +=
+ oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving;
+ } else {
+ oScope.cname = nIndex; // Free the identifier name.
+ }
+ },
+ /**
+ * Adds a variable declaration to an existing variable statement.
+ * @param {!Array} aVariableDeclaration A variable declaration
+ * with an initialiser.
+ */
+ cAddVariableDeclaration = function(aVariableDeclaration) {
+ (/** @type {!Array} */ oSourceElements[nFrom][1]).unshift(
+ aVariableDeclaration);
+ };
+
+ if (nFrom > nTo) {
+ return;
+ }
+ // If the range is a closure, reuse the closure.
+ if (nFrom === nTo &&
+ 'stat' === oSourceElements[nFrom][0] &&
+ 'call' === oSourceElements[nFrom][1][0] &&
+ 'function' === oSourceElements[nFrom][1][1][0]) {
+ fExamineSyntacticCodeUnit(oSourceElements[nFrom][1][1]);
+ return;
+ }
+ // Create a list of all derived primitive values within the range.
+ for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
+ aSourceElementsData[nPosition].aPrimitiveValues.forEach(
+ cAugmentList(oSourceElementsData.aPrimitiveValues));
+ }
+ if (0 === oSourceElementsData.aPrimitiveValues.length) {
+ return;
+ }
+ for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
+ // Add the number of occurrences to the total count.
+ fAddOccurrences(nPosition);
+ // Add identifiers of this or any nested scope to the list.
+ aSourceElementsData[nPosition].aIdentifiers.forEach(
+ cAugmentList(oSourceElementsData.aIdentifiers));
+ }
+ // Distribute identifier names among derived primitive values.
+ do { // If there was any progress, find a better distribution.
+ oSolutionBest = oSolutionCandidate;
+ if (Object.keys(oSolutionCandidate.oPrimitiveValues).length > 0) {
+ // Sort primitive values descending by their worthwhileness.
+ oSourceElementsData.aPrimitiveValues.sort(cSortPrimitiveValues);
+ }
+ oSolutionCandidate = new TSolution();
+ oSourceElementsData.aPrimitiveValues.forEach(
+ fEvaluatePrimitiveValue);
+ oScope.cname = nIndex;
+ } while (oSolutionCandidate.nSavings > oSolutionBest.nSavings);
+ // Take the necessity of adding a variable statement into account.
+ if ('var' !== oSourceElements[nFrom][0]) {
+ oSolutionBest.nSavings -= oWeights.N_VARIABLE_STATEMENT_AFFIXATION;
+ }
+ if (bEnclose) {
+ // Take the necessity of forming a closure into account.
+ oSolutionBest.nSavings -= oWeights.N_CLOSURE;
+ }
+ if (oSolutionBest.nSavings > 0) {
+ // Create variable declarations suitable for UglifyJS.
+ Object.keys(oSolutionBest.oPrimitiveValues).forEach(
+ cAugmentVariableDeclarations);
+ // Rewrite expressions that contain worthwhile primitive values.
+ for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
+ oWalker = oProcessor.ast_walker();
+ oSourceElements[nPosition] =
+ oWalker.with_walkers(
+ oWalkersTransformers,
+ cContext(oWalker, oSourceElements[nPosition]));
+ }
+ if ('var' === oSourceElements[nFrom][0]) { // Reuse the statement.
+ (/** @type {!Array.} */ aVariableDeclarations.reverse(
+ )).forEach(cAddVariableDeclaration);
+ } else { // Add a variable statement.
+ Array.prototype.splice.call(
+ oSourceElements,
+ nFrom,
+ 0,
+ ['var', aVariableDeclarations]);
+ nTo += 1;
+ }
+ if (bEnclose) {
+ // Add a closure.
+ Array.prototype.splice.call(
+ oSourceElements,
+ nFrom,
+ 0,
+ ['stat', ['call', ['function', null, [], []], []]]);
+ // Copy source elements into the closure.
+ for (nPosition = nTo + 1; nPosition > nFrom; nPosition -= 1) {
+ Array.prototype.unshift.call(
+ oSourceElements[nFrom][1][1][3],
+ oSourceElements[nPosition]);
+ }
+ // Remove source elements outside the closure.
+ Array.prototype.splice.call(
+ oSourceElements,
+ nFrom + 1,
+ nTo - nFrom + 1);
+ }
+ }
+ if (bEnclose) {
+ // Restore the availability of identifier names.
+ oScope.cname = nIndex;
+ }
+ };
+
+ oSourceElements = (/** @type {!TSyntacticCodeUnit} */
+ oSyntacticCodeUnit[bIsGlobal ? 1 : 3]);
+ if (0 === oSourceElements.length) {
+ return;
+ }
+ oScope = bIsGlobal ? oSyntacticCodeUnit.scope : oSourceElements.scope;
+ // Skip a Directive Prologue.
+ while (nAfterDirectivePrologue < oSourceElements.length &&
+ 'stat' === oSourceElements[nAfterDirectivePrologue][0] &&
+ 'string' === oSourceElements[nAfterDirectivePrologue][1][0]) {
+ nAfterDirectivePrologue += 1;
+ aSourceElementsData.push(null);
+ }
+ if (oSourceElements.length === nAfterDirectivePrologue) {
+ return;
+ }
+ for (nPosition = nAfterDirectivePrologue;
+ nPosition < oSourceElements.length;
+ nPosition += 1) {
+ oSourceElementData = new TSourceElementsData();
+ oWalker = oProcessor.ast_walker();
+ // Classify a source element.
+ // Find its derived primitive values and count their occurrences.
+ // Find all identifiers used (including nested scopes).
+ oWalker.with_walkers(
+ oWalkers.oSurveySourceElement,
+ cContext(oWalker, oSourceElements[nPosition]));
+ // Establish whether the scope is still wholly examinable.
+ bIsWhollyExaminable = bIsWhollyExaminable &&
+ ESourceElementCategories.N_WITH !== oSourceElementData.nCategory &&
+ ESourceElementCategories.N_EVAL !== oSourceElementData.nCategory;
+ aSourceElementsData.push(oSourceElementData);
+ }
+ if (bIsWhollyExaminable) { // Examine the whole scope.
+ fExamineSourceElements(
+ nAfterDirectivePrologue,
+ oSourceElements.length - 1,
+ false);
+ } else { // Examine unexcluded ranges of source elements.
+ for (nPosition = oSourceElements.length - 1;
+ nPosition >= nAfterDirectivePrologue;
+ nPosition -= 1) {
+ oSourceElementData = (/** @type {!TSourceElementsData} */
+ aSourceElementsData[nPosition]);
+ if (ESourceElementCategories.N_OTHER ===
+ oSourceElementData.nCategory) {
+ if ('undefined' === typeof nTo) {
+ nTo = nPosition; // Indicate the end of a range.
+ }
+ // Examine the range if it immediately follows a Directive Prologue.
+ if (nPosition === nAfterDirectivePrologue) {
+ fExamineSourceElements(nPosition, nTo, true);
+ }
+ } else {
+ if ('undefined' !== typeof nTo) {
+ // Examine the range that immediately follows this source element.
+ fExamineSourceElements(nPosition + 1, nTo, true);
+ nTo = void 0; // Obliterate the range.
+ }
+ // Examine nested functions.
+ oWalker = oProcessor.ast_walker();
+ oWalker.with_walkers(
+ oWalkers.oExamineFunctions,
+ cContext(oWalker, oSourceElements[nPosition]));
+ }
+ }
+ }
+ }(oAbstractSyntaxTree = oProcessor.ast_add_scope(oAbstractSyntaxTree)));
+ return oAbstractSyntaxTree;
+};
+/*jshint sub:false */
+
+
+if (require.main === module) {
+ (function() {
+ 'use strict';
+ /*jshint bitwise:true, curly:true, eqeqeq:true, forin:true, immed:true,
+ latedef:true, newcap:true, noarge:true, noempty:true, nonew:true,
+ onevar:true, plusplus:true, regexp:true, undef:true, strict:true,
+ sub:false, trailing:true */
+
+ var _,
+ /**
+ * NodeJS module for unit testing.
+ * @namespace
+ * @type {!TAssert}
+ * @see http://nodejs.org/docs/v0.6.10/api/all.html#assert
+ */
+ oAssert = (/** @type {!TAssert} */ require('assert')),
+ /**
+ * The parser of ECMA-262 found in UglifyJS.
+ * @namespace
+ * @type {!TParser}
+ */
+ oParser = (/** @type {!TParser} */ require('./parse-js')),
+ /**
+ * The processor of ASTs
+ * found in UglifyJS.
+ * @namespace
+ * @type {!TProcessor}
+ */
+ oProcessor = (/** @type {!TProcessor} */ require('./process')),
+ /**
+ * An instance of an object that allows the traversal of an AST.
+ * @type {!TWalker}
+ */
+ oWalker,
+ /**
+ * A collection of functions for the removal of the scope information
+ * during the traversal of an AST.
+ * @namespace
+ * @type {!Object.}
+ */
+ oWalkersPurifiers = {
+ /**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
+ /**
+ * Deletes the scope information from the branch of the abstract
+ * syntax tree representing the encountered function declaration.
+ * @param {string} sIdentifier The identifier of the function.
+ * @param {!Array.} aFormalParameterList Formal parameters.
+ * @param {!TSyntacticCodeUnit} oFunctionBody Function code.
+ */
+ 'defun': function(
+ sIdentifier,
+ aFormalParameterList,
+ oFunctionBody) {
+ delete oFunctionBody.scope;
+ },
+ /**
+ * Deletes the scope information from the branch of the abstract
+ * syntax tree representing the encountered function expression.
+ * @param {?string} sIdentifier The optional identifier of the
+ * function.
+ * @param {!Array.} aFormalParameterList Formal parameters.
+ * @param {!TSyntacticCodeUnit} oFunctionBody Function code.
+ */
+ 'function': function(
+ sIdentifier,
+ aFormalParameterList,
+ oFunctionBody) {
+ delete oFunctionBody.scope;
+ }
+ /**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
+ },
+ /**
+ * Initiates the traversal of a source element.
+ * @param {!TWalker} oWalker An instance of an object that allows the
+ * traversal of an abstract syntax tree.
+ * @param {!TSyntacticCodeUnit} oSourceElement A source element from
+ * which the traversal should commence.
+ * @return {function(): !TSyntacticCodeUnit} A function that is able to
+ * initiate the traversal from a given source element.
+ */
+ cContext = function(oWalker, oSourceElement) {
+ /**
+ * @return {!TSyntacticCodeUnit} A function that is able to
+ * initiate the traversal from a given source element.
+ */
+ var fLambda = function() {
+ return oWalker.walk(oSourceElement);
+ };
+
+ return fLambda;
+ },
+ /**
+ * A record consisting of configuration for the code generation phase.
+ * @type {!Object}
+ */
+ oCodeGenerationOptions = {
+ beautify: true
+ },
+ /**
+ * Tests whether consolidation of an ECMAScript program yields expected
+ * results.
+ * @param {{
+ * sTitle: string,
+ * sInput: string,
+ * sOutput: string
+ * }} oUnitTest A record consisting of data about a unit test: its
+ * name, an ECMAScript program, and, if consolidation is to take
+ * place, the resulting ECMAScript program.
+ */
+ cAssert = function(oUnitTest) {
+ var _,
+ /**
+ * An array-like object representing the AST obtained after consolidation.
+ * @type {!TSyntacticCodeUnit}
+ */
+ oSyntacticCodeUnitActual =
+ exports.ast_consolidate(oParser.parse(oUnitTest.sInput)),
+ /**
+ * An array-like object representing the expected AST.
+ * @type {!TSyntacticCodeUnit}
+ */
+ oSyntacticCodeUnitExpected = oParser.parse(
+ oUnitTest.hasOwnProperty('sOutput') ?
+ oUnitTest.sOutput : oUnitTest.sInput);
+
+ delete oSyntacticCodeUnitActual.scope;
+ oWalker = oProcessor.ast_walker();
+ oWalker.with_walkers(
+ oWalkersPurifiers,
+ cContext(oWalker, oSyntacticCodeUnitActual));
+ try {
+ oAssert.deepEqual(
+ oSyntacticCodeUnitActual,
+ oSyntacticCodeUnitExpected);
+ } catch (oException) {
+ console.error(
+ '########## A unit test has failed.\n' +
+ oUnitTest.sTitle + '\n' +
+ '##### actual code (' +
+ oProcessor.gen_code(oSyntacticCodeUnitActual).length +
+ ' bytes)\n' +
+ oProcessor.gen_code(
+ oSyntacticCodeUnitActual,
+ oCodeGenerationOptions) + '\n' +
+ '##### expected code (' +
+ oProcessor.gen_code(oSyntacticCodeUnitExpected).length +
+ ' bytes)\n' +
+ oProcessor.gen_code(
+ oSyntacticCodeUnitExpected,
+ oCodeGenerationOptions));
+ }
+ };
+
+ [
+ // 7.6.1 Reserved Words.
+ {
+ sTitle:
+ 'Omission of keywords while choosing an identifier name.',
+ sInput:
+ '(function() {' +
+ ' var a, b, c, d, e, f, g, h, i, j, k, l, m,' +
+ ' n, o, p, q, r, s, t, u, v, w, x, y, z,' +
+ ' A, B, C, D, E, F, G, H, I, J, K, L, M,' +
+ ' N, O, P, Q, R, S, T, U, V, W, X, Y, Z,' +
+ ' $, _,' +
+ ' aa, ab, ac, ad, ae, af, ag, ah, ai, aj, ak, al, am,' +
+ ' an, ao, ap, aq, ar, as, at, au, av, aw, ax, ay, az,' +
+ ' aA, aB, aC, aD, aE, aF, aG, aH, aI, aJ, aK, aL, aM,' +
+ ' aN, aO, aP, aQ, aR, aS, aT, aU, aV, aW, aX, aY, aZ,' +
+ ' a$, a_,' +
+ ' ba, bb, bc, bd, be, bf, bg, bh, bi, bj, bk, bl, bm,' +
+ ' bn, bo, bp, bq, br, bs, bt, bu, bv, bw, bx, by, bz,' +
+ ' bA, bB, bC, bD, bE, bF, bG, bH, bI, bJ, bK, bL, bM,' +
+ ' bN, bO, bP, bQ, bR, bS, bT, bU, bV, bW, bX, bY, bZ,' +
+ ' b$, b_,' +
+ ' ca, cb, cc, cd, ce, cf, cg, ch, ci, cj, ck, cl, cm,' +
+ ' cn, co, cp, cq, cr, cs, ct, cu, cv, cw, cx, cy, cz,' +
+ ' cA, cB, cC, cD, cE, cF, cG, cH, cI, cJ, cK, cL, cM,' +
+ ' cN, cO, cP, cQ, cR, cS, cT, cU, cV, cW, cX, cY, cZ,' +
+ ' c$, c_,' +
+ ' da, db, dc, dd, de, df, dg, dh, di, dj, dk, dl, dm,' +
+ ' dn, dq, dr, ds, dt, du, dv, dw, dx, dy, dz,' +
+ ' dA, dB, dC, dD, dE, dF, dG, dH, dI, dJ, dK, dL, dM,' +
+ ' dN, dO, dP, dQ, dR, dS, dT, dU, dV, dW, dX, dY, dZ,' +
+ ' d$, d_;' +
+ ' void ["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",' +
+ ' "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"];' +
+ '}());',
+ sOutput:
+ '(function() {' +
+ ' var dp =' +
+ ' "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",' +
+ ' a, b, c, d, e, f, g, h, i, j, k, l, m,' +
+ ' n, o, p, q, r, s, t, u, v, w, x, y, z,' +
+ ' A, B, C, D, E, F, G, H, I, J, K, L, M,' +
+ ' N, O, P, Q, R, S, T, U, V, W, X, Y, Z,' +
+ ' $, _,' +
+ ' aa, ab, ac, ad, ae, af, ag, ah, ai, aj, ak, al, am,' +
+ ' an, ao, ap, aq, ar, as, at, au, av, aw, ax, ay, az,' +
+ ' aA, aB, aC, aD, aE, aF, aG, aH, aI, aJ, aK, aL, aM,' +
+ ' aN, aO, aP, aQ, aR, aS, aT, aU, aV, aW, aX, aY, aZ,' +
+ ' a$, a_,' +
+ ' ba, bb, bc, bd, be, bf, bg, bh, bi, bj, bk, bl, bm,' +
+ ' bn, bo, bp, bq, br, bs, bt, bu, bv, bw, bx, by, bz,' +
+ ' bA, bB, bC, bD, bE, bF, bG, bH, bI, bJ, bK, bL, bM,' +
+ ' bN, bO, bP, bQ, bR, bS, bT, bU, bV, bW, bX, bY, bZ,' +
+ ' b$, b_,' +
+ ' ca, cb, cc, cd, ce, cf, cg, ch, ci, cj, ck, cl, cm,' +
+ ' cn, co, cp, cq, cr, cs, ct, cu, cv, cw, cx, cy, cz,' +
+ ' cA, cB, cC, cD, cE, cF, cG, cH, cI, cJ, cK, cL, cM,' +
+ ' cN, cO, cP, cQ, cR, cS, cT, cU, cV, cW, cX, cY, cZ,' +
+ ' c$, c_,' +
+ ' da, db, dc, dd, de, df, dg, dh, di, dj, dk, dl, dm,' +
+ ' dn, dq, dr, ds, dt, du, dv, dw, dx, dy, dz,' +
+ ' dA, dB, dC, dD, dE, dF, dG, dH, dI, dJ, dK, dL, dM,' +
+ ' dN, dO, dP, dQ, dR, dS, dT, dU, dV, dW, dX, dY, dZ,' +
+ ' d$, d_;' +
+ ' void [dp, dp];' +
+ '}());'
+ },
+ // 7.8.1 Null Literals.
+ {
+ sTitle:
+ 'Evaluation with regard to the null value.',
+ sInput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' var foo;' +
+ ' void [null, null, null];' +
+ '}());' +
+ 'eval("");' +
+ '(function() {' +
+ ' var foo;' +
+ ' void [null, null];' +
+ '}());',
+ sOutput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' var a = null, foo;' +
+ ' void [a, a, a];' +
+ '}());' +
+ 'eval("");' +
+ '(function() {' +
+ ' var foo;' +
+ ' void [null, null];' +
+ '}());'
+ },
+ // 7.8.2 Boolean Literals.
+ {
+ sTitle:
+ 'Evaluation with regard to the false value.',
+ sInput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' var foo;' +
+ ' void [false, false, false];' +
+ '}());' +
+ 'eval("");' +
+ '(function() {' +
+ ' var foo;' +
+ ' void [false, false];' +
+ '}());',
+ sOutput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' var a = false, foo;' +
+ ' void [a, a, a];' +
+ '}());' +
+ 'eval("");' +
+ '(function() {' +
+ ' var foo;' +
+ ' void [false, false];' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Evaluation with regard to the true value.',
+ sInput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' var foo;' +
+ ' void [true, true, true];' +
+ '}());' +
+ 'eval("");' +
+ '(function() {' +
+ ' var foo;' +
+ ' void [true, true];' +
+ '}());',
+ sOutput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' var a = true, foo;' +
+ ' void [a, a, a];' +
+ '}());' +
+ 'eval("");' +
+ '(function() {' +
+ ' var foo;' +
+ ' void [true, true];' +
+ '}());'
+ },
+ // 7.8.4 String Literals.
+ {
+ sTitle:
+ 'Evaluation with regard to the String value of a string literal.',
+ sInput:
+ '(function() {' +
+ ' var foo;' +
+ ' void ["abcd", "abcd", "abc", "abc"];' +
+ '}());',
+ sOutput:
+ '(function() {' +
+ ' var a = "abcd", foo;' +
+ ' void [a, a, "abc", "abc"];' +
+ '}());'
+ },
+ // 7.8.5 Regular Expression Literals.
+ {
+ sTitle:
+ 'Preservation of the pattern of a regular expression literal.',
+ sInput:
+ 'void [/abcdefghijklmnopqrstuvwxyz/, /abcdefghijklmnopqrstuvwxyz/];'
+ },
+ {
+ sTitle:
+ 'Preservation of the flags of a regular expression literal.',
+ sInput:
+ 'void [/(?:)/gim, /(?:)/gim, /(?:)/gim, /(?:)/gim, /(?:)/gim,' +
+ ' /(?:)/gim, /(?:)/gim, /(?:)/gim, /(?:)/gim, /(?:)/gim,' +
+ ' /(?:)/gim, /(?:)/gim, /(?:)/gim, /(?:)/gim, /(?:)/gim];'
+ },
+ // 10.2 Lexical Environments.
+ {
+ sTitle:
+ 'Preservation of identifier names in the same scope.',
+ sInput:
+ '/*jshint shadow:true */' +
+ 'var a;' +
+ 'function b(i) {' +
+ '}' +
+ 'for (var c; 0 === Math.random(););' +
+ 'for (var d in {});' +
+ 'void ["abcdefghijklmnopqrstuvwxyz"];' +
+ 'void [b(a), b(c), b(d)];' +
+ 'void [typeof e];' +
+ 'i: for (; 0 === Math.random();) {' +
+ ' if (42 === (new Date()).getMinutes()) {' +
+ ' continue i;' +
+ ' } else {' +
+ ' break i;' +
+ ' }' +
+ '}' +
+ 'try {' +
+ '} catch (f) {' +
+ '} finally {' +
+ '}' +
+ '(function g(h) {' +
+ '}());' +
+ 'void [{' +
+ ' i: 42,' +
+ ' "j": 42,' +
+ ' \'k\': 42' +
+ '}];' +
+ 'void ["abcdefghijklmnopqrstuvwxyz"];',
+ sOutput:
+ '/*jshint shadow:true */' +
+ 'var a;' +
+ 'function b(i) {' +
+ '}' +
+ 'for (var c; 0 === Math.random(););' +
+ 'for (var d in {});' +
+ '(function() {' +
+ ' var i = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [i];' +
+ ' void [b(a), b(c), b(d)];' +
+ ' void [typeof e];' +
+ ' i: for (; 0 === Math.random();) {' +
+ ' if (42 === (new Date()).getMinutes()) {' +
+ ' continue i;' +
+ ' } else {' +
+ ' break i;' +
+ ' }' +
+ ' }' +
+ ' try {' +
+ ' } catch (f) {' +
+ ' } finally {' +
+ ' }' +
+ ' (function g(h) {' +
+ ' }());' +
+ ' void [{' +
+ ' i: 42,' +
+ ' "j": 42,' +
+ ' \'k\': 42' +
+ ' }];' +
+ ' void [i];' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Preservation of identifier names in nested function code.',
+ sInput:
+ '(function() {' +
+ ' void ["abcdefghijklmnopqrstuvwxyz"];' +
+ ' (function() {' +
+ ' var a;' +
+ ' for (var b; 0 === Math.random(););' +
+ ' for (var c in {});' +
+ ' void [typeof d];' +
+ ' h: for (; 0 === Math.random();) {' +
+ ' if (42 === (new Date()).getMinutes()) {' +
+ ' continue h;' +
+ ' } else {' +
+ ' break h;' +
+ ' }' +
+ ' }' +
+ ' try {' +
+ ' } catch (e) {' +
+ ' } finally {' +
+ ' }' +
+ ' (function f(g) {' +
+ ' }());' +
+ ' void [{' +
+ ' h: 42,' +
+ ' "i": 42,' +
+ ' \'j\': 42' +
+ ' }];' +
+ ' }());' +
+ ' void ["abcdefghijklmnopqrstuvwxyz"];' +
+ '}());',
+ sOutput:
+ '(function() {' +
+ ' var h = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [h];' +
+ ' (function() {' +
+ ' var a;' +
+ ' for (var b; 0 === Math.random(););' +
+ ' for (var c in {});' +
+ ' void [typeof d];' +
+ ' h: for (; 0 === Math.random();) {' +
+ ' if (42 === (new Date()).getMinutes()) {' +
+ ' continue h;' +
+ ' } else {' +
+ ' break h;' +
+ ' }' +
+ ' }' +
+ ' try {' +
+ ' } catch (e) {' +
+ ' } finally {' +
+ ' }' +
+ ' (function f(g) {' +
+ ' }());' +
+ ' void [{' +
+ ' h: 42,' +
+ ' "i": 42,' +
+ ' \'j\': 42' +
+ ' }];' +
+ ' }());' +
+ ' void [h];' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Consolidation of a closure with other source elements.',
+ sInput:
+ '(function(foo) {' +
+ '}("abcdefghijklmnopqrstuvwxyz"));' +
+ 'void ["abcdefghijklmnopqrstuvwxyz"];',
+ sOutput:
+ '(function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' (function(foo) {' +
+ ' })(a);' +
+ ' void [a];' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Consolidation of function code instead of a sole closure.',
+ sInput:
+ '(function(foo, bar) {' +
+ ' void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];' +
+ '}("abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz"));',
+ sOutput:
+ '(function(foo, bar) {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a, a];' +
+ '}("abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz"));'
+ },
+ // 11.1.5 Object Initialiser.
+ {
+ sTitle:
+ 'Preservation of property names of an object initialiser.',
+ sInput:
+ 'var foo = {' +
+ ' abcdefghijklmnopqrstuvwxyz: 42,' +
+ ' "zyxwvutsrqponmlkjihgfedcba": 42,' +
+ ' \'mlkjihgfedcbanopqrstuvwxyz\': 42' +
+ '};' +
+ 'void [' +
+ ' foo.abcdefghijklmnopqrstuvwxyz,' +
+ ' "zyxwvutsrqponmlkjihgfedcba",' +
+ ' \'mlkjihgfedcbanopqrstuvwxyz\'' +
+ '];'
+ },
+ {
+ sTitle:
+ 'Evaluation with regard to String values derived from identifier ' +
+ 'names used as property accessors.',
+ sInput:
+ '(function() {' +
+ ' var foo;' +
+ ' void [' +
+ ' Math.abcdefghij,' +
+ ' Math.abcdefghij,' +
+ ' Math.abcdefghi,' +
+ ' Math.abcdefghi' +
+ ' ];' +
+ '}());',
+ sOutput:
+ '(function() {' +
+ ' var a = "abcdefghij", foo;' +
+ ' void [' +
+ ' Math[a],' +
+ ' Math[a],' +
+ ' Math.abcdefghi,' +
+ ' Math.abcdefghi' +
+ ' ];' +
+ '}());'
+ },
+ // 11.2.1 Property Accessors.
+ {
+ sTitle:
+ 'Preservation of identifiers in the nonterminal MemberExpression.',
+ sInput:
+ 'void [' +
+ ' Math.E,' +
+ ' Math.LN10,' +
+ ' Math.LN2,' +
+ ' Math.LOG2E,' +
+ ' Math.LOG10E,' +
+ ' Math.PI,' +
+ ' Math.SQRT1_2,' +
+ ' Math.SQRT2,' +
+ ' Math.abs,' +
+ ' Math.acos' +
+ '];'
+ },
+ // 12.2 Variable Statement.
+ {
+ sTitle:
+ 'Preservation of the identifier of a variable that is being ' +
+ 'declared in a variable statement.',
+ sInput:
+ '(function() {' +
+ ' var abcdefghijklmnopqrstuvwxyz;' +
+ ' void [abcdefghijklmnopqrstuvwxyz];' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Exclusion of a variable statement in global code.',
+ sInput:
+ 'void ["abcdefghijklmnopqrstuvwxyz"];' +
+ 'var foo = "abcdefghijklmnopqrstuvwxyz",' +
+ ' bar = "abcdefghijklmnopqrstuvwxyz";' +
+ 'void ["abcdefghijklmnopqrstuvwxyz"];'
+ },
+ {
+ sTitle:
+ 'Exclusion of a variable statement in function code that ' +
+ 'contains a with statement.',
+ sInput:
+ '(function() {' +
+ ' with ({});' +
+ ' void ["abcdefghijklmnopqrstuvwxyz"];' +
+ ' var foo;' +
+ ' void ["abcdefghijklmnopqrstuvwxyz"];' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Exclusion of a variable statement in function code that ' +
+ 'contains a direct call to the eval function.',
+ sInput:
+ '/*jshint evil:true */' +
+ 'void [' +
+ ' function() {' +
+ ' eval("");' +
+ ' void ["abcdefghijklmnopqrstuvwxyz"];' +
+ ' var foo;' +
+ ' void ["abcdefghijklmnopqrstuvwxyz"];' +
+ ' }' +
+ '];'
+ },
+ {
+ sTitle:
+ 'Consolidation within a variable statement in global code.',
+ sInput:
+ 'var foo = function() {' +
+ ' void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];' +
+ '};',
+ sOutput:
+ 'var foo = function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a, a];' +
+ '};'
+ },
+ {
+ sTitle:
+ 'Consolidation within a variable statement excluded in function ' +
+ 'code due to the presence of a with statement.',
+ sInput:
+ '(function() {' +
+ ' with ({});' +
+ ' var foo = function() {' +
+ ' void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];' +
+ ' };' +
+ '}());',
+ sOutput:
+ '(function() {' +
+ ' with ({});' +
+ ' var foo = function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a, a];' +
+ ' };' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Consolidation within a variable statement excluded in function ' +
+ 'code due to the presence of a direct call to the eval function.',
+ sInput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' eval("");' +
+ ' var foo = function() {' +
+ ' void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];' +
+ ' };' +
+ '}());',
+ sOutput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' eval("");' +
+ ' var foo = function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a, a];' +
+ ' };' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Inclusion of a variable statement in function code that ' +
+ 'contains no with statement and no direct call to the eval ' +
+ 'function.',
+ sInput:
+ '(function() {' +
+ ' void ["abcdefghijklmnopqrstuvwxyz"];' +
+ ' var foo;' +
+ ' void ["abcdefghijklmnopqrstuvwxyz"];' +
+ '}());',
+ sOutput:
+ '(function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a];' +
+ ' var foo;' +
+ ' void [a];' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Ignorance with regard to a variable statement in global code.',
+ sInput:
+ 'var foo = "abcdefghijklmnopqrstuvwxyz";' +
+ 'void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];',
+ sOutput:
+ 'var foo = "abcdefghijklmnopqrstuvwxyz";' +
+ '(function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a, a];' +
+ '}());'
+ },
+ // 12.4 Expression Statement.
+ {
+ sTitle:
+ 'Preservation of identifiers in an expression statement.',
+ sInput:
+ 'void [typeof abcdefghijklmnopqrstuvwxyz,' +
+ ' typeof abcdefghijklmnopqrstuvwxyz];'
+ },
+ // 12.6.3 The {@code for} Statement.
+ {
+ sTitle:
+ 'Preservation of identifiers in the variable declaration list of ' +
+ 'a for statement.',
+ sInput:
+ 'for (var abcdefghijklmnopqrstuvwxyz; 0 === Math.random(););' +
+ 'for (var abcdefghijklmnopqrstuvwxyz; 0 === Math.random(););'
+ },
+ // 12.6.4 The {@code for-in} Statement.
+ {
+ sTitle:
+ 'Preservation of identifiers in the variable declaration list of ' +
+ 'a for-in statement.',
+ sInput:
+ 'for (var abcdefghijklmnopqrstuvwxyz in {});' +
+ 'for (var abcdefghijklmnopqrstuvwxyz in {});'
+ },
+ // 12.7 The {@code continue} Statement.
+ {
+ sTitle:
+ 'Preservation of the identifier in a continue statement.',
+ sInput:
+ 'abcdefghijklmnopqrstuvwxyz: for (; 0 === Math.random();) {' +
+ ' continue abcdefghijklmnopqrstuvwxyz;' +
+ '}' +
+ 'abcdefghijklmnopqrstuvwxyz: for (; 0 === Math.random();) {' +
+ ' continue abcdefghijklmnopqrstuvwxyz;' +
+ '}'
+ },
+ // 12.8 The {@code break} Statement.
+ {
+ sTitle:
+ 'Preservation of the identifier in a break statement.',
+ sInput:
+ 'abcdefghijklmnopqrstuvwxyz: for (; 0 === Math.random();) {' +
+ ' break abcdefghijklmnopqrstuvwxyz;' +
+ '}' +
+ 'abcdefghijklmnopqrstuvwxyz: for (; 0 === Math.random();) {' +
+ ' break abcdefghijklmnopqrstuvwxyz;' +
+ '}'
+ },
+ // 12.9 The {@code return} Statement.
+ {
+ sTitle:
+ 'Exclusion of a return statement in function code that contains ' +
+ 'a with statement.',
+ sInput:
+ '(function() {' +
+ ' with ({});' +
+ ' void ["abcdefghijklmnopqrstuvwxyz"];' +
+ ' if (0 === Math.random()) {' +
+ ' return;' +
+ ' } else {' +
+ ' }' +
+ ' void ["abcdefghijklmnopqrstuvwxyz"];' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Exclusion of a return statement in function code that contains ' +
+ 'a direct call to the eval function.',
+ sInput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' eval("");' +
+ ' void ["abcdefghijklmnopqrstuvwxyz"];' +
+ ' if (0 === Math.random()) {' +
+ ' return;' +
+ ' } else {' +
+ ' }' +
+ ' void ["abcdefghijklmnopqrstuvwxyz"];' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Consolidation within a return statement excluded in function ' +
+ 'code due to the presence of a with statement.',
+ sInput:
+ '(function() {' +
+ ' with ({});' +
+ ' return function() {' +
+ ' void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];' +
+ ' };' +
+ '}());',
+ sOutput:
+ '(function() {' +
+ ' with ({});' +
+ ' return function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a, a];' +
+ ' };' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Consolidation within a return statement excluded in function ' +
+ 'code due to the presence of a direct call to the eval function.',
+ sInput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' eval("");' +
+ ' return function() {' +
+ ' void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];' +
+ ' };' +
+ '}());',
+ sOutput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' eval("");' +
+ ' return function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a, a];' +
+ ' };' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Inclusion of a return statement in function code that contains ' +
+ 'no with statement and no direct call to the eval function.',
+ sInput:
+ '(function() {' +
+ ' void ["abcdefghijklmnopqrstuvwxyz"];' +
+ ' if (0 === Math.random()) {' +
+ ' return;' +
+ ' } else {' +
+ ' }' +
+ ' void ["abcdefghijklmnopqrstuvwxyz"];' +
+ '}());',
+ sOutput:
+ '(function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a];' +
+ ' if (0 === Math.random()) {' +
+ ' return;' +
+ ' } else {' +
+ ' }' +
+ ' void [a];' +
+ '}());'
+ },
+ // 12.10 The {@code with} Statement.
+ {
+ sTitle:
+ 'Preservation of the statement in a with statement.',
+ sInput:
+ 'with ({}) {' +
+ ' void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];' +
+ '}'
+ },
+ {
+ sTitle:
+ 'Exclusion of a with statement in the same syntactic code unit.',
+ sInput:
+ 'void ["abcdefghijklmnopqrstuvwxyz"];' +
+ 'with ({' +
+ ' foo: "abcdefghijklmnopqrstuvwxyz",' +
+ ' bar: "abcdefghijklmnopqrstuvwxyz"' +
+ '}) {' +
+ ' void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];' +
+ '}' +
+ 'void ["abcdefghijklmnopqrstuvwxyz"];'
+ },
+ {
+ sTitle:
+ 'Exclusion of a with statement in nested function code.',
+ sInput:
+ 'void ["abcdefghijklmnopqrstuvwxyz"];' +
+ '(function() {' +
+ ' with ({' +
+ ' foo: "abcdefghijklmnopqrstuvwxyz",' +
+ ' bar: "abcdefghijklmnopqrstuvwxyz"' +
+ ' }) {' +
+ ' void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];' +
+ ' }' +
+ '}());' +
+ 'void ["abcdefghijklmnopqrstuvwxyz"];'
+ },
+ // 12.12 Labelled Statements.
+ {
+ sTitle:
+ 'Preservation of the label of a labelled statement.',
+ sInput:
+ 'abcdefghijklmnopqrstuvwxyz: for (; 0 === Math.random(););' +
+ 'abcdefghijklmnopqrstuvwxyz: for (; 0 === Math.random(););'
+ },
+ // 12.14 The {@code try} Statement.
+ {
+ sTitle:
+ 'Preservation of the identifier in the catch clause of a try' +
+ 'statement.',
+ sInput:
+ 'try {' +
+ '} catch (abcdefghijklmnopqrstuvwxyz) {' +
+ '} finally {' +
+ '}' +
+ 'try {' +
+ '} catch (abcdefghijklmnopqrstuvwxyz) {' +
+ '} finally {' +
+ '}'
+ },
+ // 13 Function Definition.
+ {
+ sTitle:
+ 'Preservation of the identifier of a function declaration.',
+ sInput:
+ 'function abcdefghijklmnopqrstuvwxyz() {' +
+ '}' +
+ 'void [abcdefghijklmnopqrstuvwxyz];'
+ },
+ {
+ sTitle:
+ 'Preservation of the identifier of a function expression.',
+ sInput:
+ 'void [' +
+ ' function abcdefghijklmnopqrstuvwxyz() {' +
+ ' },' +
+ ' function abcdefghijklmnopqrstuvwxyz() {' +
+ ' }' +
+ '];'
+ },
+ {
+ sTitle:
+ 'Preservation of a formal parameter of a function declaration.',
+ sInput:
+ 'function foo(abcdefghijklmnopqrstuvwxyz) {' +
+ '}' +
+ 'function bar(abcdefghijklmnopqrstuvwxyz) {' +
+ '}'
+ },
+ {
+ sTitle:
+ 'Preservation of a formal parameter in a function expression.',
+ sInput:
+ 'void [' +
+ ' function(abcdefghijklmnopqrstuvwxyz) {' +
+ ' },' +
+ ' function(abcdefghijklmnopqrstuvwxyz) {' +
+ ' }' +
+ '];'
+ },
+ {
+ sTitle:
+ 'Exclusion of a function declaration.',
+ sInput:
+ 'void ["abcdefghijklmnopqrstuvwxyz"];' +
+ 'function foo() {' +
+ '}' +
+ 'void ["abcdefghijklmnopqrstuvwxyz"];'
+ },
+ {
+ sTitle:
+ 'Consolidation within a function declaration.',
+ sInput:
+ 'function foo() {' +
+ ' void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];' +
+ '}',
+ sOutput:
+ 'function foo() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a, a];' +
+ '}'
+ },
+ // 14 Program.
+ {
+ sTitle:
+ 'Preservation of a program without source elements.',
+ sInput:
+ ''
+ },
+ // 14.1 Directive Prologues and the Use Strict Directive.
+ {
+ sTitle:
+ 'Preservation of a Directive Prologue in global code.',
+ sInput:
+ '"abcdefghijklmnopqrstuvwxyz";' +
+ '\'zyxwvutsrqponmlkjihgfedcba\';'
+ },
+ {
+ sTitle:
+ 'Preservation of a Directive Prologue in a function declaration.',
+ sInput:
+ 'function foo() {' +
+ ' "abcdefghijklmnopqrstuvwxyz";' +
+ ' \'zyxwvutsrqponmlkjihgfedcba\';' +
+ '}'
+ },
+ {
+ sTitle:
+ 'Preservation of a Directive Prologue in a function expression.',
+ sInput:
+ 'void [' +
+ ' function() {' +
+ ' "abcdefghijklmnopqrstuvwxyz";' +
+ ' \'zyxwvutsrqponmlkjihgfedcba\';' +
+ ' }' +
+ '];'
+ },
+ {
+ sTitle:
+ 'Ignorance with regard to a Directive Prologue in global code.',
+ sInput:
+ '"abcdefghijklmnopqrstuvwxyz";' +
+ 'void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];',
+ sOutput:
+ '"abcdefghijklmnopqrstuvwxyz";' +
+ '(function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a, a];' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Ignorance with regard to a Directive Prologue in a function' +
+ 'declaration.',
+ sInput:
+ 'function foo() {' +
+ ' "abcdefghijklmnopqrstuvwxyz";' +
+ ' void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];' +
+ '}',
+ sOutput:
+ 'function foo() {' +
+ ' "abcdefghijklmnopqrstuvwxyz";' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a, a];' +
+ '}'
+ },
+ {
+ sTitle:
+ 'Ignorance with regard to a Directive Prologue in a function' +
+ 'expression.',
+ sInput:
+ '(function() {' +
+ ' "abcdefghijklmnopqrstuvwxyz";' +
+ ' void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];' +
+ '}());',
+ sOutput:
+ '(function() {' +
+ ' "abcdefghijklmnopqrstuvwxyz";' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a, a];' +
+ '}());'
+ },
+ // 15.1 The Global Object.
+ {
+ sTitle:
+ 'Preservation of a property of the global object.',
+ sInput:
+ 'void [undefined, undefined, undefined, undefined, undefined];'
+ },
+ // 15.1.2.1.1 Direct Call to Eval.
+ {
+ sTitle:
+ 'Exclusion of a direct call to the eval function in the same ' +
+ 'syntactic code unit.',
+ sInput:
+ '/*jshint evil:true */' +
+ 'void ["abcdefghijklmnopqrstuvwxyz"];' +
+ 'eval("");' +
+ 'void ["abcdefghijklmnopqrstuvwxyz"];'
+ },
+ {
+ sTitle:
+ 'Exclusion of a direct call to the eval function in nested ' +
+ 'function code.',
+ sInput:
+ '/*jshint evil:true */' +
+ 'void ["abcdefghijklmnopqrstuvwxyz"];' +
+ '(function() {' +
+ ' eval("");' +
+ '}());' +
+ 'void ["abcdefghijklmnopqrstuvwxyz"];'
+ },
+ {
+ sTitle:
+ 'Consolidation within a direct call to the eval function.',
+ sInput:
+ '/*jshint evil:true */' +
+ 'eval(function() {' +
+ ' void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];' +
+ '}());',
+ sOutput:
+ '/*jshint evil:true */' +
+ 'eval(function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a, a];' +
+ '}());'
+ },
+ // Consolidation proper.
+ {
+ sTitle:
+ 'No consolidation if it does not result in a reduction of the ' +
+ 'number of source characters.',
+ sInput:
+ '(function() {' +
+ ' var foo;' +
+ ' void ["ab", "ab", "abc", "abc"];' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Identification of a range of source elements at the beginning ' +
+ 'of global code.',
+ sInput:
+ '/*jshint evil:true */' +
+ '"abcdefghijklmnopqrstuvwxyz";' +
+ 'void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];' +
+ 'eval("");',
+ sOutput:
+ '/*jshint evil:true */' +
+ '"abcdefghijklmnopqrstuvwxyz";' +
+ '(function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a, a];' +
+ '}());' +
+ 'eval("");'
+ },
+ {
+ sTitle:
+ 'Identification of a range of source elements in the middle of ' +
+ 'global code.',
+ sInput:
+ '/*jshint evil:true */' +
+ '"abcdefghijklmnopqrstuvwxyz";' +
+ 'eval("");' +
+ 'void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];' +
+ 'eval("");',
+ sOutput:
+ '/*jshint evil:true */' +
+ '"abcdefghijklmnopqrstuvwxyz";' +
+ 'eval("");' +
+ '(function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a, a];' +
+ '}());' +
+ 'eval("");'
+ },
+ {
+ sTitle:
+ 'Identification of a range of source elements at the end of ' +
+ 'global code.',
+ sInput:
+ '/*jshint evil:true */' +
+ '"abcdefghijklmnopqrstuvwxyz";' +
+ 'eval("");' +
+ 'void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];',
+ sOutput:
+ '/*jshint evil:true */' +
+ '"abcdefghijklmnopqrstuvwxyz";' +
+ 'eval("");' +
+ '(function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a, a];' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Identification of a range of source elements at the beginning ' +
+ 'of function code.',
+ sInput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' "abcdefghijklmnopqrstuvwxyz";' +
+ ' void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];' +
+ ' eval("");' +
+ '}());',
+ sOutput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' "abcdefghijklmnopqrstuvwxyz";' +
+ ' (function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a, a];' +
+ ' }());' +
+ ' eval("");' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Identification of a range of source elements in the middle of ' +
+ 'function code.',
+ sInput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' "abcdefghijklmnopqrstuvwxyz";' +
+ ' eval("");' +
+ ' void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];' +
+ ' eval("");' +
+ '}());',
+ sOutput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' "abcdefghijklmnopqrstuvwxyz";' +
+ ' eval("");' +
+ ' (function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a, a];' +
+ ' }());' +
+ ' eval("");' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Identification of a range of source elements at the end of ' +
+ 'function code.',
+ sInput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' "abcdefghijklmnopqrstuvwxyz";' +
+ ' eval("");' +
+ ' void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];' +
+ '}());',
+ sOutput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' "abcdefghijklmnopqrstuvwxyz";' +
+ ' eval("");' +
+ ' (function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a, a];' +
+ ' }());' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Evaluation with regard to String values of String literals and ' +
+ 'String values derived from identifier names used as property' +
+ 'accessors.',
+ sInput:
+ '(function() {' +
+ ' var foo;' +
+ ' void ["abcdefg", Math.abcdefg, "abcdef", Math.abcdef];' +
+ '}());',
+ sOutput:
+ '(function() {' +
+ ' var a = "abcdefg", foo;' +
+ ' void [a, Math[a], "abcdef", Math.abcdef];' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Evaluation with regard to the necessity of adding a variable ' +
+ 'statement.',
+ sInput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' void ["abcdefgh", "abcdefgh"];' +
+ '}());' +
+ 'eval("");' +
+ '(function() {' +
+ ' void ["abcdefg", "abcdefg"];' +
+ '}());' +
+ 'eval("");' +
+ '(function() {' +
+ ' var foo;' +
+ ' void ["abcd", "abcd"];' +
+ '}());',
+ sOutput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' var a = "abcdefgh";' +
+ ' void [a, a];' +
+ '}());' +
+ 'eval("");' +
+ '(function() {' +
+ ' void ["abcdefg", "abcdefg"];' +
+ '}());' +
+ 'eval("");' +
+ '(function() {' +
+ ' var a = "abcd", foo;' +
+ ' void [a, a];' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Evaluation with regard to the necessity of enclosing source ' +
+ 'elements.',
+ sInput:
+ '/*jshint evil:true */' +
+ 'void ["abcdefghijklmnopqrstuvwxy", "abcdefghijklmnopqrstuvwxy"];' +
+ 'eval("");' +
+ 'void ["abcdefghijklmnopqrstuvwx", "abcdefghijklmnopqrstuvwx"];' +
+ 'eval("");' +
+ '(function() {' +
+ ' void ["abcdefgh", "abcdefgh"];' +
+ '}());' +
+ '(function() {' +
+ ' void ["abcdefghijklmnopqrstuvwxy",' +
+ ' "abcdefghijklmnopqrstuvwxy"];' +
+ ' eval("");' +
+ ' void ["abcdefghijklmnopqrstuvwx",' +
+ ' "abcdefghijklmnopqrstuvwx"];' +
+ ' eval("");' +
+ ' (function() {' +
+ ' void ["abcdefgh", "abcdefgh"];' +
+ ' }());' +
+ '}());',
+ sOutput:
+ '/*jshint evil:true */' +
+ '(function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxy";' +
+ ' void [a, a];' +
+ '}());' +
+ 'eval("");' +
+ 'void ["abcdefghijklmnopqrstuvwx", "abcdefghijklmnopqrstuvwx"];' +
+ 'eval("");' +
+ '(function() {' +
+ ' var a = "abcdefgh";' +
+ ' void [a, a];' +
+ '}());' +
+ '(function() {' +
+ ' (function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxy";' +
+ ' void [a, a];' +
+ ' }());' +
+ ' eval("");' +
+ ' void ["abcdefghijklmnopqrstuvwx", "abcdefghijklmnopqrstuvwx"];' +
+ ' eval("");' +
+ ' (function() {' +
+ ' var a = "abcdefgh";' +
+ ' void [a, a];' +
+ ' }());' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Employment of a closure while consolidating in global code.',
+ sInput:
+ 'void ["abcdefghijklmnopqrstuvwxyz",' +
+ ' "abcdefghijklmnopqrstuvwxyz"];',
+ sOutput:
+ '(function() {' +
+ ' var a = "abcdefghijklmnopqrstuvwxyz";' +
+ ' void [a, a];' +
+ '}());'
+ },
+ {
+ sTitle:
+ 'Assignment of a shorter identifier to a value whose ' +
+ 'consolidation results in a greater reduction of the number of ' +
+ 'source characters.',
+ sInput:
+ '(function() {' +
+ ' var b, c, d, e, f, g, h, i, j, k, l, m,' +
+ ' n, o, p, q, r, s, t, u, v, w, x, y, z,' +
+ ' A, B, C, D, E, F, G, H, I, J, K, L, M,' +
+ ' N, O, P, Q, R, S, T, U, V, W, X, Y, Z,' +
+ ' $, _;' +
+ ' void ["abcde", "abcde", "edcba", "edcba", "edcba"];' +
+ '}());',
+ sOutput:
+ '(function() {' +
+ ' var a = "edcba",' +
+ ' b, c, d, e, f, g, h, i, j, k, l, m,' +
+ ' n, o, p, q, r, s, t, u, v, w, x, y, z,' +
+ ' A, B, C, D, E, F, G, H, I, J, K, L, M,' +
+ ' N, O, P, Q, R, S, T, U, V, W, X, Y, Z,' +
+ ' $, _;' +
+ ' void ["abcde", "abcde", a, a, a];' +
+ '}());'
+ }
+ ].forEach(cAssert);
+ }());
+}
+
+/* Local Variables: */
+/* mode: js */
+/* coding: utf-8 */
+/* indent-tabs-mode: nil */
+/* tab-width: 2 */
+/* End: */
+/* vim: set ft=javascript fenc=utf-8 et ts=2 sts=2 sw=2: */
+/* :mode=javascript:noTabs=true:tabSize=2:indentSize=2:deepIndent=true: */
+
diff --git a/node_modules/handlebars/node_modules/uglify-js/lib/object-ast.js b/node_modules/handlebars/node_modules/uglify-js/lib/object-ast.js
new file mode 100644
index 0000000000..afdb69fbd0
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/lib/object-ast.js
@@ -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"]);
diff --git a/node_modules/handlebars/node_modules/uglify-js/lib/parse-js.js b/node_modules/handlebars/node_modules/uglify-js/lib/parse-js.js
new file mode 100644
index 0000000000..dccd623808
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/lib/parse-js.js
@@ -0,0 +1,1346 @@
+/***********************************************************************
+
+ A JavaScript tokenizer / parser / beautifier / compressor.
+
+ This version is suitable for Node.js. With minimal changes (the
+ exports stuff) it should work on any JS platform.
+
+ This file contains the tokenizer/parser. It is a port to JavaScript
+ of parse-js [1], a JavaScript parser library written in Common Lisp
+ by Marijn Haverbeke. Thank you Marijn!
+
+ [1] http://marijn.haverbeke.nl/parse-js/
+
+ Exported functions:
+
+ - tokenizer(code) -- returns a function. Call the returned
+ function to fetch the next token.
+
+ - parse(code) -- returns an AST of the given JavaScript code.
+
+ -------------------------------- (C) ---------------------------------
+
+ Author: Mihai Bazon
+
+ http://mihai.bazon.net/blog
+
+ Distributed under the BSD license:
+
+ Copyright 2010 (c) Mihai Bazon
+ 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.
+
+ ***********************************************************************/
+
+/* -----[ Tokenizer (constants) ]----- */
+
+var KEYWORDS = array_to_hash([
+ "break",
+ "case",
+ "catch",
+ "const",
+ "continue",
+ "debugger",
+ "default",
+ "delete",
+ "do",
+ "else",
+ "finally",
+ "for",
+ "function",
+ "if",
+ "in",
+ "instanceof",
+ "new",
+ "return",
+ "switch",
+ "throw",
+ "try",
+ "typeof",
+ "var",
+ "void",
+ "while",
+ "with"
+]);
+
+var RESERVED_WORDS = array_to_hash([
+ "abstract",
+ "boolean",
+ "byte",
+ "char",
+ "class",
+ "double",
+ "enum",
+ "export",
+ "extends",
+ "final",
+ "float",
+ "goto",
+ "implements",
+ "import",
+ "int",
+ "interface",
+ "long",
+ "native",
+ "package",
+ "private",
+ "protected",
+ "public",
+ "short",
+ "static",
+ "super",
+ "synchronized",
+ "throws",
+ "transient",
+ "volatile"
+]);
+
+var KEYWORDS_BEFORE_EXPRESSION = array_to_hash([
+ "return",
+ "new",
+ "delete",
+ "throw",
+ "else",
+ "case"
+]);
+
+var KEYWORDS_ATOM = array_to_hash([
+ "false",
+ "null",
+ "true",
+ "undefined"
+]);
+
+var OPERATOR_CHARS = array_to_hash(characters("+-*&%=<>!?|~^"));
+
+var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;
+var RE_OCT_NUMBER = /^0[0-7]+$/;
+var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;
+
+var OPERATORS = array_to_hash([
+ "in",
+ "instanceof",
+ "typeof",
+ "new",
+ "void",
+ "delete",
+ "++",
+ "--",
+ "+",
+ "-",
+ "!",
+ "~",
+ "&",
+ "|",
+ "^",
+ "*",
+ "/",
+ "%",
+ ">>",
+ "<<",
+ ">>>",
+ "<",
+ ">",
+ "<=",
+ ">=",
+ "==",
+ "===",
+ "!=",
+ "!==",
+ "?",
+ "=",
+ "+=",
+ "-=",
+ "/=",
+ "*=",
+ "%=",
+ ">>=",
+ "<<=",
+ ">>>=",
+ "|=",
+ "^=",
+ "&=",
+ "&&",
+ "||"
+]);
+
+var WHITESPACE_CHARS = array_to_hash(characters(" \u00a0\n\r\t\f\u000b\u200b\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000"));
+
+var PUNC_BEFORE_EXPRESSION = array_to_hash(characters("[{(,.;:"));
+
+var PUNC_CHARS = array_to_hash(characters("[]{}(),;:"));
+
+var REGEXP_MODIFIERS = array_to_hash(characters("gmsiy"));
+
+/* -----[ Tokenizer ]----- */
+
+// regexps adapted from http://xregexp.com/plugins/#unicode
+var UNICODE = {
+ letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0523\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0621-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971\\u0972\\u097B-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D28\\u0D2A-\\u0D39\\u0D3D\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC\\u0EDD\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8B\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10D0-\\u10FA\\u10FC\\u1100-\\u1159\\u115F-\\u11A2\\u11A8-\\u11F9\\u1200-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u1676\\u1681-\\u169A\\u16A0-\\u16EA\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19A9\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u2094\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2C6F\\u2C71-\\u2C7D\\u2C80-\\u2CE4\\u2D00-\\u2D25\\u2D30-\\u2D65\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31B7\\u31F0-\\u31FF\\u3400\\u4DB5\\u4E00\\u9FC3\\uA000-\\uA48C\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA65F\\uA662-\\uA66E\\uA67F-\\uA697\\uA717-\\uA71F\\uA722-\\uA788\\uA78B\\uA78C\\uA7FB-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA90A-\\uA925\\uA930-\\uA946\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAC00\\uD7A3\\uF900-\\uFA2D\\uFA30-\\uFA6A\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"),
+ non_spacing_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065E\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0900-\\u0902\\u093C\\u0941-\\u0948\\u094D\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09BC\\u09C1-\\u09C4\\u09CD\\u09E2\\u09E3\\u0A01\\u0A02\\u0A3C\\u0A41\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81\\u0A82\\u0ABC\\u0AC1-\\u0AC5\\u0AC7\\u0AC8\\u0ACD\\u0AE2\\u0AE3\\u0B01\\u0B3C\\u0B3F\\u0B41-\\u0B44\\u0B4D\\u0B56\\u0B62\\u0B63\\u0B82\\u0BC0\\u0BCD\\u0C3E-\\u0C40\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0CBC\\u0CBF\\u0CC6\\u0CCC\\u0CCD\\u0CE2\\u0CE3\\u0D41-\\u0D44\\u0D4D\\u0D62\\u0D63\\u0DCA\\u0DD2-\\u0DD4\\u0DD6\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F71-\\u0F7E\\u0F80-\\u0F84\\u0F86\\u0F87\\u0F90-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102D-\\u1030\\u1032-\\u1037\\u1039\\u103A\\u103D\\u103E\\u1058\\u1059\\u105E-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108D\\u109D\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B7-\\u17BD\\u17C6\\u17C9-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193B\\u1A17\\u1A18\\u1A56\\u1A58-\\u1A5E\\u1A60\\u1A62\\u1A65-\\u1A6C\\u1A73-\\u1A7C\\u1A7F\\u1B00-\\u1B03\\u1B34\\u1B36-\\u1B3A\\u1B3C\\u1B42\\u1B6B-\\u1B73\\u1B80\\u1B81\\u1BA2-\\u1BA5\\u1BA8\\u1BA9\\u1C2C-\\u1C33\\u1C36\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE0\\u1CE2-\\u1CE8\\u1CED\\u1DC0-\\u1DE6\\u1DFD-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA67C\\uA67D\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA825\\uA826\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA951\\uA980-\\uA982\\uA9B3\\uA9B6-\\uA9B9\\uA9BC\\uAA29-\\uAA2E\\uAA31\\uAA32\\uAA35\\uAA36\\uAA43\\uAA4C\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uABE5\\uABE8\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"),
+ space_combining_mark: new RegExp("[\\u0903\\u093E-\\u0940\\u0949-\\u094C\\u094E\\u0982\\u0983\\u09BE-\\u09C0\\u09C7\\u09C8\\u09CB\\u09CC\\u09D7\\u0A03\\u0A3E-\\u0A40\\u0A83\\u0ABE-\\u0AC0\\u0AC9\\u0ACB\\u0ACC\\u0B02\\u0B03\\u0B3E\\u0B40\\u0B47\\u0B48\\u0B4B\\u0B4C\\u0B57\\u0BBE\\u0BBF\\u0BC1\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCC\\u0BD7\\u0C01-\\u0C03\\u0C41-\\u0C44\\u0C82\\u0C83\\u0CBE\\u0CC0-\\u0CC4\\u0CC7\\u0CC8\\u0CCA\\u0CCB\\u0CD5\\u0CD6\\u0D02\\u0D03\\u0D3E-\\u0D40\\u0D46-\\u0D48\\u0D4A-\\u0D4C\\u0D57\\u0D82\\u0D83\\u0DCF-\\u0DD1\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0F3E\\u0F3F\\u0F7F\\u102B\\u102C\\u1031\\u1038\\u103B\\u103C\\u1056\\u1057\\u1062-\\u1064\\u1067-\\u106D\\u1083\\u1084\\u1087-\\u108C\\u108F\\u109A-\\u109C\\u17B6\\u17BE-\\u17C5\\u17C7\\u17C8\\u1923-\\u1926\\u1929-\\u192B\\u1930\\u1931\\u1933-\\u1938\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A19-\\u1A1B\\u1A55\\u1A57\\u1A61\\u1A63\\u1A64\\u1A6D-\\u1A72\\u1B04\\u1B35\\u1B3B\\u1B3D-\\u1B41\\u1B43\\u1B44\\u1B82\\u1BA1\\u1BA6\\u1BA7\\u1BAA\\u1C24-\\u1C2B\\u1C34\\u1C35\\u1CE1\\u1CF2\\uA823\\uA824\\uA827\\uA880\\uA881\\uA8B4-\\uA8C3\\uA952\\uA953\\uA983\\uA9B4\\uA9B5\\uA9BA\\uA9BB\\uA9BD-\\uA9C0\\uAA2F\\uAA30\\uAA33\\uAA34\\uAA4D\\uAA7B\\uABE3\\uABE4\\uABE6\\uABE7\\uABE9\\uABEA\\uABEC]"),
+ connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]")
+};
+
+function is_letter(ch) {
+ return UNICODE.letter.test(ch);
+};
+
+function is_digit(ch) {
+ ch = ch.charCodeAt(0);
+ return ch >= 48 && ch <= 57; //XXX: find out if "UnicodeDigit" means something else than 0..9
+};
+
+function is_alphanumeric_char(ch) {
+ return is_digit(ch) || is_letter(ch);
+};
+
+function is_unicode_combining_mark(ch) {
+ return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch);
+};
+
+function is_unicode_connector_punctuation(ch) {
+ return UNICODE.connector_punctuation.test(ch);
+};
+
+function is_identifier_start(ch) {
+ return ch == "$" || ch == "_" || is_letter(ch);
+};
+
+function is_identifier_char(ch) {
+ return is_identifier_start(ch)
+ || is_unicode_combining_mark(ch)
+ || is_digit(ch)
+ || is_unicode_connector_punctuation(ch)
+ || ch == "\u200c" // zero-width non-joiner
+ || ch == "\u200d" // zero-width joiner (in my ECMA-262 PDF, this is also 200c)
+ ;
+};
+
+function parse_js_number(num) {
+ if (RE_HEX_NUMBER.test(num)) {
+ return parseInt(num.substr(2), 16);
+ } else if (RE_OCT_NUMBER.test(num)) {
+ return parseInt(num.substr(1), 8);
+ } else if (RE_DEC_NUMBER.test(num)) {
+ return parseFloat(num);
+ }
+};
+
+function JS_Parse_Error(message, line, col, pos) {
+ this.message = message;
+ this.line = line + 1;
+ this.col = col + 1;
+ this.pos = pos + 1;
+ this.stack = new Error().stack;
+};
+
+JS_Parse_Error.prototype.toString = function() {
+ return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack;
+};
+
+function js_error(message, line, col, pos) {
+ throw new JS_Parse_Error(message, line, col, pos);
+};
+
+function is_token(token, type, val) {
+ return token.type == type && (val == null || token.value == val);
+};
+
+var EX_EOF = {};
+
+function tokenizer($TEXT) {
+
+ var S = {
+ text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, ''),
+ pos : 0,
+ tokpos : 0,
+ line : 0,
+ tokline : 0,
+ col : 0,
+ tokcol : 0,
+ newline_before : false,
+ regex_allowed : false,
+ comments_before : []
+ };
+
+ function peek() { return S.text.charAt(S.pos); };
+
+ function next(signal_eof, in_string) {
+ var ch = S.text.charAt(S.pos++);
+ if (signal_eof && !ch)
+ throw EX_EOF;
+ if (ch == "\n") {
+ S.newline_before = S.newline_before || !in_string;
+ ++S.line;
+ S.col = 0;
+ } else {
+ ++S.col;
+ }
+ return ch;
+ };
+
+ function eof() {
+ return !S.peek();
+ };
+
+ function find(what, signal_eof) {
+ var pos = S.text.indexOf(what, S.pos);
+ if (signal_eof && pos == -1) throw EX_EOF;
+ return pos;
+ };
+
+ function start_token() {
+ S.tokline = S.line;
+ S.tokcol = S.col;
+ S.tokpos = S.pos;
+ };
+
+ function token(type, value, is_comment) {
+ S.regex_allowed = ((type == "operator" && !HOP(UNARY_POSTFIX, value)) ||
+ (type == "keyword" && HOP(KEYWORDS_BEFORE_EXPRESSION, value)) ||
+ (type == "punc" && HOP(PUNC_BEFORE_EXPRESSION, value)));
+ var ret = {
+ type : type,
+ value : value,
+ line : S.tokline,
+ col : S.tokcol,
+ pos : S.tokpos,
+ endpos : S.pos,
+ nlb : S.newline_before
+ };
+ if (!is_comment) {
+ ret.comments_before = S.comments_before;
+ S.comments_before = [];
+ }
+ S.newline_before = false;
+ return ret;
+ };
+
+ function skip_whitespace() {
+ while (HOP(WHITESPACE_CHARS, peek()))
+ next();
+ };
+
+ function read_while(pred) {
+ var ret = "", ch = peek(), i = 0;
+ while (ch && pred(ch, i++)) {
+ ret += next();
+ ch = peek();
+ }
+ return ret;
+ };
+
+ function parse_error(err) {
+ js_error(err, S.tokline, S.tokcol, S.tokpos);
+ };
+
+ function read_num(prefix) {
+ var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".";
+ var num = read_while(function(ch, i){
+ if (ch == "x" || ch == "X") {
+ if (has_x) return false;
+ return has_x = true;
+ }
+ if (!has_x && (ch == "E" || ch == "e")) {
+ if (has_e) return false;
+ return has_e = after_e = true;
+ }
+ if (ch == "-") {
+ if (after_e || (i == 0 && !prefix)) return true;
+ return false;
+ }
+ if (ch == "+") return after_e;
+ after_e = false;
+ if (ch == ".") {
+ if (!has_dot && !has_x)
+ return has_dot = true;
+ return false;
+ }
+ return is_alphanumeric_char(ch);
+ });
+ if (prefix)
+ num = prefix + num;
+ var valid = parse_js_number(num);
+ if (!isNaN(valid)) {
+ return token("num", valid);
+ } else {
+ parse_error("Invalid syntax: " + num);
+ }
+ };
+
+ function read_escaped_char(in_string) {
+ var ch = next(true, in_string);
+ switch (ch) {
+ case "n" : return "\n";
+ case "r" : return "\r";
+ case "t" : return "\t";
+ case "b" : return "\b";
+ case "v" : return "\u000b";
+ case "f" : return "\f";
+ case "0" : return "\0";
+ case "x" : return String.fromCharCode(hex_bytes(2));
+ case "u" : return String.fromCharCode(hex_bytes(4));
+ case "\n": return "";
+ default : return ch;
+ }
+ };
+
+ function hex_bytes(n) {
+ var num = 0;
+ for (; n > 0; --n) {
+ var digit = parseInt(next(true), 16);
+ if (isNaN(digit))
+ parse_error("Invalid hex-character pattern in string");
+ num = (num << 4) | digit;
+ }
+ return num;
+ };
+
+ function read_string() {
+ return with_eof_error("Unterminated string constant", function(){
+ var quote = next(), ret = "";
+ for (;;) {
+ var ch = next(true);
+ if (ch == "\\") {
+ // read OctalEscapeSequence (XXX: deprecated if "strict mode")
+ // https://github.com/mishoo/UglifyJS/issues/178
+ var octal_len = 0, first = null;
+ ch = read_while(function(ch){
+ if (ch >= "0" && ch <= "7") {
+ if (!first) {
+ first = ch;
+ return ++octal_len;
+ }
+ else if (first <= "3" && octal_len <= 2) return ++octal_len;
+ else if (first >= "4" && octal_len <= 1) return ++octal_len;
+ }
+ return false;
+ });
+ if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8));
+ else ch = read_escaped_char(true);
+ }
+ else if (ch == quote) break;
+ ret += ch;
+ }
+ return token("string", ret);
+ });
+ };
+
+ function read_line_comment() {
+ next();
+ var i = find("\n"), ret;
+ if (i == -1) {
+ ret = S.text.substr(S.pos);
+ S.pos = S.text.length;
+ } else {
+ ret = S.text.substring(S.pos, i);
+ S.pos = i;
+ }
+ return token("comment1", ret, true);
+ };
+
+ function read_multiline_comment() {
+ next();
+ return with_eof_error("Unterminated multiline comment", function(){
+ var i = find("*/", true),
+ text = S.text.substring(S.pos, i);
+ S.pos = i + 2;
+ S.line += text.split("\n").length - 1;
+ S.newline_before = text.indexOf("\n") >= 0;
+
+ // https://github.com/mishoo/UglifyJS/issues/#issue/100
+ if (/^@cc_on/i.test(text)) {
+ warn("WARNING: at line " + S.line);
+ warn("*** Found \"conditional comment\": " + text);
+ warn("*** UglifyJS DISCARDS ALL COMMENTS. This means your code might no longer work properly in Internet Explorer.");
+ }
+
+ return token("comment2", text, true);
+ });
+ };
+
+ function read_name() {
+ var backslash = false, name = "", ch, escaped = false, hex;
+ while ((ch = peek()) != null) {
+ if (!backslash) {
+ if (ch == "\\") escaped = backslash = true, next();
+ else if (is_identifier_char(ch)) name += next();
+ else break;
+ }
+ else {
+ if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX");
+ ch = read_escaped_char();
+ if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
+ name += ch;
+ backslash = false;
+ }
+ }
+ if (HOP(KEYWORDS, name) && escaped) {
+ hex = name.charCodeAt(0).toString(16).toUpperCase();
+ name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1);
+ }
+ return name;
+ };
+
+ function read_regexp(regexp) {
+ return with_eof_error("Unterminated regular expression", function(){
+ var prev_backslash = false, ch, in_class = false;
+ while ((ch = next(true))) if (prev_backslash) {
+ regexp += "\\" + ch;
+ prev_backslash = false;
+ } else if (ch == "[") {
+ in_class = true;
+ regexp += ch;
+ } else if (ch == "]" && in_class) {
+ in_class = false;
+ regexp += ch;
+ } else if (ch == "/" && !in_class) {
+ break;
+ } else if (ch == "\\") {
+ prev_backslash = true;
+ } else {
+ regexp += ch;
+ }
+ var mods = read_name();
+ return token("regexp", [ regexp, mods ]);
+ });
+ };
+
+ function read_operator(prefix) {
+ function grow(op) {
+ if (!peek()) return op;
+ var bigger = op + peek();
+ if (HOP(OPERATORS, bigger)) {
+ next();
+ return grow(bigger);
+ } else {
+ return op;
+ }
+ };
+ return token("operator", grow(prefix || next()));
+ };
+
+ function handle_slash() {
+ next();
+ var regex_allowed = S.regex_allowed;
+ switch (peek()) {
+ case "/":
+ S.comments_before.push(read_line_comment());
+ S.regex_allowed = regex_allowed;
+ return next_token();
+ case "*":
+ S.comments_before.push(read_multiline_comment());
+ S.regex_allowed = regex_allowed;
+ return next_token();
+ }
+ return S.regex_allowed ? read_regexp("") : read_operator("/");
+ };
+
+ function handle_dot() {
+ next();
+ return is_digit(peek())
+ ? read_num(".")
+ : token("punc", ".");
+ };
+
+ function read_word() {
+ var word = read_name();
+ return !HOP(KEYWORDS, word)
+ ? token("name", word)
+ : HOP(OPERATORS, word)
+ ? token("operator", word)
+ : HOP(KEYWORDS_ATOM, word)
+ ? token("atom", word)
+ : token("keyword", word);
+ };
+
+ function with_eof_error(eof_error, cont) {
+ try {
+ return cont();
+ } catch(ex) {
+ if (ex === EX_EOF) parse_error(eof_error);
+ else throw ex;
+ }
+ };
+
+ function next_token(force_regexp) {
+ if (force_regexp != null)
+ return read_regexp(force_regexp);
+ skip_whitespace();
+ start_token();
+ var ch = peek();
+ if (!ch) return token("eof");
+ if (is_digit(ch)) return read_num();
+ if (ch == '"' || ch == "'") return read_string();
+ if (HOP(PUNC_CHARS, ch)) return token("punc", next());
+ if (ch == ".") return handle_dot();
+ if (ch == "/") return handle_slash();
+ if (HOP(OPERATOR_CHARS, ch)) return read_operator();
+ if (ch == "\\" || is_identifier_start(ch)) return read_word();
+ parse_error("Unexpected character '" + ch + "'");
+ };
+
+ next_token.context = function(nc) {
+ if (nc) S = nc;
+ return S;
+ };
+
+ return next_token;
+
+};
+
+/* -----[ Parser (constants) ]----- */
+
+var UNARY_PREFIX = array_to_hash([
+ "typeof",
+ "void",
+ "delete",
+ "--",
+ "++",
+ "!",
+ "~",
+ "-",
+ "+"
+]);
+
+var UNARY_POSTFIX = array_to_hash([ "--", "++" ]);
+
+var ASSIGNMENT = (function(a, ret, i){
+ while (i < a.length) {
+ ret[a[i]] = a[i].substr(0, a[i].length - 1);
+ i++;
+ }
+ return ret;
+})(
+ ["+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&="],
+ { "=": true },
+ 0
+);
+
+var PRECEDENCE = (function(a, ret){
+ for (var i = 0, n = 1; i < a.length; ++i, ++n) {
+ var b = a[i];
+ for (var j = 0; j < b.length; ++j) {
+ ret[b[j]] = n;
+ }
+ }
+ return ret;
+})(
+ [
+ ["||"],
+ ["&&"],
+ ["|"],
+ ["^"],
+ ["&"],
+ ["==", "===", "!=", "!=="],
+ ["<", ">", "<=", ">=", "in", "instanceof"],
+ [">>", "<<", ">>>"],
+ ["+", "-"],
+ ["*", "/", "%"]
+ ],
+ {}
+);
+
+var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]);
+
+var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]);
+
+/* -----[ Parser ]----- */
+
+function NodeWithToken(str, start, end) {
+ this.name = str;
+ this.start = start;
+ this.end = end;
+};
+
+NodeWithToken.prototype.toString = function() { return this.name; };
+
+function parse($TEXT, exigent_mode, embed_tokens) {
+
+ var S = {
+ input : typeof $TEXT == "string" ? tokenizer($TEXT, true) : $TEXT,
+ token : null,
+ prev : null,
+ peeked : null,
+ in_function : 0,
+ in_loop : 0,
+ labels : []
+ };
+
+ S.token = next();
+
+ function is(type, value) {
+ return is_token(S.token, type, value);
+ };
+
+ function peek() { return S.peeked || (S.peeked = S.input()); };
+
+ function next() {
+ S.prev = S.token;
+ if (S.peeked) {
+ S.token = S.peeked;
+ S.peeked = null;
+ } else {
+ S.token = S.input();
+ }
+ return S.token;
+ };
+
+ function prev() {
+ return S.prev;
+ };
+
+ function croak(msg, line, col, pos) {
+ var ctx = S.input.context();
+ js_error(msg,
+ line != null ? line : ctx.tokline,
+ col != null ? col : ctx.tokcol,
+ pos != null ? pos : ctx.tokpos);
+ };
+
+ function token_error(token, msg) {
+ croak(msg, token.line, token.col);
+ };
+
+ function unexpected(token) {
+ if (token == null)
+ token = S.token;
+ token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")");
+ };
+
+ function expect_token(type, val) {
+ if (is(type, val)) {
+ return next();
+ }
+ token_error(S.token, "Unexpected token " + S.token.type + ", expected " + type);
+ };
+
+ function expect(punc) { return expect_token("punc", punc); };
+
+ function can_insert_semicolon() {
+ return !exigent_mode && (
+ S.token.nlb || is("eof") || is("punc", "}")
+ );
+ };
+
+ function semicolon() {
+ if (is("punc", ";")) next();
+ else if (!can_insert_semicolon()) unexpected();
+ };
+
+ function as() {
+ return slice(arguments);
+ };
+
+ function parenthesised() {
+ expect("(");
+ var ex = expression();
+ expect(")");
+ return ex;
+ };
+
+ function add_tokens(str, start, end) {
+ return str instanceof NodeWithToken ? str : new NodeWithToken(str, start, end);
+ };
+
+ function maybe_embed_tokens(parser) {
+ if (embed_tokens) return function() {
+ var start = S.token;
+ var ast = parser.apply(this, arguments);
+ ast[0] = add_tokens(ast[0], start, prev());
+ return ast;
+ };
+ else return parser;
+ };
+
+ var statement = maybe_embed_tokens(function() {
+ if (is("operator", "/") || is("operator", "/=")) {
+ S.peeked = null;
+ S.token = S.input(S.token.value.substr(1)); // force regexp
+ }
+ switch (S.token.type) {
+ case "num":
+ case "string":
+ case "regexp":
+ case "operator":
+ case "atom":
+ return simple_statement();
+
+ case "name":
+ return is_token(peek(), "punc", ":")
+ ? labeled_statement(prog1(S.token.value, next, next))
+ : simple_statement();
+
+ case "punc":
+ switch (S.token.value) {
+ case "{":
+ return as("block", block_());
+ case "[":
+ case "(":
+ return simple_statement();
+ case ";":
+ next();
+ return as("block");
+ default:
+ unexpected();
+ }
+
+ case "keyword":
+ switch (prog1(S.token.value, next)) {
+ case "break":
+ return break_cont("break");
+
+ case "continue":
+ return break_cont("continue");
+
+ case "debugger":
+ semicolon();
+ return as("debugger");
+
+ case "do":
+ return (function(body){
+ expect_token("keyword", "while");
+ return as("do", prog1(parenthesised, semicolon), body);
+ })(in_loop(statement));
+
+ case "for":
+ return for_();
+
+ case "function":
+ return function_(true);
+
+ case "if":
+ return if_();
+
+ case "return":
+ if (S.in_function == 0)
+ croak("'return' outside of function");
+ return as("return",
+ is("punc", ";")
+ ? (next(), null)
+ : can_insert_semicolon()
+ ? null
+ : prog1(expression, semicolon));
+
+ case "switch":
+ return as("switch", parenthesised(), switch_block_());
+
+ case "throw":
+ if (S.token.nlb)
+ croak("Illegal newline after 'throw'");
+ return as("throw", prog1(expression, semicolon));
+
+ case "try":
+ return try_();
+
+ case "var":
+ return prog1(var_, semicolon);
+
+ case "const":
+ return prog1(const_, semicolon);
+
+ case "while":
+ return as("while", parenthesised(), in_loop(statement));
+
+ case "with":
+ return as("with", parenthesised(), statement());
+
+ default:
+ unexpected();
+ }
+ }
+ });
+
+ function labeled_statement(label) {
+ S.labels.push(label);
+ var start = S.token, stat = statement();
+ if (exigent_mode && !HOP(STATEMENTS_WITH_LABELS, stat[0]))
+ unexpected(start);
+ S.labels.pop();
+ return as("label", label, stat);
+ };
+
+ function simple_statement() {
+ return as("stat", prog1(expression, semicolon));
+ };
+
+ function break_cont(type) {
+ var name;
+ if (!can_insert_semicolon()) {
+ name = is("name") ? S.token.value : null;
+ }
+ if (name != null) {
+ next();
+ if (!member(name, S.labels))
+ croak("Label " + name + " without matching loop or statement");
+ }
+ else if (S.in_loop == 0)
+ croak(type + " not inside a loop or switch");
+ semicolon();
+ return as(type, name);
+ };
+
+ function for_() {
+ expect("(");
+ var init = null;
+ if (!is("punc", ";")) {
+ init = is("keyword", "var")
+ ? (next(), var_(true))
+ : expression(true, true);
+ if (is("operator", "in")) {
+ if (init[0] == "var" && init[1].length > 1)
+ croak("Only one variable declaration allowed in for..in loop");
+ return for_in(init);
+ }
+ }
+ return regular_for(init);
+ };
+
+ function regular_for(init) {
+ expect(";");
+ var test = is("punc", ";") ? null : expression();
+ expect(";");
+ var step = is("punc", ")") ? null : expression();
+ expect(")");
+ return as("for", init, test, step, in_loop(statement));
+ };
+
+ function for_in(init) {
+ var lhs = init[0] == "var" ? as("name", init[1][0]) : init;
+ next();
+ var obj = expression();
+ expect(")");
+ return as("for-in", init, lhs, obj, in_loop(statement));
+ };
+
+ var function_ = function(in_statement) {
+ var name = is("name") ? prog1(S.token.value, next) : null;
+ if (in_statement && !name)
+ unexpected();
+ expect("(");
+ return as(in_statement ? "defun" : "function",
+ name,
+ // arguments
+ (function(first, a){
+ while (!is("punc", ")")) {
+ if (first) first = false; else expect(",");
+ if (!is("name")) unexpected();
+ a.push(S.token.value);
+ next();
+ }
+ next();
+ return a;
+ })(true, []),
+ // body
+ (function(){
+ ++S.in_function;
+ var loop = S.in_loop;
+ S.in_loop = 0;
+ var a = block_();
+ --S.in_function;
+ S.in_loop = loop;
+ return a;
+ })());
+ };
+
+ function if_() {
+ var cond = parenthesised(), body = statement(), belse;
+ if (is("keyword", "else")) {
+ next();
+ belse = statement();
+ }
+ return as("if", cond, body, belse);
+ };
+
+ function block_() {
+ expect("{");
+ var a = [];
+ while (!is("punc", "}")) {
+ if (is("eof")) unexpected();
+ a.push(statement());
+ }
+ next();
+ return a;
+ };
+
+ var switch_block_ = curry(in_loop, function(){
+ expect("{");
+ var a = [], cur = null;
+ while (!is("punc", "}")) {
+ if (is("eof")) unexpected();
+ if (is("keyword", "case")) {
+ next();
+ cur = [];
+ a.push([ expression(), cur ]);
+ expect(":");
+ }
+ else if (is("keyword", "default")) {
+ next();
+ expect(":");
+ cur = [];
+ a.push([ null, cur ]);
+ }
+ else {
+ if (!cur) unexpected();
+ cur.push(statement());
+ }
+ }
+ next();
+ return a;
+ });
+
+ function try_() {
+ var body = block_(), bcatch, bfinally;
+ if (is("keyword", "catch")) {
+ next();
+ expect("(");
+ if (!is("name"))
+ croak("Name expected");
+ var name = S.token.value;
+ next();
+ expect(")");
+ bcatch = [ name, block_() ];
+ }
+ if (is("keyword", "finally")) {
+ next();
+ bfinally = block_();
+ }
+ if (!bcatch && !bfinally)
+ croak("Missing catch/finally blocks");
+ return as("try", body, bcatch, bfinally);
+ };
+
+ function vardefs(no_in) {
+ var a = [];
+ for (;;) {
+ if (!is("name"))
+ unexpected();
+ var name = S.token.value;
+ next();
+ if (is("operator", "=")) {
+ next();
+ a.push([ name, expression(false, no_in) ]);
+ } else {
+ a.push([ name ]);
+ }
+ if (!is("punc", ","))
+ break;
+ next();
+ }
+ return a;
+ };
+
+ function var_(no_in) {
+ return as("var", vardefs(no_in));
+ };
+
+ function const_() {
+ return as("const", vardefs());
+ };
+
+ function new_() {
+ var newexp = expr_atom(false), args;
+ if (is("punc", "(")) {
+ next();
+ args = expr_list(")");
+ } else {
+ args = [];
+ }
+ return subscripts(as("new", newexp, args), true);
+ };
+
+ var expr_atom = maybe_embed_tokens(function(allow_calls) {
+ if (is("operator", "new")) {
+ next();
+ return new_();
+ }
+ if (is("punc")) {
+ switch (S.token.value) {
+ case "(":
+ next();
+ return subscripts(prog1(expression, curry(expect, ")")), allow_calls);
+ case "[":
+ next();
+ return subscripts(array_(), allow_calls);
+ case "{":
+ next();
+ return subscripts(object_(), allow_calls);
+ }
+ unexpected();
+ }
+ if (is("keyword", "function")) {
+ next();
+ return subscripts(function_(false), allow_calls);
+ }
+ if (HOP(ATOMIC_START_TOKEN, S.token.type)) {
+ var atom = S.token.type == "regexp"
+ ? as("regexp", S.token.value[0], S.token.value[1])
+ : as(S.token.type, S.token.value);
+ return subscripts(prog1(atom, next), allow_calls);
+ }
+ unexpected();
+ });
+
+ function expr_list(closing, allow_trailing_comma, allow_empty) {
+ var first = true, a = [];
+ while (!is("punc", closing)) {
+ if (first) first = false; else expect(",");
+ if (allow_trailing_comma && is("punc", closing)) break;
+ if (is("punc", ",") && allow_empty) {
+ a.push([ "atom", "undefined" ]);
+ } else {
+ a.push(expression(false));
+ }
+ }
+ next();
+ return a;
+ };
+
+ function array_() {
+ return as("array", expr_list("]", !exigent_mode, true));
+ };
+
+ function object_() {
+ var first = true, a = [];
+ while (!is("punc", "}")) {
+ if (first) first = false; else expect(",");
+ if (!exigent_mode && is("punc", "}"))
+ // allow trailing comma
+ break;
+ var type = S.token.type;
+ var name = as_property_name();
+ if (type == "name" && (name == "get" || name == "set") && !is("punc", ":")) {
+ a.push([ as_name(), function_(false), name ]);
+ } else {
+ expect(":");
+ a.push([ name, expression(false) ]);
+ }
+ }
+ next();
+ return as("object", a);
+ };
+
+ function as_property_name() {
+ switch (S.token.type) {
+ case "num":
+ case "string":
+ return prog1(S.token.value, next);
+ }
+ return as_name();
+ };
+
+ function as_name() {
+ switch (S.token.type) {
+ case "name":
+ case "operator":
+ case "keyword":
+ case "atom":
+ return prog1(S.token.value, next);
+ default:
+ unexpected();
+ }
+ };
+
+ function subscripts(expr, allow_calls) {
+ if (is("punc", ".")) {
+ next();
+ return subscripts(as("dot", expr, as_name()), allow_calls);
+ }
+ if (is("punc", "[")) {
+ next();
+ return subscripts(as("sub", expr, prog1(expression, curry(expect, "]"))), allow_calls);
+ }
+ if (allow_calls && is("punc", "(")) {
+ next();
+ return subscripts(as("call", expr, expr_list(")")), true);
+ }
+ return expr;
+ };
+
+ function maybe_unary(allow_calls) {
+ if (is("operator") && HOP(UNARY_PREFIX, S.token.value)) {
+ return make_unary("unary-prefix",
+ prog1(S.token.value, next),
+ maybe_unary(allow_calls));
+ }
+ var val = expr_atom(allow_calls);
+ while (is("operator") && HOP(UNARY_POSTFIX, S.token.value) && !S.token.nlb) {
+ val = make_unary("unary-postfix", S.token.value, val);
+ next();
+ }
+ return val;
+ };
+
+ function make_unary(tag, op, expr) {
+ if ((op == "++" || op == "--") && !is_assignable(expr))
+ croak("Invalid use of " + op + " operator");
+ return as(tag, op, expr);
+ };
+
+ function expr_op(left, min_prec, no_in) {
+ var op = is("operator") ? S.token.value : null;
+ if (op && op == "in" && no_in) op = null;
+ var prec = op != null ? PRECEDENCE[op] : null;
+ if (prec != null && prec > min_prec) {
+ next();
+ var right = expr_op(maybe_unary(true), prec, no_in);
+ return expr_op(as("binary", op, left, right), min_prec, no_in);
+ }
+ return left;
+ };
+
+ function expr_ops(no_in) {
+ return expr_op(maybe_unary(true), 0, no_in);
+ };
+
+ function maybe_conditional(no_in) {
+ var expr = expr_ops(no_in);
+ if (is("operator", "?")) {
+ next();
+ var yes = expression(false);
+ expect(":");
+ return as("conditional", expr, yes, expression(false, no_in));
+ }
+ return expr;
+ };
+
+ function is_assignable(expr) {
+ if (!exigent_mode) return true;
+ switch (expr[0]+"") {
+ case "dot":
+ case "sub":
+ case "new":
+ case "call":
+ return true;
+ case "name":
+ return expr[1] != "this";
+ }
+ };
+
+ function maybe_assign(no_in) {
+ var left = maybe_conditional(no_in), val = S.token.value;
+ if (is("operator") && HOP(ASSIGNMENT, val)) {
+ if (is_assignable(left)) {
+ next();
+ return as("assign", ASSIGNMENT[val], left, maybe_assign(no_in));
+ }
+ croak("Invalid assignment");
+ }
+ return left;
+ };
+
+ var expression = maybe_embed_tokens(function(commas, no_in) {
+ if (arguments.length == 0)
+ commas = true;
+ var expr = maybe_assign(no_in);
+ if (commas && is("punc", ",")) {
+ next();
+ return as("seq", expr, expression(true, no_in));
+ }
+ return expr;
+ });
+
+ function in_loop(cont) {
+ try {
+ ++S.in_loop;
+ return cont();
+ } finally {
+ --S.in_loop;
+ }
+ };
+
+ return as("toplevel", (function(a){
+ while (!is("eof"))
+ a.push(statement());
+ return a;
+ })([]));
+
+};
+
+/* -----[ Utilities ]----- */
+
+function curry(f) {
+ var args = slice(arguments, 1);
+ return function() { return f.apply(this, args.concat(slice(arguments))); };
+};
+
+function prog1(ret) {
+ if (ret instanceof Function)
+ ret = ret();
+ for (var i = 1, n = arguments.length; --n > 0; ++i)
+ arguments[i]();
+ return ret;
+};
+
+function array_to_hash(a) {
+ var ret = {};
+ for (var i = 0; i < a.length; ++i)
+ ret[a[i]] = true;
+ return ret;
+};
+
+function slice(a, start) {
+ return Array.prototype.slice.call(a, start || 0);
+};
+
+function characters(str) {
+ return str.split("");
+};
+
+function member(name, array) {
+ for (var i = array.length; --i >= 0;)
+ if (array[i] == name)
+ return true;
+ return false;
+};
+
+function HOP(obj, prop) {
+ return Object.prototype.hasOwnProperty.call(obj, prop);
+};
+
+var warn = function() {};
+
+/* -----[ Exports ]----- */
+
+exports.tokenizer = tokenizer;
+exports.parse = parse;
+exports.slice = slice;
+exports.curry = curry;
+exports.member = member;
+exports.array_to_hash = array_to_hash;
+exports.PRECEDENCE = PRECEDENCE;
+exports.KEYWORDS_ATOM = KEYWORDS_ATOM;
+exports.RESERVED_WORDS = RESERVED_WORDS;
+exports.KEYWORDS = KEYWORDS;
+exports.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN;
+exports.OPERATORS = OPERATORS;
+exports.is_alphanumeric_char = is_alphanumeric_char;
+exports.set_logger = function(logger) {
+ warn = logger;
+};
diff --git a/node_modules/handlebars/node_modules/uglify-js/lib/process.js b/node_modules/handlebars/node_modules/uglify-js/lib/process.js
new file mode 100644
index 0000000000..da5553c710
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/lib/process.js
@@ -0,0 +1,2011 @@
+/***********************************************************************
+
+ A JavaScript tokenizer / parser / beautifier / compressor.
+
+ This version is suitable for Node.js. With minimal changes (the
+ exports stuff) it should work on any JS platform.
+
+ This file implements some AST processors. They work on data built
+ by parse-js.
+
+ Exported functions:
+
+ - ast_mangle(ast, options) -- mangles the variable/function names
+ in the AST. Returns an AST.
+
+ - ast_squeeze(ast) -- employs various optimizations to make the
+ final generated code even smaller. Returns an AST.
+
+ - gen_code(ast, options) -- generates JS code from the AST. Pass
+ true (or an object, see the code for some options) as second
+ argument to get "pretty" (indented) code.
+
+ -------------------------------- (C) ---------------------------------
+
+ Author: Mihai Bazon
+
+ http://mihai.bazon.net/blog
+
+ Distributed under the BSD license:
+
+ Copyright 2010 (c) Mihai Bazon
+
+ 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.
+
+ ***********************************************************************/
+
+var jsp = require("./parse-js"),
+ slice = jsp.slice,
+ member = jsp.member,
+ PRECEDENCE = jsp.PRECEDENCE,
+ OPERATORS = jsp.OPERATORS;
+
+/* -----[ helper for AST traversal ]----- */
+
+function ast_walker() {
+ function _vardefs(defs) {
+ return [ this[0], MAP(defs, function(def){
+ var a = [ def[0] ];
+ if (def.length > 1)
+ a[1] = walk(def[1]);
+ return a;
+ }) ];
+ };
+ function _block(statements) {
+ var out = [ this[0] ];
+ if (statements != null)
+ out.push(MAP(statements, walk));
+ return out;
+ };
+ var walkers = {
+ "string": function(str) {
+ return [ this[0], str ];
+ },
+ "num": function(num) {
+ return [ this[0], num ];
+ },
+ "name": function(name) {
+ return [ this[0], name ];
+ },
+ "toplevel": function(statements) {
+ return [ this[0], MAP(statements, walk) ];
+ },
+ "block": _block,
+ "splice": _block,
+ "var": _vardefs,
+ "const": _vardefs,
+ "try": function(t, c, f) {
+ return [
+ this[0],
+ MAP(t, walk),
+ c != null ? [ c[0], MAP(c[1], walk) ] : null,
+ f != null ? MAP(f, walk) : null
+ ];
+ },
+ "throw": function(expr) {
+ return [ this[0], walk(expr) ];
+ },
+ "new": function(ctor, args) {
+ return [ this[0], walk(ctor), MAP(args, walk) ];
+ },
+ "switch": function(expr, body) {
+ return [ this[0], walk(expr), MAP(body, function(branch){
+ return [ branch[0] ? walk(branch[0]) : null,
+ MAP(branch[1], walk) ];
+ }) ];
+ },
+ "break": function(label) {
+ return [ this[0], label ];
+ },
+ "continue": function(label) {
+ return [ this[0], label ];
+ },
+ "conditional": function(cond, t, e) {
+ return [ this[0], walk(cond), walk(t), walk(e) ];
+ },
+ "assign": function(op, lvalue, rvalue) {
+ return [ this[0], op, walk(lvalue), walk(rvalue) ];
+ },
+ "dot": function(expr) {
+ return [ this[0], walk(expr) ].concat(slice(arguments, 1));
+ },
+ "call": function(expr, args) {
+ return [ this[0], walk(expr), MAP(args, walk) ];
+ },
+ "function": function(name, args, body) {
+ return [ this[0], name, args.slice(), MAP(body, walk) ];
+ },
+ "debugger": function() {
+ return [ this[0] ];
+ },
+ "defun": function(name, args, body) {
+ return [ this[0], name, args.slice(), MAP(body, walk) ];
+ },
+ "if": function(conditional, t, e) {
+ return [ this[0], walk(conditional), walk(t), walk(e) ];
+ },
+ "for": function(init, cond, step, block) {
+ return [ this[0], walk(init), walk(cond), walk(step), walk(block) ];
+ },
+ "for-in": function(vvar, key, hash, block) {
+ return [ this[0], walk(vvar), walk(key), walk(hash), walk(block) ];
+ },
+ "while": function(cond, block) {
+ return [ this[0], walk(cond), walk(block) ];
+ },
+ "do": function(cond, block) {
+ return [ this[0], walk(cond), walk(block) ];
+ },
+ "return": function(expr) {
+ return [ this[0], walk(expr) ];
+ },
+ "binary": function(op, left, right) {
+ return [ this[0], op, walk(left), walk(right) ];
+ },
+ "unary-prefix": function(op, expr) {
+ return [ this[0], op, walk(expr) ];
+ },
+ "unary-postfix": function(op, expr) {
+ return [ this[0], op, walk(expr) ];
+ },
+ "sub": function(expr, subscript) {
+ return [ this[0], walk(expr), walk(subscript) ];
+ },
+ "object": function(props) {
+ return [ this[0], MAP(props, function(p){
+ return p.length == 2
+ ? [ p[0], walk(p[1]) ]
+ : [ p[0], walk(p[1]), p[2] ]; // get/set-ter
+ }) ];
+ },
+ "regexp": function(rx, mods) {
+ return [ this[0], rx, mods ];
+ },
+ "array": function(elements) {
+ return [ this[0], MAP(elements, walk) ];
+ },
+ "stat": function(stat) {
+ return [ this[0], walk(stat) ];
+ },
+ "seq": function() {
+ return [ this[0] ].concat(MAP(slice(arguments), walk));
+ },
+ "label": function(name, block) {
+ return [ this[0], name, walk(block) ];
+ },
+ "with": function(expr, block) {
+ return [ this[0], walk(expr), walk(block) ];
+ },
+ "atom": function(name) {
+ return [ this[0], name ];
+ }
+ };
+
+ var user = {};
+ var stack = [];
+ function walk(ast) {
+ if (ast == null)
+ return null;
+ try {
+ stack.push(ast);
+ var type = ast[0];
+ var gen = user[type];
+ if (gen) {
+ var ret = gen.apply(ast, ast.slice(1));
+ if (ret != null)
+ return ret;
+ }
+ gen = walkers[type];
+ return gen.apply(ast, ast.slice(1));
+ } finally {
+ stack.pop();
+ }
+ };
+
+ function dive(ast) {
+ if (ast == null)
+ return null;
+ try {
+ stack.push(ast);
+ return walkers[ast[0]].apply(ast, ast.slice(1));
+ } finally {
+ stack.pop();
+ }
+ };
+
+ function with_walkers(walkers, cont){
+ var save = {}, i;
+ for (i in walkers) if (HOP(walkers, i)) {
+ save[i] = user[i];
+ user[i] = walkers[i];
+ }
+ var ret = cont();
+ for (i in save) if (HOP(save, i)) {
+ if (!save[i]) delete user[i];
+ else user[i] = save[i];
+ }
+ return ret;
+ };
+
+ return {
+ walk: walk,
+ dive: dive,
+ with_walkers: with_walkers,
+ parent: function() {
+ return stack[stack.length - 2]; // last one is current node
+ },
+ stack: function() {
+ return stack;
+ }
+ };
+};
+
+/* -----[ Scope and mangling ]----- */
+
+function Scope(parent) {
+ this.names = {}; // names defined in this scope
+ this.mangled = {}; // mangled names (orig.name => mangled)
+ this.rev_mangled = {}; // reverse lookup (mangled => orig.name)
+ this.cname = -1; // current mangled name
+ this.refs = {}; // names referenced from this scope
+ this.uses_with = false; // will become TRUE if with() is detected in this or any subscopes
+ this.uses_eval = false; // will become TRUE if eval() is detected in this or any subscopes
+ this.parent = parent; // parent scope
+ this.children = []; // sub-scopes
+ if (parent) {
+ this.level = parent.level + 1;
+ parent.children.push(this);
+ } else {
+ this.level = 0;
+ }
+};
+
+var base54 = (function(){
+ var DIGITS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
+ return function(num) {
+ var ret = "", base = 54;
+ do {
+ ret += DIGITS.charAt(num % base);
+ num = Math.floor(num / base);
+ base = 64;
+ } while (num > 0);
+ return ret;
+ };
+})();
+
+Scope.prototype = {
+ has: function(name) {
+ for (var s = this; s; s = s.parent)
+ if (HOP(s.names, name))
+ return s;
+ },
+ has_mangled: function(mname) {
+ for (var s = this; s; s = s.parent)
+ if (HOP(s.rev_mangled, mname))
+ return s;
+ },
+ toJSON: function() {
+ return {
+ names: this.names,
+ uses_eval: this.uses_eval,
+ uses_with: this.uses_with
+ };
+ },
+
+ next_mangled: function() {
+ // we must be careful that the new mangled name:
+ //
+ // 1. doesn't shadow a mangled name from a parent
+ // scope, unless we don't reference the original
+ // name from this scope OR from any sub-scopes!
+ // This will get slow.
+ //
+ // 2. doesn't shadow an original name from a parent
+ // scope, in the event that the name is not mangled
+ // in the parent scope and we reference that name
+ // here OR IN ANY SUBSCOPES!
+ //
+ // 3. doesn't shadow a name that is referenced but not
+ // defined (possibly global defined elsewhere).
+ for (;;) {
+ var m = base54(++this.cname), prior;
+
+ // case 1.
+ prior = this.has_mangled(m);
+ if (prior && this.refs[prior.rev_mangled[m]] === prior)
+ continue;
+
+ // case 2.
+ prior = this.has(m);
+ if (prior && prior !== this && this.refs[m] === prior && !prior.has_mangled(m))
+ continue;
+
+ // case 3.
+ if (HOP(this.refs, m) && this.refs[m] == null)
+ continue;
+
+ // I got "do" once. :-/
+ if (!is_identifier(m))
+ continue;
+
+ return m;
+ }
+ },
+ set_mangle: function(name, m) {
+ this.rev_mangled[m] = name;
+ return this.mangled[name] = m;
+ },
+ get_mangled: function(name, newMangle) {
+ if (this.uses_eval || this.uses_with) return name; // no mangle if eval or with is in use
+ var s = this.has(name);
+ if (!s) return name; // not in visible scope, no mangle
+ if (HOP(s.mangled, name)) return s.mangled[name]; // already mangled in this scope
+ if (!newMangle) return name; // not found and no mangling requested
+ return s.set_mangle(name, s.next_mangled());
+ },
+ references: function(name) {
+ return name && !this.parent || this.uses_with || this.uses_eval || this.refs[name];
+ },
+ define: function(name, type) {
+ if (name != null) {
+ if (type == "var" || !HOP(this.names, name))
+ this.names[name] = type || "var";
+ return name;
+ }
+ }
+};
+
+function ast_add_scope(ast) {
+
+ var current_scope = null;
+ var w = ast_walker(), walk = w.walk;
+ var having_eval = [];
+
+ function with_new_scope(cont) {
+ current_scope = new Scope(current_scope);
+ current_scope.labels = new Scope();
+ var ret = current_scope.body = cont();
+ ret.scope = current_scope;
+ current_scope = current_scope.parent;
+ return ret;
+ };
+
+ function define(name, type) {
+ return current_scope.define(name, type);
+ };
+
+ function reference(name) {
+ current_scope.refs[name] = true;
+ };
+
+ function _lambda(name, args, body) {
+ var is_defun = this[0] == "defun";
+ return [ this[0], is_defun ? define(name, "defun") : name, args, with_new_scope(function(){
+ if (!is_defun) define(name, "lambda");
+ MAP(args, function(name){ define(name, "arg") });
+ return MAP(body, walk);
+ })];
+ };
+
+ function _vardefs(type) {
+ return function(defs) {
+ MAP(defs, function(d){
+ define(d[0], type);
+ if (d[1]) reference(d[0]);
+ });
+ };
+ };
+
+ function _breacont(label) {
+ if (label)
+ current_scope.labels.refs[label] = true;
+ };
+
+ return with_new_scope(function(){
+ // process AST
+ var ret = w.with_walkers({
+ "function": _lambda,
+ "defun": _lambda,
+ "label": function(name, stat) { current_scope.labels.define(name) },
+ "break": _breacont,
+ "continue": _breacont,
+ "with": function(expr, block) {
+ for (var s = current_scope; s; s = s.parent)
+ s.uses_with = true;
+ },
+ "var": _vardefs("var"),
+ "const": _vardefs("const"),
+ "try": function(t, c, f) {
+ if (c != null) return [
+ this[0],
+ MAP(t, walk),
+ [ define(c[0], "catch"), MAP(c[1], walk) ],
+ f != null ? MAP(f, walk) : null
+ ];
+ },
+ "name": function(name) {
+ if (name == "eval")
+ having_eval.push(current_scope);
+ reference(name);
+ }
+ }, function(){
+ return walk(ast);
+ });
+
+ // the reason why we need an additional pass here is
+ // that names can be used prior to their definition.
+
+ // scopes where eval was detected and their parents
+ // are marked with uses_eval, unless they define the
+ // "eval" name.
+ MAP(having_eval, function(scope){
+ if (!scope.has("eval")) while (scope) {
+ scope.uses_eval = true;
+ scope = scope.parent;
+ }
+ });
+
+ // for referenced names it might be useful to know
+ // their origin scope. current_scope here is the
+ // toplevel one.
+ function fixrefs(scope, i) {
+ // do children first; order shouldn't matter
+ for (i = scope.children.length; --i >= 0;)
+ fixrefs(scope.children[i]);
+ for (i in scope.refs) if (HOP(scope.refs, i)) {
+ // find origin scope and propagate the reference to origin
+ for (var origin = scope.has(i), s = scope; s; s = s.parent) {
+ s.refs[i] = origin;
+ if (s === origin) break;
+ }
+ }
+ };
+ fixrefs(current_scope);
+
+ return ret;
+ });
+
+};
+
+/* -----[ mangle names ]----- */
+
+function ast_mangle(ast, options) {
+ var w = ast_walker(), walk = w.walk, scope;
+ options = options || {};
+
+ function get_mangled(name, newMangle) {
+ if (!options.toplevel && !scope.parent) return name; // don't mangle toplevel
+ if (options.except && member(name, options.except))
+ return name;
+ return scope.get_mangled(name, newMangle);
+ };
+
+ function get_define(name) {
+ if (options.defines) {
+ // we always lookup a defined symbol for the current scope FIRST, so declared
+ // vars trump a DEFINE symbol, but if no such var is found, then match a DEFINE value
+ if (!scope.has(name)) {
+ if (HOP(options.defines, name)) {
+ return options.defines[name];
+ }
+ }
+ return null;
+ }
+ };
+
+ function _lambda(name, args, body) {
+ if (!options.no_functions) {
+ var is_defun = this[0] == "defun", extra;
+ if (name) {
+ if (is_defun) name = get_mangled(name);
+ else if (body.scope.references(name)) {
+ extra = {};
+ if (!(scope.uses_eval || scope.uses_with))
+ name = extra[name] = scope.next_mangled();
+ else
+ extra[name] = name;
+ }
+ else name = null;
+ }
+ }
+ body = with_scope(body.scope, function(){
+ args = MAP(args, function(name){ return get_mangled(name) });
+ return MAP(body, walk);
+ }, extra);
+ return [ this[0], name, args, body ];
+ };
+
+ function with_scope(s, cont, extra) {
+ var _scope = scope;
+ scope = s;
+ if (extra) for (var i in extra) if (HOP(extra, i)) {
+ s.set_mangle(i, extra[i]);
+ }
+ for (var i in s.names) if (HOP(s.names, i)) {
+ get_mangled(i, true);
+ }
+ var ret = cont();
+ ret.scope = s;
+ scope = _scope;
+ return ret;
+ };
+
+ function _vardefs(defs) {
+ return [ this[0], MAP(defs, function(d){
+ return [ get_mangled(d[0]), walk(d[1]) ];
+ }) ];
+ };
+
+ function _breacont(label) {
+ if (label) return [ this[0], scope.labels.get_mangled(label) ];
+ };
+
+ return w.with_walkers({
+ "function": _lambda,
+ "defun": function() {
+ // move function declarations to the top when
+ // they are not in some block.
+ var ast = _lambda.apply(this, arguments);
+ switch (w.parent()[0]) {
+ case "toplevel":
+ case "function":
+ case "defun":
+ return MAP.at_top(ast);
+ }
+ return ast;
+ },
+ "label": function(label, stat) {
+ if (scope.labels.refs[label]) return [
+ this[0],
+ scope.labels.get_mangled(label, true),
+ walk(stat)
+ ];
+ return walk(stat);
+ },
+ "break": _breacont,
+ "continue": _breacont,
+ "var": _vardefs,
+ "const": _vardefs,
+ "name": function(name) {
+ return get_define(name) || [ this[0], get_mangled(name) ];
+ },
+ "try": function(t, c, f) {
+ return [ this[0],
+ MAP(t, walk),
+ c != null ? [ get_mangled(c[0]), MAP(c[1], walk) ] : null,
+ f != null ? MAP(f, walk) : null ];
+ },
+ "toplevel": function(body) {
+ var self = this;
+ return with_scope(self.scope, function(){
+ return [ self[0], MAP(body, walk) ];
+ });
+ }
+ }, function() {
+ return walk(ast_add_scope(ast));
+ });
+};
+
+/* -----[
+ - compress foo["bar"] into foo.bar,
+ - remove block brackets {} where possible
+ - join consecutive var declarations
+ - various optimizations for IFs:
+ - if (cond) foo(); else bar(); ==> cond?foo():bar();
+ - if (cond) foo(); ==> cond&&foo();
+ - if (foo) return bar(); else return baz(); ==> return foo?bar():baz(); // also for throw
+ - if (foo) return bar(); else something(); ==> {if(foo)return bar();something()}
+ ]----- */
+
+var warn = function(){};
+
+function best_of(ast1, ast2) {
+ return gen_code(ast1).length > gen_code(ast2[0] == "stat" ? ast2[1] : ast2).length ? ast2 : ast1;
+};
+
+function last_stat(b) {
+ if (b[0] == "block" && b[1] && b[1].length > 0)
+ return b[1][b[1].length - 1];
+ return b;
+}
+
+function aborts(t) {
+ if (t) switch (last_stat(t)[0]) {
+ case "return":
+ case "break":
+ case "continue":
+ case "throw":
+ return true;
+ }
+};
+
+function boolean_expr(expr) {
+ return ( (expr[0] == "unary-prefix"
+ && member(expr[1], [ "!", "delete" ])) ||
+
+ (expr[0] == "binary"
+ && member(expr[1], [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ])) ||
+
+ (expr[0] == "binary"
+ && member(expr[1], [ "&&", "||" ])
+ && boolean_expr(expr[2])
+ && boolean_expr(expr[3])) ||
+
+ (expr[0] == "conditional"
+ && boolean_expr(expr[2])
+ && boolean_expr(expr[3])) ||
+
+ (expr[0] == "assign"
+ && expr[1] === true
+ && boolean_expr(expr[3])) ||
+
+ (expr[0] == "seq"
+ && boolean_expr(expr[expr.length - 1]))
+ );
+};
+
+function empty(b) {
+ return !b || (b[0] == "block" && (!b[1] || b[1].length == 0));
+};
+
+function is_string(node) {
+ return (node[0] == "string" ||
+ node[0] == "unary-prefix" && node[1] == "typeof" ||
+ node[0] == "binary" && node[1] == "+" &&
+ (is_string(node[2]) || is_string(node[3])));
+};
+
+var when_constant = (function(){
+
+ var $NOT_CONSTANT = {};
+
+ // this can only evaluate constant expressions. If it finds anything
+ // not constant, it throws $NOT_CONSTANT.
+ function evaluate(expr) {
+ switch (expr[0]) {
+ case "string":
+ case "num":
+ return expr[1];
+ case "name":
+ case "atom":
+ switch (expr[1]) {
+ case "true": return true;
+ case "false": return false;
+ case "null": return null;
+ }
+ break;
+ case "unary-prefix":
+ switch (expr[1]) {
+ case "!": return !evaluate(expr[2]);
+ case "typeof": return typeof evaluate(expr[2]);
+ case "~": return ~evaluate(expr[2]);
+ case "-": return -evaluate(expr[2]);
+ case "+": return +evaluate(expr[2]);
+ }
+ break;
+ case "binary":
+ var left = expr[2], right = expr[3];
+ switch (expr[1]) {
+ case "&&" : return evaluate(left) && evaluate(right);
+ case "||" : return evaluate(left) || evaluate(right);
+ case "|" : return evaluate(left) | evaluate(right);
+ case "&" : return evaluate(left) & evaluate(right);
+ case "^" : return evaluate(left) ^ evaluate(right);
+ case "+" : return evaluate(left) + evaluate(right);
+ case "*" : return evaluate(left) * evaluate(right);
+ case "/" : return evaluate(left) / evaluate(right);
+ case "%" : return evaluate(left) % evaluate(right);
+ case "-" : return evaluate(left) - evaluate(right);
+ case "<<" : return evaluate(left) << evaluate(right);
+ case ">>" : return evaluate(left) >> evaluate(right);
+ case ">>>" : return evaluate(left) >>> evaluate(right);
+ case "==" : return evaluate(left) == evaluate(right);
+ case "===" : return evaluate(left) === evaluate(right);
+ case "!=" : return evaluate(left) != evaluate(right);
+ case "!==" : return evaluate(left) !== evaluate(right);
+ case "<" : return evaluate(left) < evaluate(right);
+ case "<=" : return evaluate(left) <= evaluate(right);
+ case ">" : return evaluate(left) > evaluate(right);
+ case ">=" : return evaluate(left) >= evaluate(right);
+ case "in" : return evaluate(left) in evaluate(right);
+ case "instanceof" : return evaluate(left) instanceof evaluate(right);
+ }
+ }
+ throw $NOT_CONSTANT;
+ };
+
+ return function(expr, yes, no) {
+ try {
+ var val = evaluate(expr), ast;
+ switch (typeof val) {
+ case "string": ast = [ "string", val ]; break;
+ case "number": ast = [ "num", val ]; break;
+ case "boolean": ast = [ "name", String(val) ]; break;
+ default:
+ if (val === null) { ast = [ "atom", "null" ]; break; }
+ throw new Error("Can't handle constant of type: " + (typeof val));
+ }
+ return yes.call(expr, ast, val);
+ } catch(ex) {
+ if (ex === $NOT_CONSTANT) {
+ if (expr[0] == "binary"
+ && (expr[1] == "===" || expr[1] == "!==")
+ && ((is_string(expr[2]) && is_string(expr[3]))
+ || (boolean_expr(expr[2]) && boolean_expr(expr[3])))) {
+ expr[1] = expr[1].substr(0, 2);
+ }
+ else if (no && expr[0] == "binary"
+ && (expr[1] == "||" || expr[1] == "&&")) {
+ // the whole expression is not constant but the lval may be...
+ try {
+ var lval = evaluate(expr[2]);
+ expr = ((expr[1] == "&&" && (lval ? expr[3] : lval)) ||
+ (expr[1] == "||" && (lval ? lval : expr[3])) ||
+ expr);
+ } catch(ex2) {
+ // IGNORE... lval is not constant
+ }
+ }
+ return no ? no.call(expr, expr) : null;
+ }
+ else throw ex;
+ }
+ };
+
+})();
+
+function warn_unreachable(ast) {
+ if (!empty(ast))
+ warn("Dropping unreachable code: " + gen_code(ast, true));
+};
+
+function prepare_ifs(ast) {
+ var w = ast_walker(), walk = w.walk;
+ // In this first pass, we rewrite ifs which abort with no else with an
+ // if-else. For example:
+ //
+ // if (x) {
+ // blah();
+ // return y;
+ // }
+ // foobar();
+ //
+ // is rewritten into:
+ //
+ // if (x) {
+ // blah();
+ // return y;
+ // } else {
+ // foobar();
+ // }
+ function redo_if(statements) {
+ statements = MAP(statements, walk);
+
+ for (var i = 0; i < statements.length; ++i) {
+ var fi = statements[i];
+ if (fi[0] != "if") continue;
+
+ if (fi[3] && walk(fi[3])) continue;
+
+ var t = walk(fi[2]);
+ if (!aborts(t)) continue;
+
+ var conditional = walk(fi[1]);
+
+ var e_body = redo_if(statements.slice(i + 1));
+ var e = e_body.length == 1 ? e_body[0] : [ "block", e_body ];
+
+ return statements.slice(0, i).concat([ [
+ fi[0], // "if"
+ conditional, // conditional
+ t, // then
+ e // else
+ ] ]);
+ }
+
+ return statements;
+ };
+
+ function redo_if_lambda(name, args, body) {
+ body = redo_if(body);
+ return [ this[0], name, args, body ];
+ };
+
+ function redo_if_block(statements) {
+ return [ this[0], statements != null ? redo_if(statements) : null ];
+ };
+
+ return w.with_walkers({
+ "defun": redo_if_lambda,
+ "function": redo_if_lambda,
+ "block": redo_if_block,
+ "splice": redo_if_block,
+ "toplevel": function(statements) {
+ return [ this[0], redo_if(statements) ];
+ },
+ "try": function(t, c, f) {
+ return [
+ this[0],
+ redo_if(t),
+ c != null ? [ c[0], redo_if(c[1]) ] : null,
+ f != null ? redo_if(f) : null
+ ];
+ }
+ }, function() {
+ return walk(ast);
+ });
+};
+
+function for_side_effects(ast, handler) {
+ var w = ast_walker(), walk = w.walk;
+ var $stop = {}, $restart = {};
+ function stop() { throw $stop };
+ function restart() { throw $restart };
+ function found(){ return handler.call(this, this, w, stop, restart) };
+ function unary(op) {
+ if (op == "++" || op == "--")
+ return found.apply(this, arguments);
+ };
+ return w.with_walkers({
+ "try": found,
+ "throw": found,
+ "return": found,
+ "new": found,
+ "switch": found,
+ "break": found,
+ "continue": found,
+ "assign": found,
+ "call": found,
+ "if": found,
+ "for": found,
+ "for-in": found,
+ "while": found,
+ "do": found,
+ "return": found,
+ "unary-prefix": unary,
+ "unary-postfix": unary,
+ "defun": found
+ }, function(){
+ while (true) try {
+ walk(ast);
+ break;
+ } catch(ex) {
+ if (ex === $stop) break;
+ if (ex === $restart) continue;
+ throw ex;
+ }
+ });
+};
+
+function ast_lift_variables(ast) {
+ var w = ast_walker(), walk = w.walk, scope;
+ function do_body(body, env) {
+ var _scope = scope;
+ scope = env;
+ body = MAP(body, walk);
+ var hash = {}, names = MAP(env.names, function(type, name){
+ if (type != "var") return MAP.skip;
+ if (!env.references(name)) return MAP.skip;
+ hash[name] = true;
+ return [ name ];
+ });
+ if (names.length > 0) {
+ // looking for assignments to any of these variables.
+ // we can save considerable space by moving the definitions
+ // in the var declaration.
+ for_side_effects([ "block", body ], function(ast, walker, stop, restart) {
+ if (ast[0] == "assign"
+ && ast[1] === true
+ && ast[2][0] == "name"
+ && HOP(hash, ast[2][1])) {
+ // insert the definition into the var declaration
+ for (var i = names.length; --i >= 0;) {
+ if (names[i][0] == ast[2][1]) {
+ if (names[i][1]) // this name already defined, we must stop
+ stop();
+ names[i][1] = ast[3]; // definition
+ names.push(names.splice(i, 1)[0]);
+ break;
+ }
+ }
+ // remove this assignment from the AST.
+ var p = walker.parent();
+ if (p[0] == "seq") {
+ var a = p[2];
+ a.unshift(0, p.length);
+ p.splice.apply(p, a);
+ }
+ else if (p[0] == "stat") {
+ p.splice(0, p.length, "block"); // empty statement
+ }
+ else {
+ stop();
+ }
+ restart();
+ }
+ stop();
+ });
+ body.unshift([ "var", names ]);
+ }
+ scope = _scope;
+ return body;
+ };
+ function _vardefs(defs) {
+ var ret = null;
+ for (var i = defs.length; --i >= 0;) {
+ var d = defs[i];
+ if (!d[1]) continue;
+ d = [ "assign", true, [ "name", d[0] ], d[1] ];
+ if (ret == null) ret = d;
+ else ret = [ "seq", d, ret ];
+ }
+ if (ret == null) {
+ if (w.parent()[0] == "for-in")
+ return [ "name", defs[0][0] ];
+ return MAP.skip;
+ }
+ return [ "stat", ret ];
+ };
+ function _toplevel(body) {
+ return [ this[0], do_body(body, this.scope) ];
+ };
+ return w.with_walkers({
+ "function": function(name, args, body){
+ for (var i = args.length; --i >= 0 && !body.scope.references(args[i]);)
+ args.pop();
+ if (!body.scope.references(name)) name = null;
+ return [ this[0], name, args, do_body(body, body.scope) ];
+ },
+ "defun": function(name, args, body){
+ if (!scope.references(name)) return MAP.skip;
+ for (var i = args.length; --i >= 0 && !body.scope.references(args[i]);)
+ args.pop();
+ return [ this[0], name, args, do_body(body, body.scope) ];
+ },
+ "var": _vardefs,
+ "toplevel": _toplevel
+ }, function(){
+ return walk(ast_add_scope(ast));
+ });
+};
+
+function ast_squeeze(ast, options) {
+ options = defaults(options, {
+ make_seqs : true,
+ dead_code : true,
+ no_warnings : false,
+ keep_comps : true
+ });
+
+ var w = ast_walker(), walk = w.walk;
+
+ function negate(c) {
+ var not_c = [ "unary-prefix", "!", c ];
+ switch (c[0]) {
+ case "unary-prefix":
+ return c[1] == "!" && boolean_expr(c[2]) ? c[2] : not_c;
+ case "seq":
+ c = slice(c);
+ c[c.length - 1] = negate(c[c.length - 1]);
+ return c;
+ case "conditional":
+ return best_of(not_c, [ "conditional", c[1], negate(c[2]), negate(c[3]) ]);
+ case "binary":
+ var op = c[1], left = c[2], right = c[3];
+ if (!options.keep_comps) switch (op) {
+ case "<=" : return [ "binary", ">", left, right ];
+ case "<" : return [ "binary", ">=", left, right ];
+ case ">=" : return [ "binary", "<", left, right ];
+ case ">" : return [ "binary", "<=", left, right ];
+ }
+ switch (op) {
+ case "==" : return [ "binary", "!=", left, right ];
+ case "!=" : return [ "binary", "==", left, right ];
+ case "===" : return [ "binary", "!==", left, right ];
+ case "!==" : return [ "binary", "===", left, right ];
+ case "&&" : return best_of(not_c, [ "binary", "||", negate(left), negate(right) ]);
+ case "||" : return best_of(not_c, [ "binary", "&&", negate(left), negate(right) ]);
+ }
+ break;
+ }
+ return not_c;
+ };
+
+ function make_conditional(c, t, e) {
+ var make_real_conditional = function() {
+ if (c[0] == "unary-prefix" && c[1] == "!") {
+ return e ? [ "conditional", c[2], e, t ] : [ "binary", "||", c[2], t ];
+ } else {
+ return e ? best_of(
+ [ "conditional", c, t, e ],
+ [ "conditional", negate(c), e, t ]
+ ) : [ "binary", "&&", c, t ];
+ }
+ };
+ // shortcut the conditional if the expression has a constant value
+ return when_constant(c, function(ast, val){
+ warn_unreachable(val ? e : t);
+ return (val ? t : e);
+ }, make_real_conditional);
+ };
+
+ function rmblock(block) {
+ if (block != null && block[0] == "block" && block[1]) {
+ if (block[1].length == 1)
+ block = block[1][0];
+ else if (block[1].length == 0)
+ block = [ "block" ];
+ }
+ return block;
+ };
+
+ function _lambda(name, args, body) {
+ return [ this[0], name, args, tighten(body, "lambda") ];
+ };
+
+ // this function does a few things:
+ // 1. discard useless blocks
+ // 2. join consecutive var declarations
+ // 3. remove obviously dead code
+ // 4. transform consecutive statements using the comma operator
+ // 5. if block_type == "lambda" and it detects constructs like if(foo) return ... - rewrite like if (!foo) { ... }
+ function tighten(statements, block_type) {
+ statements = MAP(statements, walk);
+
+ statements = statements.reduce(function(a, stat){
+ if (stat[0] == "block") {
+ if (stat[1]) {
+ a.push.apply(a, stat[1]);
+ }
+ } else {
+ a.push(stat);
+ }
+ return a;
+ }, []);
+
+ statements = (function(a, prev){
+ statements.forEach(function(cur){
+ if (prev && ((cur[0] == "var" && prev[0] == "var") ||
+ (cur[0] == "const" && prev[0] == "const"))) {
+ prev[1] = prev[1].concat(cur[1]);
+ } else {
+ a.push(cur);
+ prev = cur;
+ }
+ });
+ return a;
+ })([]);
+
+ if (options.dead_code) statements = (function(a, has_quit){
+ statements.forEach(function(st){
+ if (has_quit) {
+ if (st[0] == "function" || st[0] == "defun") {
+ a.push(st);
+ }
+ else if (st[0] == "var" || st[0] == "const") {
+ if (!options.no_warnings)
+ warn("Variables declared in unreachable code");
+ st[1] = MAP(st[1], function(def){
+ if (def[1] && !options.no_warnings)
+ warn_unreachable([ "assign", true, [ "name", def[0] ], def[1] ]);
+ return [ def[0] ];
+ });
+ a.push(st);
+ }
+ else if (!options.no_warnings)
+ warn_unreachable(st);
+ }
+ else {
+ a.push(st);
+ if (member(st[0], [ "return", "throw", "break", "continue" ]))
+ has_quit = true;
+ }
+ });
+ return a;
+ })([]);
+
+ if (options.make_seqs) statements = (function(a, prev) {
+ statements.forEach(function(cur){
+ if (prev && prev[0] == "stat" && cur[0] == "stat") {
+ prev[1] = [ "seq", prev[1], cur[1] ];
+ } else {
+ a.push(cur);
+ prev = cur;
+ }
+ });
+ if (a.length >= 2
+ && a[a.length-2][0] == "stat"
+ && (a[a.length-1][0] == "return" || a[a.length-1][0] == "throw")
+ && a[a.length-1][1])
+ {
+ a.splice(a.length - 2, 2,
+ [ a[a.length-1][0],
+ [ "seq", a[a.length-2][1], a[a.length-1][1] ]]);
+ }
+ return a;
+ })([]);
+
+ // this increases jQuery by 1K. Probably not such a good idea after all..
+ // part of this is done in prepare_ifs anyway.
+ // if (block_type == "lambda") statements = (function(i, a, stat){
+ // while (i < statements.length) {
+ // stat = statements[i++];
+ // if (stat[0] == "if" && !stat[3]) {
+ // if (stat[2][0] == "return" && stat[2][1] == null) {
+ // a.push(make_if(negate(stat[1]), [ "block", statements.slice(i) ]));
+ // break;
+ // }
+ // var last = last_stat(stat[2]);
+ // if (last[0] == "return" && last[1] == null) {
+ // a.push(make_if(stat[1], [ "block", stat[2][1].slice(0, -1) ], [ "block", statements.slice(i) ]));
+ // break;
+ // }
+ // }
+ // a.push(stat);
+ // }
+ // return a;
+ // })(0, []);
+
+ return statements;
+ };
+
+ function make_if(c, t, e) {
+ return when_constant(c, function(ast, val){
+ if (val) {
+ t = walk(t);
+ warn_unreachable(e);
+ return t || [ "block" ];
+ } else {
+ e = walk(e);
+ warn_unreachable(t);
+ return e || [ "block" ];
+ }
+ }, function() {
+ return make_real_if(c, t, e);
+ });
+ };
+
+ function abort_else(c, t, e) {
+ var ret = [ [ "if", negate(c), e ] ];
+ if (t[0] == "block") {
+ if (t[1]) ret = ret.concat(t[1]);
+ } else {
+ ret.push(t);
+ }
+ return walk([ "block", ret ]);
+ };
+
+ function make_real_if(c, t, e) {
+ c = walk(c);
+ t = walk(t);
+ e = walk(e);
+
+ if (empty(t)) {
+ c = negate(c);
+ t = e;
+ e = null;
+ } else if (empty(e)) {
+ e = null;
+ } else {
+ // if we have both else and then, maybe it makes sense to switch them?
+ (function(){
+ var a = gen_code(c);
+ var n = negate(c);
+ var b = gen_code(n);
+ if (b.length < a.length) {
+ var tmp = t;
+ t = e;
+ e = tmp;
+ c = n;
+ }
+ })();
+ }
+ if (empty(e) && empty(t))
+ return [ "stat", c ];
+ var ret = [ "if", c, t, e ];
+ if (t[0] == "if" && empty(t[3]) && empty(e)) {
+ ret = best_of(ret, walk([ "if", [ "binary", "&&", c, t[1] ], t[2] ]));
+ }
+ else if (t[0] == "stat") {
+ if (e) {
+ if (e[0] == "stat")
+ ret = best_of(ret, [ "stat", make_conditional(c, t[1], e[1]) ]);
+ else if (aborts(e))
+ ret = abort_else(c, t, e);
+ }
+ else {
+ ret = best_of(ret, [ "stat", make_conditional(c, t[1]) ]);
+ }
+ }
+ else if (e && t[0] == e[0] && (t[0] == "return" || t[0] == "throw") && t[1] && e[1]) {
+ ret = best_of(ret, [ t[0], make_conditional(c, t[1], e[1] ) ]);
+ }
+ else if (e && aborts(t)) {
+ ret = [ [ "if", c, t ] ];
+ if (e[0] == "block") {
+ if (e[1]) ret = ret.concat(e[1]);
+ }
+ else {
+ ret.push(e);
+ }
+ ret = walk([ "block", ret ]);
+ }
+ else if (t && aborts(e)) {
+ ret = abort_else(c, t, e);
+ }
+ return ret;
+ };
+
+ function _do_while(cond, body) {
+ return when_constant(cond, function(cond, val){
+ if (!val) {
+ warn_unreachable(body);
+ return [ "block" ];
+ } else {
+ return [ "for", null, null, null, walk(body) ];
+ }
+ });
+ };
+
+ return w.with_walkers({
+ "sub": function(expr, subscript) {
+ if (subscript[0] == "string") {
+ var name = subscript[1];
+ if (is_identifier(name))
+ return [ "dot", walk(expr), name ];
+ else if (/^[1-9][0-9]*$/.test(name) || name === "0")
+ return [ "sub", walk(expr), [ "num", parseInt(name, 10) ] ];
+ }
+ },
+ "if": make_if,
+ "toplevel": function(body) {
+ return [ "toplevel", tighten(body) ];
+ },
+ "switch": function(expr, body) {
+ var last = body.length - 1;
+ return [ "switch", walk(expr), MAP(body, function(branch, i){
+ var block = tighten(branch[1]);
+ if (i == last && block.length > 0) {
+ var node = block[block.length - 1];
+ if (node[0] == "break" && !node[1])
+ block.pop();
+ }
+ return [ branch[0] ? walk(branch[0]) : null, block ];
+ }) ];
+ },
+ "function": _lambda,
+ "defun": _lambda,
+ "block": function(body) {
+ if (body) return rmblock([ "block", tighten(body) ]);
+ },
+ "binary": function(op, left, right) {
+ return when_constant([ "binary", op, walk(left), walk(right) ], function yes(c){
+ return best_of(walk(c), this);
+ }, function no() {
+ return function(){
+ if(op != "==" && op != "!=") return;
+ var l = walk(left), r = walk(right);
+ if(l && l[0] == "unary-prefix" && l[1] == "!" && l[2][0] == "num")
+ left = ['num', +!l[2][1]];
+ else if (r && r[0] == "unary-prefix" && r[1] == "!" && r[2][0] == "num")
+ right = ['num', +!r[2][1]];
+ return ["binary", op, left, right];
+ }() || this;
+ });
+ },
+ "conditional": function(c, t, e) {
+ return make_conditional(walk(c), walk(t), walk(e));
+ },
+ "try": function(t, c, f) {
+ return [
+ "try",
+ tighten(t),
+ c != null ? [ c[0], tighten(c[1]) ] : null,
+ f != null ? tighten(f) : null
+ ];
+ },
+ "unary-prefix": function(op, expr) {
+ expr = walk(expr);
+ var ret = [ "unary-prefix", op, expr ];
+ if (op == "!")
+ ret = best_of(ret, negate(expr));
+ return when_constant(ret, function(ast, val){
+ return walk(ast); // it's either true or false, so minifies to !0 or !1
+ }, function() { return ret });
+ },
+ "name": function(name) {
+ switch (name) {
+ case "true": return [ "unary-prefix", "!", [ "num", 0 ]];
+ case "false": return [ "unary-prefix", "!", [ "num", 1 ]];
+ }
+ },
+ "while": _do_while,
+ "assign": function(op, lvalue, rvalue) {
+ lvalue = walk(lvalue);
+ rvalue = walk(rvalue);
+ var okOps = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];
+ if (op === true && lvalue[0] === "name" && rvalue[0] === "binary" &&
+ ~okOps.indexOf(rvalue[1]) && rvalue[2][0] === "name" &&
+ rvalue[2][1] === lvalue[1]) {
+ return [ this[0], rvalue[1], lvalue, rvalue[3] ]
+ }
+ return [ this[0], op, lvalue, rvalue ];
+ }
+ }, function() {
+ for (var i = 0; i < 2; ++i) {
+ ast = prepare_ifs(ast);
+ ast = walk(ast);
+ }
+ return ast;
+ });
+};
+
+/* -----[ re-generate code from the AST ]----- */
+
+var DOT_CALL_NO_PARENS = jsp.array_to_hash([
+ "name",
+ "array",
+ "object",
+ "string",
+ "dot",
+ "sub",
+ "call",
+ "regexp",
+ "defun"
+]);
+
+function make_string(str, ascii_only) {
+ var dq = 0, sq = 0;
+ str = str.replace(/[\\\b\f\n\r\t\x22\x27\u2028\u2029\0]/g, function(s){
+ switch (s) {
+ case "\\": return "\\\\";
+ case "\b": return "\\b";
+ case "\f": return "\\f";
+ case "\n": return "\\n";
+ case "\r": return "\\r";
+ case "\u2028": return "\\u2028";
+ case "\u2029": return "\\u2029";
+ case '"': ++dq; return '"';
+ case "'": ++sq; return "'";
+ case "\0": return "\\0";
+ }
+ return s;
+ });
+ if (ascii_only) str = to_ascii(str);
+ if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'";
+ else return '"' + str.replace(/\x22/g, '\\"') + '"';
+};
+
+function to_ascii(str) {
+ return str.replace(/[\u0080-\uffff]/g, function(ch) {
+ var code = ch.charCodeAt(0).toString(16);
+ while (code.length < 4) code = "0" + code;
+ return "\\u" + code;
+ });
+};
+
+var SPLICE_NEEDS_BRACKETS = jsp.array_to_hash([ "if", "while", "do", "for", "for-in", "with" ]);
+
+function gen_code(ast, options) {
+ options = defaults(options, {
+ indent_start : 0,
+ indent_level : 4,
+ quote_keys : false,
+ space_colon : false,
+ beautify : false,
+ ascii_only : false,
+ inline_script: false
+ });
+ var beautify = !!options.beautify;
+ var indentation = 0,
+ newline = beautify ? "\n" : "",
+ space = beautify ? " " : "";
+
+ function encode_string(str) {
+ var ret = make_string(str, options.ascii_only);
+ if (options.inline_script)
+ ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1");
+ return ret;
+ };
+
+ function make_name(name) {
+ name = name.toString();
+ if (options.ascii_only)
+ name = to_ascii(name);
+ return name;
+ };
+
+ function indent(line) {
+ if (line == null)
+ line = "";
+ if (beautify)
+ line = repeat_string(" ", options.indent_start + indentation * options.indent_level) + line;
+ return line;
+ };
+
+ function with_indent(cont, incr) {
+ if (incr == null) incr = 1;
+ indentation += incr;
+ try { return cont.apply(null, slice(arguments, 1)); }
+ finally { indentation -= incr; }
+ };
+
+ function add_spaces(a) {
+ if (beautify)
+ return a.join(" ");
+ var b = [];
+ for (var i = 0; i < a.length; ++i) {
+ var next = a[i + 1];
+ b.push(a[i]);
+ if (next &&
+ ((/[a-z0-9_\x24]$/i.test(a[i].toString()) && /^[a-z0-9_\x24]/i.test(next.toString())) ||
+ (/[\+\-]$/.test(a[i].toString()) && /^[\+\-]/.test(next.toString())))) {
+ b.push(" ");
+ }
+ }
+ return b.join("");
+ };
+
+ function add_commas(a) {
+ return a.join("," + space);
+ };
+
+ function parenthesize(expr) {
+ var gen = make(expr);
+ for (var i = 1; i < arguments.length; ++i) {
+ var el = arguments[i];
+ if ((el instanceof Function && el(expr)) || expr[0] == el)
+ return "(" + gen + ")";
+ }
+ return gen;
+ };
+
+ function best_of(a) {
+ if (a.length == 1) {
+ return a[0];
+ }
+ if (a.length == 2) {
+ var b = a[1];
+ a = a[0];
+ return a.length <= b.length ? a : b;
+ }
+ return best_of([ a[0], best_of(a.slice(1)) ]);
+ };
+
+ function needs_parens(expr) {
+ if (expr[0] == "function" || expr[0] == "object") {
+ // dot/call on a literal function requires the
+ // function literal itself to be parenthesized
+ // only if it's the first "thing" in a
+ // statement. This means that the parent is
+ // "stat", but it could also be a "seq" and
+ // we're the first in this "seq" and the
+ // parent is "stat", and so on. Messy stuff,
+ // but it worths the trouble.
+ var a = slice(w.stack()), self = a.pop(), p = a.pop();
+ while (p) {
+ if (p[0] == "stat") return true;
+ if (((p[0] == "seq" || p[0] == "call" || p[0] == "dot" || p[0] == "sub" || p[0] == "conditional") && p[1] === self) ||
+ ((p[0] == "binary" || p[0] == "assign" || p[0] == "unary-postfix") && p[2] === self)) {
+ self = p;
+ p = a.pop();
+ } else {
+ return false;
+ }
+ }
+ }
+ return !HOP(DOT_CALL_NO_PARENS, expr[0]);
+ };
+
+ function make_num(num) {
+ var str = num.toString(10), a = [ str.replace(/^0\./, ".") ], m;
+ if (Math.floor(num) === num) {
+ if (num >= 0) {
+ a.push("0x" + num.toString(16).toLowerCase(), // probably pointless
+ "0" + num.toString(8)); // same.
+ } else {
+ a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless
+ "-0" + (-num).toString(8)); // same.
+ }
+ if ((m = /^(.*?)(0+)$/.exec(num))) {
+ a.push(m[1] + "e" + m[2].length);
+ }
+ } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) {
+ a.push(m[2] + "e-" + (m[1].length + m[2].length),
+ str.substr(str.indexOf(".")));
+ }
+ return best_of(a);
+ };
+
+ var w = ast_walker();
+ var make = w.walk;
+ return w.with_walkers({
+ "string": encode_string,
+ "num": make_num,
+ "name": make_name,
+ "debugger": function(){ return "debugger" },
+ "toplevel": function(statements) {
+ return make_block_statements(statements)
+ .join(newline + newline);
+ },
+ "splice": function(statements) {
+ var parent = w.parent();
+ if (HOP(SPLICE_NEEDS_BRACKETS, parent)) {
+ // we need block brackets in this case
+ return make_block.apply(this, arguments);
+ } else {
+ return MAP(make_block_statements(statements, true),
+ function(line, i) {
+ // the first line is already indented
+ return i > 0 ? indent(line) : line;
+ }).join(newline);
+ }
+ },
+ "block": make_block,
+ "var": function(defs) {
+ return "var " + add_commas(MAP(defs, make_1vardef)) + ";";
+ },
+ "const": function(defs) {
+ return "const " + add_commas(MAP(defs, make_1vardef)) + ";";
+ },
+ "try": function(tr, ca, fi) {
+ var out = [ "try", make_block(tr) ];
+ if (ca) out.push("catch", "(" + ca[0] + ")", make_block(ca[1]));
+ if (fi) out.push("finally", make_block(fi));
+ return add_spaces(out);
+ },
+ "throw": function(expr) {
+ return add_spaces([ "throw", make(expr) ]) + ";";
+ },
+ "new": function(ctor, args) {
+ args = args.length > 0 ? "(" + add_commas(MAP(args, function(expr){
+ return parenthesize(expr, "seq");
+ })) + ")" : "";
+ return add_spaces([ "new", parenthesize(ctor, "seq", "binary", "conditional", "assign", function(expr){
+ var w = ast_walker(), has_call = {};
+ try {
+ w.with_walkers({
+ "call": function() { throw has_call },
+ "function": function() { return this }
+ }, function(){
+ w.walk(expr);
+ });
+ } catch(ex) {
+ if (ex === has_call)
+ return true;
+ throw ex;
+ }
+ }) + args ]);
+ },
+ "switch": function(expr, body) {
+ return add_spaces([ "switch", "(" + make(expr) + ")", make_switch_block(body) ]);
+ },
+ "break": function(label) {
+ var out = "break";
+ if (label != null)
+ out += " " + make_name(label);
+ return out + ";";
+ },
+ "continue": function(label) {
+ var out = "continue";
+ if (label != null)
+ out += " " + make_name(label);
+ return out + ";";
+ },
+ "conditional": function(co, th, el) {
+ return add_spaces([ parenthesize(co, "assign", "seq", "conditional"), "?",
+ parenthesize(th, "seq"), ":",
+ parenthesize(el, "seq") ]);
+ },
+ "assign": function(op, lvalue, rvalue) {
+ if (op && op !== true) op += "=";
+ else op = "=";
+ return add_spaces([ make(lvalue), op, parenthesize(rvalue, "seq") ]);
+ },
+ "dot": function(expr) {
+ var out = make(expr), i = 1;
+ if (expr[0] == "num") {
+ if (!/\./.test(expr[1]))
+ out += ".";
+ } else if (expr[0] != "function" && needs_parens(expr))
+ out = "(" + out + ")";
+ while (i < arguments.length)
+ out += "." + make_name(arguments[i++]);
+ return out;
+ },
+ "call": function(func, args) {
+ var f = make(func);
+ if (f.charAt(0) != "(" && needs_parens(func))
+ f = "(" + f + ")";
+ return f + "(" + add_commas(MAP(args, function(expr){
+ return parenthesize(expr, "seq");
+ })) + ")";
+ },
+ "function": make_function,
+ "defun": make_function,
+ "if": function(co, th, el) {
+ var out = [ "if", "(" + make(co) + ")", el ? make_then(th) : make(th) ];
+ if (el) {
+ out.push("else", make(el));
+ }
+ return add_spaces(out);
+ },
+ "for": function(init, cond, step, block) {
+ var out = [ "for" ];
+ init = (init != null ? make(init) : "").replace(/;*\s*$/, ";" + space);
+ cond = (cond != null ? make(cond) : "").replace(/;*\s*$/, ";" + space);
+ step = (step != null ? make(step) : "").replace(/;*\s*$/, "");
+ var args = init + cond + step;
+ if (args == "; ; ") args = ";;";
+ out.push("(" + args + ")", make(block));
+ return add_spaces(out);
+ },
+ "for-in": function(vvar, key, hash, block) {
+ return add_spaces([ "for", "(" +
+ (vvar ? make(vvar).replace(/;+$/, "") : make(key)),
+ "in",
+ make(hash) + ")", make(block) ]);
+ },
+ "while": function(condition, block) {
+ return add_spaces([ "while", "(" + make(condition) + ")", make(block) ]);
+ },
+ "do": function(condition, block) {
+ return add_spaces([ "do", make(block), "while", "(" + make(condition) + ")" ]) + ";";
+ },
+ "return": function(expr) {
+ var out = [ "return" ];
+ if (expr != null) out.push(make(expr));
+ return add_spaces(out) + ";";
+ },
+ "binary": function(operator, lvalue, rvalue) {
+ var left = make(lvalue), right = make(rvalue);
+ // XXX: I'm pretty sure other cases will bite here.
+ // we need to be smarter.
+ // adding parens all the time is the safest bet.
+ if (member(lvalue[0], [ "assign", "conditional", "seq" ]) ||
+ lvalue[0] == "binary" && PRECEDENCE[operator] > PRECEDENCE[lvalue[1]] ||
+ lvalue[0] == "function" && needs_parens(this)) {
+ left = "(" + left + ")";
+ }
+ if (member(rvalue[0], [ "assign", "conditional", "seq" ]) ||
+ rvalue[0] == "binary" && PRECEDENCE[operator] >= PRECEDENCE[rvalue[1]] &&
+ !(rvalue[1] == operator && member(operator, [ "&&", "||", "*" ]))) {
+ right = "(" + right + ")";
+ }
+ else if (!beautify && options.inline_script && (operator == "<" || operator == "<<")
+ && rvalue[0] == "regexp" && /^script/i.test(rvalue[1])) {
+ right = " " + right;
+ }
+ return add_spaces([ left, operator, right ]);
+ },
+ "unary-prefix": function(operator, expr) {
+ var val = make(expr);
+ if (!(expr[0] == "num" || (expr[0] == "unary-prefix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
+ val = "(" + val + ")";
+ return operator + (jsp.is_alphanumeric_char(operator.charAt(0)) ? " " : "") + val;
+ },
+ "unary-postfix": function(operator, expr) {
+ var val = make(expr);
+ if (!(expr[0] == "num" || (expr[0] == "unary-postfix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
+ val = "(" + val + ")";
+ return val + operator;
+ },
+ "sub": function(expr, subscript) {
+ var hash = make(expr);
+ if (needs_parens(expr))
+ hash = "(" + hash + ")";
+ return hash + "[" + make(subscript) + "]";
+ },
+ "object": function(props) {
+ var obj_needs_parens = needs_parens(this);
+ if (props.length == 0)
+ return obj_needs_parens ? "({})" : "{}";
+ var out = "{" + newline + with_indent(function(){
+ return MAP(props, function(p){
+ if (p.length == 3) {
+ // getter/setter. The name is in p[0], the arg.list in p[1][2], the
+ // body in p[1][3] and type ("get" / "set") in p[2].
+ return indent(make_function(p[0], p[1][2], p[1][3], p[2], true));
+ }
+ var key = p[0], val = parenthesize(p[1], "seq");
+ if (options.quote_keys) {
+ key = encode_string(key);
+ } else if ((typeof key == "number" || !beautify && +key + "" == key)
+ && parseFloat(key) >= 0) {
+ key = make_num(+key);
+ } else if (!is_identifier(key)) {
+ key = encode_string(key);
+ }
+ return indent(add_spaces(beautify && options.space_colon
+ ? [ key, ":", val ]
+ : [ key + ":", val ]));
+ }).join("," + newline);
+ }) + newline + indent("}");
+ return obj_needs_parens ? "(" + out + ")" : out;
+ },
+ "regexp": function(rx, mods) {
+ return "/" + rx + "/" + mods;
+ },
+ "array": function(elements) {
+ if (elements.length == 0) return "[]";
+ return add_spaces([ "[", add_commas(MAP(elements, function(el, i){
+ if (!beautify && el[0] == "atom" && el[1] == "undefined") return i === elements.length - 1 ? "," : "";
+ return parenthesize(el, "seq");
+ })), "]" ]);
+ },
+ "stat": function(stmt) {
+ return make(stmt).replace(/;*\s*$/, ";");
+ },
+ "seq": function() {
+ return add_commas(MAP(slice(arguments), make));
+ },
+ "label": function(name, block) {
+ return add_spaces([ make_name(name), ":", make(block) ]);
+ },
+ "with": function(expr, block) {
+ return add_spaces([ "with", "(" + make(expr) + ")", make(block) ]);
+ },
+ "atom": function(name) {
+ return make_name(name);
+ }
+ }, function(){ return make(ast) });
+
+ // The squeezer replaces "block"-s that contain only a single
+ // statement with the statement itself; technically, the AST
+ // is correct, but this can create problems when we output an
+ // IF having an ELSE clause where the THEN clause ends in an
+ // IF *without* an ELSE block (then the outer ELSE would refer
+ // to the inner IF). This function checks for this case and
+ // adds the block brackets if needed.
+ function make_then(th) {
+ if (th == null) return ";";
+ if (th[0] == "do") {
+ // https://github.com/mishoo/UglifyJS/issues/#issue/57
+ // IE croaks with "syntax error" on code like this:
+ // if (foo) do ... while(cond); else ...
+ // we need block brackets around do/while
+ return make_block([ th ]);
+ }
+ var b = th;
+ while (true) {
+ var type = b[0];
+ if (type == "if") {
+ if (!b[3])
+ // no else, we must add the block
+ return make([ "block", [ th ]]);
+ b = b[3];
+ }
+ else if (type == "while" || type == "do") b = b[2];
+ else if (type == "for" || type == "for-in") b = b[4];
+ else break;
+ }
+ return make(th);
+ };
+
+ function make_function(name, args, body, keyword, no_parens) {
+ var out = keyword || "function";
+ if (name) {
+ out += " " + make_name(name);
+ }
+ out += "(" + add_commas(MAP(args, make_name)) + ")";
+ out = add_spaces([ out, make_block(body) ]);
+ return (!no_parens && needs_parens(this)) ? "(" + out + ")" : out;
+ };
+
+ function must_has_semicolon(node) {
+ switch (node[0]) {
+ case "with":
+ case "while":
+ return empty(node[2]); // `with' or `while' with empty body?
+ case "for":
+ case "for-in":
+ return empty(node[4]); // `for' with empty body?
+ case "if":
+ if (empty(node[2]) && !node[3]) return true; // `if' with empty `then' and no `else'
+ if (node[3]) {
+ if (empty(node[3])) return true; // `else' present but empty
+ return must_has_semicolon(node[3]); // dive into the `else' branch
+ }
+ return must_has_semicolon(node[2]); // dive into the `then' branch
+ }
+ };
+
+ function make_block_statements(statements, noindent) {
+ for (var a = [], last = statements.length - 1, i = 0; i <= last; ++i) {
+ var stat = statements[i];
+ var code = make(stat);
+ if (code != ";") {
+ if (!beautify && i == last && !must_has_semicolon(stat)) {
+ code = code.replace(/;+\s*$/, "");
+ }
+ a.push(code);
+ }
+ }
+ return noindent ? a : MAP(a, indent);
+ };
+
+ function make_switch_block(body) {
+ var n = body.length;
+ if (n == 0) return "{}";
+ return "{" + newline + MAP(body, function(branch, i){
+ var has_body = branch[1].length > 0, code = with_indent(function(){
+ return indent(branch[0]
+ ? add_spaces([ "case", make(branch[0]) + ":" ])
+ : "default:");
+ }, 0.5) + (has_body ? newline + with_indent(function(){
+ return make_block_statements(branch[1]).join(newline);
+ }) : "");
+ if (!beautify && has_body && i < n - 1)
+ code += ";";
+ return code;
+ }).join(newline) + newline + indent("}");
+ };
+
+ function make_block(statements) {
+ if (!statements) return ";";
+ if (statements.length == 0) return "{}";
+ return "{" + newline + with_indent(function(){
+ return make_block_statements(statements).join(newline);
+ }) + newline + indent("}");
+ };
+
+ function make_1vardef(def) {
+ var name = def[0], val = def[1];
+ if (val != null)
+ name = add_spaces([ make_name(name), "=", parenthesize(val, "seq") ]);
+ return name;
+ };
+
+};
+
+function split_lines(code, max_line_length) {
+ var splits = [ 0 ];
+ jsp.parse(function(){
+ var next_token = jsp.tokenizer(code);
+ var last_split = 0;
+ var prev_token;
+ function current_length(tok) {
+ return tok.pos - last_split;
+ };
+ function split_here(tok) {
+ last_split = tok.pos;
+ splits.push(last_split);
+ };
+ function custom(){
+ var tok = next_token.apply(this, arguments);
+ out: {
+ if (prev_token) {
+ if (prev_token.type == "keyword") break out;
+ }
+ if (current_length(tok) > max_line_length) {
+ switch (tok.type) {
+ case "keyword":
+ case "atom":
+ case "name":
+ case "punc":
+ split_here(tok);
+ break out;
+ }
+ }
+ }
+ prev_token = tok;
+ return tok;
+ };
+ custom.context = function() {
+ return next_token.context.apply(this, arguments);
+ };
+ return custom;
+ }());
+ return splits.map(function(pos, i){
+ return code.substring(pos, splits[i + 1] || code.length);
+ }).join("\n");
+};
+
+/* -----[ Utilities ]----- */
+
+function repeat_string(str, i) {
+ if (i <= 0) return "";
+ if (i == 1) return str;
+ var d = repeat_string(str, i >> 1);
+ d += d;
+ if (i & 1) d += str;
+ return d;
+};
+
+function defaults(args, defs) {
+ var ret = {};
+ if (args === true)
+ args = {};
+ for (var i in defs) if (HOP(defs, i)) {
+ ret[i] = (args && HOP(args, i)) ? args[i] : defs[i];
+ }
+ return ret;
+};
+
+function is_identifier(name) {
+ return /^[a-z_$][a-z0-9_$]*$/i.test(name)
+ && name != "this"
+ && !HOP(jsp.KEYWORDS_ATOM, name)
+ && !HOP(jsp.RESERVED_WORDS, name)
+ && !HOP(jsp.KEYWORDS, name);
+};
+
+function HOP(obj, prop) {
+ return Object.prototype.hasOwnProperty.call(obj, prop);
+};
+
+// some utilities
+
+var MAP;
+
+(function(){
+ MAP = function(a, f, o) {
+ var ret = [], top = [], i;
+ function doit() {
+ var val = f.call(o, a[i], i);
+ if (val instanceof AtTop) {
+ val = val.v;
+ if (val instanceof Splice) {
+ top.push.apply(top, val.v);
+ } else {
+ top.push(val);
+ }
+ }
+ else if (val != skip) {
+ if (val instanceof Splice) {
+ ret.push.apply(ret, val.v);
+ } else {
+ ret.push(val);
+ }
+ }
+ };
+ if (a instanceof Array) for (i = 0; i < a.length; ++i) doit();
+ else for (i in a) if (HOP(a, i)) doit();
+ return top.concat(ret);
+ };
+ MAP.at_top = function(val) { return new AtTop(val) };
+ MAP.splice = function(val) { return new Splice(val) };
+ var skip = MAP.skip = {};
+ function AtTop(val) { this.v = val };
+ function Splice(val) { this.v = val };
+})();
+
+/* -----[ Exports ]----- */
+
+exports.ast_walker = ast_walker;
+exports.ast_mangle = ast_mangle;
+exports.ast_squeeze = ast_squeeze;
+exports.ast_lift_variables = ast_lift_variables;
+exports.gen_code = gen_code;
+exports.ast_add_scope = ast_add_scope;
+exports.set_logger = function(logger) { warn = logger };
+exports.make_string = make_string;
+exports.split_lines = split_lines;
+exports.MAP = MAP;
+
+// keep this last!
+exports.ast_squeeze_more = require("./squeeze-more").ast_squeeze_more;
diff --git a/node_modules/handlebars/node_modules/uglify-js/lib/squeeze-more.js b/node_modules/handlebars/node_modules/uglify-js/lib/squeeze-more.js
new file mode 100644
index 0000000000..0908db3eee
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/lib/squeeze-more.js
@@ -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;
diff --git a/node_modules/handlebars/node_modules/uglify-js/package.json b/node_modules/handlebars/node_modules/uglify-js/package.json
new file mode 100644
index 0000000000..978a466484
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/package.json
@@ -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"
+}
diff --git a/node_modules/handlebars/node_modules/uglify-js/test/beautify.js b/node_modules/handlebars/node_modules/uglify-js/test/beautify.js
new file mode 100755
index 0000000000..f19369e3a1
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/test/beautify.js
@@ -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."); }
+};
diff --git a/node_modules/handlebars/node_modules/uglify-js/test/testparser.js b/node_modules/handlebars/node_modules/uglify-js/test/testparser.js
new file mode 100755
index 0000000000..02c19a9c98
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/test/testparser.js
@@ -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�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"],
+ ["xy;", "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>>= 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> 1;
+var c = 8 >>> 1;
\ No newline at end of file
diff --git a/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue34.js b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue34.js
new file mode 100644
index 0000000000..022f7a31b6
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue34.js
@@ -0,0 +1,3 @@
+var a = {};
+a["this"] = 1;
+a["that"] = 2;
\ No newline at end of file
diff --git a/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue4.js b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue4.js
new file mode 100644
index 0000000000..0b76103792
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue4.js
@@ -0,0 +1,3 @@
+var a = 2e3;
+var b = 2e-3;
+var c = 2e-5;
\ No newline at end of file
diff --git a/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue48.js b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue48.js
new file mode 100644
index 0000000000..031e85b39c
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue48.js
@@ -0,0 +1 @@
+var s, i; s = ''; i = 0;
\ No newline at end of file
diff --git a/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue50.js b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue50.js
new file mode 100644
index 0000000000..060f9df82f
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue50.js
@@ -0,0 +1,9 @@
+function bar(a) {
+ try {
+ foo();
+ } catch(e) {
+ alert("Exception caught (foo not defined)");
+ }
+ alert(a); // 10 in FF, "[object Error]" in IE
+}
+bar(10);
diff --git a/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue53.js b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue53.js
new file mode 100644
index 0000000000..4f8b32f11f
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue53.js
@@ -0,0 +1 @@
+x = (y, z)
diff --git a/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue54.1.js b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue54.1.js
new file mode 100644
index 0000000000..967052e857
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue54.1.js
@@ -0,0 +1,3 @@
+foo.toString();
+a.toString(16);
+b.toString.call(c);
diff --git a/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue68.js b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue68.js
new file mode 100644
index 0000000000..14054d01e2
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue68.js
@@ -0,0 +1,5 @@
+function f() {
+ if (a) return;
+ g();
+ function g(){}
+};
diff --git a/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue69.js b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue69.js
new file mode 100644
index 0000000000..d25ecd671e
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue69.js
@@ -0,0 +1 @@
+[(a,b)]
diff --git a/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue9.js b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue9.js
new file mode 100644
index 0000000000..61588614b8
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/issue9.js
@@ -0,0 +1,4 @@
+var a = {
+ a: 1,
+ b: 2, // <-- trailing comma
+};
diff --git a/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/mangle.js b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/mangle.js
new file mode 100644
index 0000000000..c271a26dc5
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/mangle.js
@@ -0,0 +1,5 @@
+(function() {
+ var x = function fun(a, fun, b) {
+ return fun;
+ };
+}());
diff --git a/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/null_string.js b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/null_string.js
new file mode 100644
index 0000000000..a675b1c5cc
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/null_string.js
@@ -0,0 +1 @@
+var nullString = "\0"
\ No newline at end of file
diff --git a/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/strict-equals.js b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/strict-equals.js
new file mode 100644
index 0000000000..b631f4c350
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/strict-equals.js
@@ -0,0 +1,3 @@
+typeof a === 'string'
+b + "" !== c + ""
+d < e === f < g
diff --git a/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/var.js b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/var.js
new file mode 100644
index 0000000000..609a35d2a2
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/var.js
@@ -0,0 +1,3 @@
+// var declarations after each other should be combined
+var a = 1;
+var b = 2;
\ No newline at end of file
diff --git a/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/whitespace.js b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/whitespace.js
new file mode 100644
index 0000000000..6a15c464fb
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/whitespace.js
@@ -0,0 +1,21 @@
+function id(a) {
+ // Form-Feed
+ // Vertical Tab
+ // No-Break Space
+ // Mongolian Vowel Separator
+ // En quad
+ // Em quad
+ // En space
+ // Em space
+ // Three-Per-Em Space
+ // Four-Per-Em Space
+ // Six-Per-Em Space
+ // Figure Space
+ // Punctuation Space
+ // Thin Space
+ // Hair Space
+ // Narrow No-Break Space
+ // Medium Mathematical Space
+ // Ideographic Space
+ return a;
+}
diff --git a/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/with.js b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/with.js
new file mode 100644
index 0000000000..de266ed547
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/test/unit/compress/test/with.js
@@ -0,0 +1,2 @@
+with({}) {
+};
diff --git a/node_modules/handlebars/node_modules/uglify-js/test/unit/scripts.js b/node_modules/handlebars/node_modules/uglify-js/test/unit/scripts.js
new file mode 100644
index 0000000000..5d334ff76a
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/test/unit/scripts.js
@@ -0,0 +1,55 @@
+var fs = require('fs'),
+ uglify = require('../../uglify-js'),
+ jsp = uglify.parser,
+ nodeunit = require('nodeunit'),
+ path = require('path'),
+ pro = uglify.uglify;
+
+var Script = process.binding('evals').Script;
+
+var scriptsPath = __dirname;
+
+function compress(code) {
+ var ast = jsp.parse(code);
+ ast = pro.ast_mangle(ast);
+ ast = pro.ast_squeeze(ast, { no_warnings: true });
+ ast = pro.ast_squeeze_more(ast);
+ return pro.gen_code(ast);
+};
+
+var testDir = path.join(scriptsPath, "compress", "test");
+var expectedDir = path.join(scriptsPath, "compress", "expected");
+
+function getTester(script) {
+ return function(test) {
+ var testPath = path.join(testDir, script);
+ var expectedPath = path.join(expectedDir, script);
+ var content = fs.readFileSync(testPath, 'utf-8');
+ var outputCompress = compress(content);
+
+ // Check if the noncompressdata is larger or same size as the compressed data
+ test.ok(content.length >= outputCompress.length);
+
+ // Check that a recompress gives the same result
+ var outputReCompress = compress(content);
+ test.equal(outputCompress, outputReCompress);
+
+ // Check if the compressed output is what is expected
+ var expected = fs.readFileSync(expectedPath, 'utf-8');
+ test.equal(outputCompress, expected.replace(/(\r?\n)+$/, ""));
+
+ test.done();
+ };
+};
+
+var tests = {};
+
+var scripts = fs.readdirSync(testDir);
+for (var i in scripts) {
+ var script = scripts[i];
+ if (/\.js$/.test(script)) {
+ tests[script] = getTester(script);
+ }
+}
+
+module.exports = nodeunit.testCase(tests);
diff --git a/node_modules/handlebars/node_modules/uglify-js/tmp/269.js b/node_modules/handlebars/node_modules/uglify-js/tmp/269.js
new file mode 100644
index 0000000000..256ad1c939
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/tmp/269.js
@@ -0,0 +1,13 @@
+var jsp = require("uglify-js").parser;
+var pro = require("uglify-js").uglify;
+
+var test_code = "var JSON;JSON||(JSON={});";
+
+var ast = jsp.parse(test_code, false, false);
+var nonembed_token_code = pro.gen_code(ast);
+ast = jsp.parse(test_code, false, true);
+var embed_token_code = pro.gen_code(ast);
+
+console.log("original: " + test_code);
+console.log("no token: " + nonembed_token_code);
+console.log(" token: " + embed_token_code);
diff --git a/node_modules/handlebars/node_modules/uglify-js/tmp/app.js b/node_modules/handlebars/node_modules/uglify-js/tmp/app.js
new file mode 100644
index 0000000000..2c6257eb37
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/tmp/app.js
@@ -0,0 +1,22315 @@
+/* Modernizr 2.0.6 (Custom Build) | MIT & BSD
+ * Build: http://www.modernizr.com/download/#-iepp
+ */
+;window.Modernizr=function(a,b,c){function w(a,b){return!!~(""+a).indexOf(b)}function v(a,b){return typeof a===b}function u(a,b){return t(prefixes.join(a+";")+(b||""))}function t(a){j.cssText=a}var d="2.0.6",e={},f=b.documentElement,g=b.head||b.getElementsByTagName("head")[0],h="modernizr",i=b.createElement(h),j=i.style,k,l=Object.prototype.toString,m={},n={},o={},p=[],q,r={}.hasOwnProperty,s;!v(r,c)&&!v(r.call,c)?s=function(a,b){return r.call(a,b)}:s=function(a,b){return b in a&&v(a.constructor.prototype[b],c)};for(var x in m)s(m,x)&&(q=x.toLowerCase(),e[q]=m[x](),p.push((e[q]?"":"no-")+q));t(""),i=k=null,a.attachEvent&&function(){var a=b.createElement("div");a.innerHTML="";return a.childNodes.length!==1}()&&function(a,b){function s(a){var b=-1;while(++b to avoid XSS via location.hash (#9521)
+ quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
+
+ // Check if a string has a non-whitespace character in it
+ rnotwhite = /\S/,
+
+ // Used for trimming whitespace
+ trimLeft = /^\s+/,
+ trimRight = /\s+$/,
+
+ // Check for digits
+ rdigit = /\d/,
+
+ // Match a standalone tag
+ rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
+
+ // JSON RegExp
+ rvalidchars = /^[\],:{}\s]*$/,
+ rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
+ rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
+ rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
+
+ // Useragent RegExp
+ rwebkit = /(webkit)[ \/]([\w.]+)/,
+ ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
+ rmsie = /(msie) ([\w.]+)/,
+ rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
+
+ // Matches dashed string for camelizing
+ rdashAlpha = /-([a-z]|[0-9])/ig,
+ rmsPrefix = /^-ms-/,
+
+ // Used by jQuery.camelCase as callback to replace()
+ fcamelCase = function( all, letter ) {
+ return ( letter + "" ).toUpperCase();
+ },
+
+ // Keep a UserAgent string for use with jQuery.browser
+ userAgent = navigator.userAgent,
+
+ // For matching the engine and version of the browser
+ browserMatch,
+
+ // The deferred used on DOM ready
+ readyList,
+
+ // The ready event handler
+ DOMContentLoaded,
+
+ // Save a reference to some core methods
+ toString = Object.prototype.toString,
+ hasOwn = Object.prototype.hasOwnProperty,
+ push = Array.prototype.push,
+ slice = Array.prototype.slice,
+ trim = String.prototype.trim,
+ indexOf = Array.prototype.indexOf,
+
+ // [[Class]] -> type pairs
+ class2type = {};
+
+jQuery.fn = jQuery.prototype = {
+ constructor: jQuery,
+ init: function( selector, context, rootjQuery ) {
+ var match, elem, ret, doc;
+
+ // Handle $(""), $(null), or $(undefined)
+ if ( !selector ) {
+ return this;
+ }
+
+ // Handle $(DOMElement)
+ if ( selector.nodeType ) {
+ this.context = this[0] = selector;
+ this.length = 1;
+ return this;
+ }
+
+ // The body element only exists once, optimize finding it
+ if ( selector === "body" && !context && document.body ) {
+ this.context = document;
+ this[0] = document.body;
+ this.selector = selector;
+ this.length = 1;
+ return this;
+ }
+
+ // Handle HTML strings
+ if ( typeof selector === "string" ) {
+ // Are we dealing with HTML string or an ID?
+ if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
+ // Assume that strings that start and end with <> are HTML and skip the regex check
+ match = [ null, selector, null ];
+
+ } else {
+ match = quickExpr.exec( selector );
+ }
+
+ // Verify a match, and that no context was specified for #id
+ if ( match && (match[1] || !context) ) {
+
+ // HANDLE: $(html) -> $(array)
+ if ( match[1] ) {
+ context = context instanceof jQuery ? context[0] : context;
+ doc = (context ? context.ownerDocument || context : document);
+
+ // If a single string is passed in and it's a single tag
+ // just do a createElement and skip the rest
+ ret = rsingleTag.exec( selector );
+
+ if ( ret ) {
+ if ( jQuery.isPlainObject( context ) ) {
+ selector = [ document.createElement( ret[1] ) ];
+ jQuery.fn.attr.call( selector, context, true );
+
+ } else {
+ selector = [ doc.createElement( ret[1] ) ];
+ }
+
+ } else {
+ ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
+ selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
+ }
+
+ return jQuery.merge( this, selector );
+
+ // HANDLE: $("#id")
+ } else {
+ elem = document.getElementById( match[2] );
+
+ // Check parentNode to catch when Blackberry 4.6 returns
+ // nodes that are no longer in the document #6963
+ if ( elem && elem.parentNode ) {
+ // Handle the case where IE and Opera return items
+ // by name instead of ID
+ if ( elem.id !== match[2] ) {
+ return rootjQuery.find( selector );
+ }
+
+ // Otherwise, we inject the element directly into the jQuery object
+ this.length = 1;
+ this[0] = elem;
+ }
+
+ this.context = document;
+ this.selector = selector;
+ return this;
+ }
+
+ // HANDLE: $(expr, $(...))
+ } else if ( !context || context.jquery ) {
+ return (context || rootjQuery).find( selector );
+
+ // HANDLE: $(expr, context)
+ // (which is just equivalent to: $(context).find(expr)
+ } else {
+ return this.constructor( context ).find( selector );
+ }
+
+ // HANDLE: $(function)
+ // Shortcut for document ready
+ } else if ( jQuery.isFunction( selector ) ) {
+ return rootjQuery.ready( selector );
+ }
+
+ if (selector.selector !== undefined) {
+ this.selector = selector.selector;
+ this.context = selector.context;
+ }
+
+ return jQuery.makeArray( selector, this );
+ },
+
+ // Start with an empty selector
+ selector: "",
+
+ // The current version of jQuery being used
+ jquery: "1.6.3",
+
+ // The default length of a jQuery object is 0
+ length: 0,
+
+ // The number of elements contained in the matched element set
+ size: function() {
+ return this.length;
+ },
+
+ toArray: function() {
+ return slice.call( this, 0 );
+ },
+
+ // Get the Nth element in the matched element set OR
+ // Get the whole matched element set as a clean array
+ get: function( num ) {
+ return num == null ?
+
+ // Return a 'clean' array
+ this.toArray() :
+
+ // Return just the object
+ ( num < 0 ? this[ this.length + num ] : this[ num ] );
+ },
+
+ // Take an array of elements and push it onto the stack
+ // (returning the new matched element set)
+ pushStack: function( elems, name, selector ) {
+ // Build a new jQuery matched element set
+ var ret = this.constructor();
+
+ if ( jQuery.isArray( elems ) ) {
+ push.apply( ret, elems );
+
+ } else {
+ jQuery.merge( ret, elems );
+ }
+
+ // Add the old object onto the stack (as a reference)
+ ret.prevObject = this;
+
+ ret.context = this.context;
+
+ if ( name === "find" ) {
+ ret.selector = this.selector + (this.selector ? " " : "") + selector;
+ } else if ( name ) {
+ ret.selector = this.selector + "." + name + "(" + selector + ")";
+ }
+
+ // Return the newly-formed element set
+ return ret;
+ },
+
+ // Execute a callback for every element in the matched set.
+ // (You can seed the arguments with an array of args, but this is
+ // only used internally.)
+ each: function( callback, args ) {
+ return jQuery.each( this, callback, args );
+ },
+
+ ready: function( fn ) {
+ // Attach the listeners
+ jQuery.bindReady();
+
+ // Add the callback
+ readyList.done( fn );
+
+ return this;
+ },
+
+ eq: function( i ) {
+ return i === -1 ?
+ this.slice( i ) :
+ this.slice( i, +i + 1 );
+ },
+
+ first: function() {
+ return this.eq( 0 );
+ },
+
+ last: function() {
+ return this.eq( -1 );
+ },
+
+ slice: function() {
+ return this.pushStack( slice.apply( this, arguments ),
+ "slice", slice.call(arguments).join(",") );
+ },
+
+ map: function( callback ) {
+ return this.pushStack( jQuery.map(this, function( elem, i ) {
+ return callback.call( elem, i, elem );
+ }));
+ },
+
+ end: function() {
+ return this.prevObject || this.constructor(null);
+ },
+
+ // For internal use only.
+ // Behaves like an Array's method, not like a jQuery method.
+ push: push,
+ sort: [].sort,
+ splice: [].splice
+};
+
+// Give the init function the jQuery prototype for later instantiation
+jQuery.fn.init.prototype = jQuery.fn;
+
+jQuery.extend = jQuery.fn.extend = function() {
+ var options, name, src, copy, copyIsArray, clone,
+ target = arguments[0] || {},
+ i = 1,
+ length = arguments.length,
+ deep = false;
+
+ // Handle a deep copy situation
+ if ( typeof target === "boolean" ) {
+ deep = target;
+ target = arguments[1] || {};
+ // skip the boolean and the target
+ i = 2;
+ }
+
+ // Handle case when target is a string or something (possible in deep copy)
+ if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
+ target = {};
+ }
+
+ // extend jQuery itself if only one argument is passed
+ if ( length === i ) {
+ target = this;
+ --i;
+ }
+
+ for ( ; i < length; i++ ) {
+ // Only deal with non-null/undefined values
+ if ( (options = arguments[ i ]) != null ) {
+ // Extend the base object
+ for ( name in options ) {
+ src = target[ name ];
+ copy = options[ name ];
+
+ // Prevent never-ending loop
+ if ( target === copy ) {
+ continue;
+ }
+
+ // Recurse if we're merging plain objects or arrays
+ if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
+ if ( copyIsArray ) {
+ copyIsArray = false;
+ clone = src && jQuery.isArray(src) ? src : [];
+
+ } else {
+ clone = src && jQuery.isPlainObject(src) ? src : {};
+ }
+
+ // Never move original objects, clone them
+ target[ name ] = jQuery.extend( deep, clone, copy );
+
+ // Don't bring in undefined values
+ } else if ( copy !== undefined ) {
+ target[ name ] = copy;
+ }
+ }
+ }
+ }
+
+ // Return the modified object
+ return target;
+};
+
+jQuery.extend({
+ noConflict: function( deep ) {
+ if ( window.$ === jQuery ) {
+ window.$ = _$;
+ }
+
+ if ( deep && window.jQuery === jQuery ) {
+ window.jQuery = _jQuery;
+ }
+
+ return jQuery;
+ },
+
+ // Is the DOM ready to be used? Set to true once it occurs.
+ isReady: false,
+
+ // A counter to track how many items to wait for before
+ // the ready event fires. See #6781
+ readyWait: 1,
+
+ // Hold (or release) the ready event
+ holdReady: function( hold ) {
+ if ( hold ) {
+ jQuery.readyWait++;
+ } else {
+ jQuery.ready( true );
+ }
+ },
+
+ // Handle when the DOM is ready
+ ready: function( wait ) {
+ // Either a released hold or an DOMready/load event and not yet ready
+ if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
+ // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
+ if ( !document.body ) {
+ return setTimeout( jQuery.ready, 1 );
+ }
+
+ // Remember that the DOM is ready
+ jQuery.isReady = true;
+
+ // If a normal DOM Ready event fired, decrement, and wait if need be
+ if ( wait !== true && --jQuery.readyWait > 0 ) {
+ return;
+ }
+
+ // If there are functions bound, to execute
+ readyList.resolveWith( document, [ jQuery ] );
+
+ // Trigger any bound ready events
+ if ( jQuery.fn.trigger ) {
+ jQuery( document ).trigger( "ready" ).unbind( "ready" );
+ }
+ }
+ },
+
+ bindReady: function() {
+ if ( readyList ) {
+ return;
+ }
+
+ readyList = jQuery._Deferred();
+
+ // Catch cases where $(document).ready() is called after the
+ // browser event has already occurred.
+ if ( document.readyState === "complete" ) {
+ // Handle it asynchronously to allow scripts the opportunity to delay ready
+ return setTimeout( jQuery.ready, 1 );
+ }
+
+ // Mozilla, Opera and webkit nightlies currently support this event
+ if ( document.addEventListener ) {
+ // Use the handy event callback
+ document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
+
+ // A fallback to window.onload, that will always work
+ window.addEventListener( "load", jQuery.ready, false );
+
+ // If IE event model is used
+ } else if ( document.attachEvent ) {
+ // ensure firing before onload,
+ // maybe late but safe also for iframes
+ document.attachEvent( "onreadystatechange", DOMContentLoaded );
+
+ // A fallback to window.onload, that will always work
+ window.attachEvent( "onload", jQuery.ready );
+
+ // If IE and not a frame
+ // continually check to see if the document is ready
+ var toplevel = false;
+
+ try {
+ toplevel = window.frameElement == null;
+ } catch(e) {}
+
+ if ( document.documentElement.doScroll && toplevel ) {
+ doScrollCheck();
+ }
+ }
+ },
+
+ // See test/unit/core.js for details concerning isFunction.
+ // Since version 1.3, DOM methods and functions like alert
+ // aren't supported. They return false on IE (#2968).
+ isFunction: function( obj ) {
+ return jQuery.type(obj) === "function";
+ },
+
+ isArray: Array.isArray || function( obj ) {
+ return jQuery.type(obj) === "array";
+ },
+
+ // A crude way of determining if an object is a window
+ isWindow: function( obj ) {
+ return obj && typeof obj === "object" && "setInterval" in obj;
+ },
+
+ isNaN: function( obj ) {
+ return obj == null || !rdigit.test( obj ) || isNaN( obj );
+ },
+
+ type: function( obj ) {
+ return obj == null ?
+ String( obj ) :
+ class2type[ toString.call(obj) ] || "object";
+ },
+
+ isPlainObject: function( obj ) {
+ // Must be an Object.
+ // Because of IE, we also have to check the presence of the constructor property.
+ // Make sure that DOM nodes and window objects don't pass through, as well
+ if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
+ return false;
+ }
+
+ try {
+ // Not own constructor property must be Object
+ if ( obj.constructor &&
+ !hasOwn.call(obj, "constructor") &&
+ !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
+ return false;
+ }
+ } catch ( e ) {
+ // IE8,9 Will throw exceptions on certain host objects #9897
+ return false;
+ }
+
+ // Own properties are enumerated firstly, so to speed up,
+ // if last one is own, then all properties are own.
+
+ var key;
+ for ( key in obj ) {}
+
+ return key === undefined || hasOwn.call( obj, key );
+ },
+
+ isEmptyObject: function( obj ) {
+ for ( var name in obj ) {
+ return false;
+ }
+ return true;
+ },
+
+ error: function( msg ) {
+ throw msg;
+ },
+
+ parseJSON: function( data ) {
+ if ( typeof data !== "string" || !data ) {
+ return null;
+ }
+
+ // Make sure leading/trailing whitespace is removed (IE can't handle it)
+ data = jQuery.trim( data );
+
+ // Attempt to parse using the native JSON parser first
+ if ( window.JSON && window.JSON.parse ) {
+ return window.JSON.parse( data );
+ }
+
+ // Make sure the incoming data is actual JSON
+ // Logic borrowed from http://json.org/json2.js
+ if ( rvalidchars.test( data.replace( rvalidescape, "@" )
+ .replace( rvalidtokens, "]" )
+ .replace( rvalidbraces, "")) ) {
+
+ return (new Function( "return " + data ))();
+
+ }
+ jQuery.error( "Invalid JSON: " + data );
+ },
+
+ // Cross-browser xml parsing
+ parseXML: function( data ) {
+ var xml, tmp;
+ try {
+ if ( window.DOMParser ) { // Standard
+ tmp = new DOMParser();
+ xml = tmp.parseFromString( data , "text/xml" );
+ } else { // IE
+ xml = new ActiveXObject( "Microsoft.XMLDOM" );
+ xml.async = "false";
+ xml.loadXML( data );
+ }
+ } catch( e ) {
+ xml = undefined;
+ }
+ if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
+ jQuery.error( "Invalid XML: " + data );
+ }
+ return xml;
+ },
+
+ noop: function() {},
+
+ // Evaluates a script in a global context
+ // Workarounds based on findings by Jim Driscoll
+ // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
+ globalEval: function( data ) {
+ if ( data && rnotwhite.test( data ) ) {
+ // We use execScript on Internet Explorer
+ // We use an anonymous function so that context is window
+ // rather than jQuery in Firefox
+ ( window.execScript || function( data ) {
+ window[ "eval" ].call( window, data );
+ } )( data );
+ }
+ },
+
+ // Convert dashed to camelCase; used by the css and data modules
+ // Microsoft forgot to hump their vendor prefix (#9572)
+ camelCase: function( string ) {
+ return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
+ },
+
+ nodeName: function( elem, name ) {
+ return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
+ },
+
+ // args is for internal usage only
+ each: function( object, callback, args ) {
+ var name, i = 0,
+ length = object.length,
+ isObj = length === undefined || jQuery.isFunction( object );
+
+ if ( args ) {
+ if ( isObj ) {
+ for ( name in object ) {
+ if ( callback.apply( object[ name ], args ) === false ) {
+ break;
+ }
+ }
+ } else {
+ for ( ; i < length; ) {
+ if ( callback.apply( object[ i++ ], args ) === false ) {
+ break;
+ }
+ }
+ }
+
+ // A special, fast, case for the most common use of each
+ } else {
+ if ( isObj ) {
+ for ( name in object ) {
+ if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
+ break;
+ }
+ }
+ } else {
+ for ( ; i < length; ) {
+ if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
+ break;
+ }
+ }
+ }
+ }
+
+ return object;
+ },
+
+ // Use native String.trim function wherever possible
+ trim: trim ?
+ function( text ) {
+ return text == null ?
+ "" :
+ trim.call( text );
+ } :
+
+ // Otherwise use our own trimming functionality
+ function( text ) {
+ return text == null ?
+ "" :
+ text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
+ },
+
+ // results is for internal usage only
+ makeArray: function( array, results ) {
+ var ret = results || [];
+
+ if ( array != null ) {
+ // The window, strings (and functions) also have 'length'
+ // The extra typeof function check is to prevent crashes
+ // in Safari 2 (See: #3039)
+ // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
+ var type = jQuery.type( array );
+
+ if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
+ push.call( ret, array );
+ } else {
+ jQuery.merge( ret, array );
+ }
+ }
+
+ return ret;
+ },
+
+ inArray: function( elem, array ) {
+ if ( !array ) {
+ return -1;
+ }
+
+ if ( indexOf ) {
+ return indexOf.call( array, elem );
+ }
+
+ for ( var i = 0, length = array.length; i < length; i++ ) {
+ if ( array[ i ] === elem ) {
+ return i;
+ }
+ }
+
+ return -1;
+ },
+
+ merge: function( first, second ) {
+ var i = first.length,
+ j = 0;
+
+ if ( typeof second.length === "number" ) {
+ for ( var l = second.length; j < l; j++ ) {
+ first[ i++ ] = second[ j ];
+ }
+
+ } else {
+ while ( second[j] !== undefined ) {
+ first[ i++ ] = second[ j++ ];
+ }
+ }
+
+ first.length = i;
+
+ return first;
+ },
+
+ grep: function( elems, callback, inv ) {
+ var ret = [], retVal;
+ inv = !!inv;
+
+ // Go through the array, only saving the items
+ // that pass the validator function
+ for ( var i = 0, length = elems.length; i < length; i++ ) {
+ retVal = !!callback( elems[ i ], i );
+ if ( inv !== retVal ) {
+ ret.push( elems[ i ] );
+ }
+ }
+
+ return ret;
+ },
+
+ // arg is for internal usage only
+ map: function( elems, callback, arg ) {
+ var value, key, ret = [],
+ i = 0,
+ length = elems.length,
+ // jquery objects are treated as arrays
+ isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
+
+ // Go through the array, translating each of the items to their
+ if ( isArray ) {
+ for ( ; i < length; i++ ) {
+ value = callback( elems[ i ], i, arg );
+
+ if ( value != null ) {
+ ret[ ret.length ] = value;
+ }
+ }
+
+ // Go through every key on the object,
+ } else {
+ for ( key in elems ) {
+ value = callback( elems[ key ], key, arg );
+
+ if ( value != null ) {
+ ret[ ret.length ] = value;
+ }
+ }
+ }
+
+ // Flatten any nested arrays
+ return ret.concat.apply( [], ret );
+ },
+
+ // A global GUID counter for objects
+ guid: 1,
+
+ // Bind a function to a context, optionally partially applying any
+ // arguments.
+ proxy: function( fn, context ) {
+ if ( typeof context === "string" ) {
+ var tmp = fn[ context ];
+ context = fn;
+ fn = tmp;
+ }
+
+ // Quick check to determine if target is callable, in the spec
+ // this throws a TypeError, but we will just return undefined.
+ if ( !jQuery.isFunction( fn ) ) {
+ return undefined;
+ }
+
+ // Simulated bind
+ var args = slice.call( arguments, 2 ),
+ proxy = function() {
+ return fn.apply( context, args.concat( slice.call( arguments ) ) );
+ };
+
+ // Set the guid of unique handler to the same of original handler, so it can be removed
+ proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
+
+ return proxy;
+ },
+
+ // Mutifunctional method to get and set values to a collection
+ // The value/s can optionally be executed if it's a function
+ access: function( elems, key, value, exec, fn, pass ) {
+ var length = elems.length;
+
+ // Setting many attributes
+ if ( typeof key === "object" ) {
+ for ( var k in key ) {
+ jQuery.access( elems, k, key[k], exec, fn, value );
+ }
+ return elems;
+ }
+
+ // Setting one attribute
+ if ( value !== undefined ) {
+ // Optionally, function values get executed if exec is true
+ exec = !pass && exec && jQuery.isFunction(value);
+
+ for ( var i = 0; i < length; i++ ) {
+ fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
+ }
+
+ return elems;
+ }
+
+ // Getting an attribute
+ return length ? fn( elems[0], key ) : undefined;
+ },
+
+ now: function() {
+ return (new Date()).getTime();
+ },
+
+ // Use of jQuery.browser is frowned upon.
+ // More details: http://docs.jquery.com/Utilities/jQuery.browser
+ uaMatch: function( ua ) {
+ ua = ua.toLowerCase();
+
+ var match = rwebkit.exec( ua ) ||
+ ropera.exec( ua ) ||
+ rmsie.exec( ua ) ||
+ ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
+ [];
+
+ return { browser: match[1] || "", version: match[2] || "0" };
+ },
+
+ sub: function() {
+ function jQuerySub( selector, context ) {
+ return new jQuerySub.fn.init( selector, context );
+ }
+ jQuery.extend( true, jQuerySub, this );
+ jQuerySub.superclass = this;
+ jQuerySub.fn = jQuerySub.prototype = this();
+ jQuerySub.fn.constructor = jQuerySub;
+ jQuerySub.sub = this.sub;
+ jQuerySub.fn.init = function init( selector, context ) {
+ if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
+ context = jQuerySub( context );
+ }
+
+ return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
+ };
+ jQuerySub.fn.init.prototype = jQuerySub.fn;
+ var rootjQuerySub = jQuerySub(document);
+ return jQuerySub;
+ },
+
+ browser: {}
+});
+
+// Populate the class2type map
+jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
+ class2type[ "[object " + name + "]" ] = name.toLowerCase();
+});
+
+browserMatch = jQuery.uaMatch( userAgent );
+if ( browserMatch.browser ) {
+ jQuery.browser[ browserMatch.browser ] = true;
+ jQuery.browser.version = browserMatch.version;
+}
+
+// Deprecated, use jQuery.browser.webkit instead
+if ( jQuery.browser.webkit ) {
+ jQuery.browser.safari = true;
+}
+
+// IE doesn't match non-breaking spaces with \s
+if ( rnotwhite.test( "\xA0" ) ) {
+ trimLeft = /^[\s\xA0]+/;
+ trimRight = /[\s\xA0]+$/;
+}
+
+// All jQuery objects should point back to these
+rootjQuery = jQuery(document);
+
+// Cleanup functions for the document ready method
+if ( document.addEventListener ) {
+ DOMContentLoaded = function() {
+ document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
+ jQuery.ready();
+ };
+
+} else if ( document.attachEvent ) {
+ DOMContentLoaded = function() {
+ // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
+ if ( document.readyState === "complete" ) {
+ document.detachEvent( "onreadystatechange", DOMContentLoaded );
+ jQuery.ready();
+ }
+ };
+}
+
+// The DOM ready check for Internet Explorer
+function doScrollCheck() {
+ if ( jQuery.isReady ) {
+ return;
+ }
+
+ try {
+ // If IE is used, use the trick by Diego Perini
+ // http://javascript.nwbox.com/IEContentLoaded/
+ document.documentElement.doScroll("left");
+ } catch(e) {
+ setTimeout( doScrollCheck, 1 );
+ return;
+ }
+
+ // and execute any waiting functions
+ jQuery.ready();
+}
+
+return jQuery;
+
+})();
+
+
+var // Promise methods
+ promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ),
+ // Static reference to slice
+ sliceDeferred = [].slice;
+
+jQuery.extend({
+ // Create a simple deferred (one callbacks list)
+ _Deferred: function() {
+ var // callbacks list
+ callbacks = [],
+ // stored [ context , args ]
+ fired,
+ // to avoid firing when already doing so
+ firing,
+ // flag to know if the deferred has been cancelled
+ cancelled,
+ // the deferred itself
+ deferred = {
+
+ // done( f1, f2, ...)
+ done: function() {
+ if ( !cancelled ) {
+ var args = arguments,
+ i,
+ length,
+ elem,
+ type,
+ _fired;
+ if ( fired ) {
+ _fired = fired;
+ fired = 0;
+ }
+ for ( i = 0, length = args.length; i < length; i++ ) {
+ elem = args[ i ];
+ type = jQuery.type( elem );
+ if ( type === "array" ) {
+ deferred.done.apply( deferred, elem );
+ } else if ( type === "function" ) {
+ callbacks.push( elem );
+ }
+ }
+ if ( _fired ) {
+ deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
+ }
+ }
+ return this;
+ },
+
+ // resolve with given context and args
+ resolveWith: function( context, args ) {
+ if ( !cancelled && !fired && !firing ) {
+ // make sure args are available (#8421)
+ args = args || [];
+ firing = 1;
+ try {
+ while( callbacks[ 0 ] ) {
+ callbacks.shift().apply( context, args );
+ }
+ }
+ finally {
+ fired = [ context, args ];
+ firing = 0;
+ }
+ }
+ return this;
+ },
+
+ // resolve with this as context and given arguments
+ resolve: function() {
+ deferred.resolveWith( this, arguments );
+ return this;
+ },
+
+ // Has this deferred been resolved?
+ isResolved: function() {
+ return !!( firing || fired );
+ },
+
+ // Cancel
+ cancel: function() {
+ cancelled = 1;
+ callbacks = [];
+ return this;
+ }
+ };
+
+ return deferred;
+ },
+
+ // Full fledged deferred (two callbacks list)
+ Deferred: function( func ) {
+ var deferred = jQuery._Deferred(),
+ failDeferred = jQuery._Deferred(),
+ promise;
+ // Add errorDeferred methods, then and promise
+ jQuery.extend( deferred, {
+ then: function( doneCallbacks, failCallbacks ) {
+ deferred.done( doneCallbacks ).fail( failCallbacks );
+ return this;
+ },
+ always: function() {
+ return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments );
+ },
+ fail: failDeferred.done,
+ rejectWith: failDeferred.resolveWith,
+ reject: failDeferred.resolve,
+ isRejected: failDeferred.isResolved,
+ pipe: function( fnDone, fnFail ) {
+ return jQuery.Deferred(function( newDefer ) {
+ jQuery.each( {
+ done: [ fnDone, "resolve" ],
+ fail: [ fnFail, "reject" ]
+ }, function( handler, data ) {
+ var fn = data[ 0 ],
+ action = data[ 1 ],
+ returned;
+ if ( jQuery.isFunction( fn ) ) {
+ deferred[ handler ](function() {
+ returned = fn.apply( this, arguments );
+ if ( returned && jQuery.isFunction( returned.promise ) ) {
+ returned.promise().then( newDefer.resolve, newDefer.reject );
+ } else {
+ newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
+ }
+ });
+ } else {
+ deferred[ handler ]( newDefer[ action ] );
+ }
+ });
+ }).promise();
+ },
+ // Get a promise for this deferred
+ // If obj is provided, the promise aspect is added to the object
+ promise: function( obj ) {
+ if ( obj == null ) {
+ if ( promise ) {
+ return promise;
+ }
+ promise = obj = {};
+ }
+ var i = promiseMethods.length;
+ while( i-- ) {
+ obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ];
+ }
+ return obj;
+ }
+ });
+ // Make sure only one callback list will be used
+ deferred.done( failDeferred.cancel ).fail( deferred.cancel );
+ // Unexpose cancel
+ delete deferred.cancel;
+ // Call given func if any
+ if ( func ) {
+ func.call( deferred, deferred );
+ }
+ return deferred;
+ },
+
+ // Deferred helper
+ when: function( firstParam ) {
+ var args = arguments,
+ i = 0,
+ length = args.length,
+ count = length,
+ deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
+ firstParam :
+ jQuery.Deferred();
+ function resolveFunc( i ) {
+ return function( value ) {
+ args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
+ if ( !( --count ) ) {
+ // Strange bug in FF4:
+ // Values changed onto the arguments object sometimes end up as undefined values
+ // outside the $.when method. Cloning the object into a fresh array solves the issue
+ deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) );
+ }
+ };
+ }
+ if ( length > 1 ) {
+ for( ; i < length; i++ ) {
+ if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) {
+ args[ i ].promise().then( resolveFunc(i), deferred.reject );
+ } else {
+ --count;
+ }
+ }
+ if ( !count ) {
+ deferred.resolveWith( deferred, args );
+ }
+ } else if ( deferred !== firstParam ) {
+ deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
+ }
+ return deferred.promise();
+ }
+});
+
+
+
+jQuery.support = (function() {
+
+ var div = document.createElement( "div" ),
+ documentElement = document.documentElement,
+ all,
+ a,
+ select,
+ opt,
+ input,
+ marginDiv,
+ support,
+ fragment,
+ body,
+ testElementParent,
+ testElement,
+ testElementStyle,
+ tds,
+ events,
+ eventName,
+ i,
+ isSupported;
+
+ // Preliminary tests
+ div.setAttribute("className", "t");
+ div.innerHTML = "
a";
+
+
+ all = div.getElementsByTagName( "*" );
+ a = div.getElementsByTagName( "a" )[ 0 ];
+
+ // Can't get basic test support
+ if ( !all || !all.length || !a ) {
+ return {};
+ }
+
+ // First batch of supports tests
+ select = document.createElement( "select" );
+ opt = select.appendChild( document.createElement("option") );
+ input = div.getElementsByTagName( "input" )[ 0 ];
+
+ support = {
+ // IE strips leading whitespace when .innerHTML is used
+ leadingWhitespace: ( div.firstChild.nodeType === 3 ),
+
+ // Make sure that tbody elements aren't automatically inserted
+ // IE will insert them into empty tables
+ tbody: !div.getElementsByTagName( "tbody" ).length,
+
+ // Make sure that link elements get serialized correctly by innerHTML
+ // This requires a wrapper element in IE
+ htmlSerialize: !!div.getElementsByTagName( "link" ).length,
+
+ // Get the style information from getAttribute
+ // (IE uses .cssText instead)
+ style: /top/.test( a.getAttribute("style") ),
+
+ // Make sure that URLs aren't manipulated
+ // (IE normalizes it by default)
+ hrefNormalized: ( a.getAttribute( "href" ) === "/a" ),
+
+ // Make sure that element opacity exists
+ // (IE uses filter instead)
+ // Use a regex to work around a WebKit issue. See #5145
+ opacity: /^0.55$/.test( a.style.opacity ),
+
+ // Verify style float existence
+ // (IE uses styleFloat instead of cssFloat)
+ cssFloat: !!a.style.cssFloat,
+
+ // Make sure that if no value is specified for a checkbox
+ // that it defaults to "on".
+ // (WebKit defaults to "" instead)
+ checkOn: ( input.value === "on" ),
+
+ // Make sure that a selected-by-default option has a working selected property.
+ // (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
+ optSelected: opt.selected,
+
+ // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
+ getSetAttribute: div.className !== "t",
+
+ // Will be defined later
+ submitBubbles: true,
+ changeBubbles: true,
+ focusinBubbles: false,
+ deleteExpando: true,
+ noCloneEvent: true,
+ inlineBlockNeedsLayout: false,
+ shrinkWrapBlocks: false,
+ reliableMarginRight: true
+ };
+
+ // Make sure checked status is properly cloned
+ input.checked = true;
+ support.noCloneChecked = input.cloneNode( true ).checked;
+
+ // Make sure that the options inside disabled selects aren't marked as disabled
+ // (WebKit marks them as disabled)
+ select.disabled = true;
+ support.optDisabled = !opt.disabled;
+
+ // Test to see if it's possible to delete an expando from an element
+ // Fails in Internet Explorer
+ try {
+ delete div.test;
+ } catch( e ) {
+ support.deleteExpando = false;
+ }
+
+ if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
+ div.attachEvent( "onclick", function() {
+ // Cloning a node shouldn't copy over any
+ // bound event handlers (IE does this)
+ support.noCloneEvent = false;
+ });
+ div.cloneNode( true ).fireEvent( "onclick" );
+ }
+
+ // Check if a radio maintains it's value
+ // after being appended to the DOM
+ input = document.createElement("input");
+ input.value = "t";
+ input.setAttribute("type", "radio");
+ support.radioValue = input.value === "t";
+
+ input.setAttribute("checked", "checked");
+ div.appendChild( input );
+ fragment = document.createDocumentFragment();
+ fragment.appendChild( div.firstChild );
+
+ // WebKit doesn't clone checked state correctly in fragments
+ support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
+
+ div.innerHTML = "";
+
+ // Figure out if the W3C box model works as expected
+ div.style.width = div.style.paddingLeft = "1px";
+
+ body = document.getElementsByTagName( "body" )[ 0 ];
+ // We use our own, invisible, body unless the body is already present
+ // in which case we use a div (#9239)
+ testElement = document.createElement( body ? "div" : "body" );
+ testElementStyle = {
+ visibility: "hidden",
+ width: 0,
+ height: 0,
+ border: 0,
+ margin: 0,
+ background: "none"
+ };
+ if ( body ) {
+ jQuery.extend( testElementStyle, {
+ position: "absolute",
+ left: "-1000px",
+ top: "-1000px"
+ });
+ }
+ for ( i in testElementStyle ) {
+ testElement.style[ i ] = testElementStyle[ i ];
+ }
+ testElement.appendChild( div );
+ testElementParent = body || documentElement;
+ testElementParent.insertBefore( testElement, testElementParent.firstChild );
+
+ // Check if a disconnected checkbox will retain its checked
+ // value of true after appended to the DOM (IE6/7)
+ support.appendChecked = input.checked;
+
+ support.boxModel = div.offsetWidth === 2;
+
+ if ( "zoom" in div.style ) {
+ // Check if natively block-level elements act like inline-block
+ // elements when setting their display to 'inline' and giving
+ // them layout
+ // (IE < 8 does this)
+ div.style.display = "inline";
+ div.style.zoom = 1;
+ support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 );
+
+ // Check if elements with layout shrink-wrap their children
+ // (IE 6 does this)
+ div.style.display = "";
+ div.innerHTML = "";
+ support.shrinkWrapBlocks = ( div.offsetWidth !== 2 );
+ }
+
+ div.innerHTML = "
t
";
+ tds = div.getElementsByTagName( "td" );
+
+ // Check if table cells still have offsetWidth/Height when they are set
+ // to display:none and there are still other visible table cells in a
+ // table row; if so, offsetWidth/Height are not reliable for use when
+ // determining if an element has been hidden directly using
+ // display:none (it is still safe to use offsets if a parent element is
+ // hidden; don safety goggles and see bug #4512 for more information).
+ // (only IE 8 fails this test)
+ isSupported = ( tds[ 0 ].offsetHeight === 0 );
+
+ tds[ 0 ].style.display = "";
+ tds[ 1 ].style.display = "none";
+
+ // Check if empty table cells still have offsetWidth/Height
+ // (IE < 8 fail this test)
+ support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
+ div.innerHTML = "";
+
+ // Check if div with explicit width and no margin-right incorrectly
+ // gets computed margin-right based on width of container. For more
+ // info see bug #3333
+ // Fails in WebKit before Feb 2011 nightlies
+ // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
+ if ( document.defaultView && document.defaultView.getComputedStyle ) {
+ marginDiv = document.createElement( "div" );
+ marginDiv.style.width = "0";
+ marginDiv.style.marginRight = "0";
+ div.appendChild( marginDiv );
+ support.reliableMarginRight =
+ ( parseInt( ( document.defaultView.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
+ }
+
+ // Remove the body element we added
+ testElement.innerHTML = "";
+ testElementParent.removeChild( testElement );
+
+ // Technique from Juriy Zaytsev
+ // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
+ // We only care about the case where non-standard event systems
+ // are used, namely in IE. Short-circuiting here helps us to
+ // avoid an eval call (in setAttribute) which can cause CSP
+ // to go haywire. See: https://developer.mozilla.org/en/Security/CSP
+ if ( div.attachEvent ) {
+ for( i in {
+ submit: 1,
+ change: 1,
+ focusin: 1
+ } ) {
+ eventName = "on" + i;
+ isSupported = ( eventName in div );
+ if ( !isSupported ) {
+ div.setAttribute( eventName, "return;" );
+ isSupported = ( typeof div[ eventName ] === "function" );
+ }
+ support[ i + "Bubbles" ] = isSupported;
+ }
+ }
+
+ // Null connected elements to avoid leaks in IE
+ testElement = fragment = select = opt = body = marginDiv = div = input = null;
+
+ return support;
+})();
+
+// Keep track of boxModel
+jQuery.boxModel = jQuery.support.boxModel;
+
+
+
+
+var rbrace = /^(?:\{.*\}|\[.*\])$/,
+ rmultiDash = /([a-z])([A-Z])/g;
+
+jQuery.extend({
+ cache: {},
+
+ // Please use with caution
+ uuid: 0,
+
+ // Unique for each copy of jQuery on the page
+ // Non-digits removed to match rinlinejQuery
+ expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
+
+ // The following elements throw uncatchable exceptions if you
+ // attempt to add expando properties to them.
+ noData: {
+ "embed": true,
+ // Ban all objects except for Flash (which handle expandos)
+ "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
+ "applet": true
+ },
+
+ hasData: function( elem ) {
+ elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
+
+ return !!elem && !isEmptyDataObject( elem );
+ },
+
+ data: function( elem, name, data, pvt /* Internal Use Only */ ) {
+ if ( !jQuery.acceptData( elem ) ) {
+ return;
+ }
+
+ var thisCache, ret,
+ internalKey = jQuery.expando,
+ getByName = typeof name === "string",
+
+ // We have to handle DOM nodes and JS objects differently because IE6-7
+ // can't GC object references properly across the DOM-JS boundary
+ isNode = elem.nodeType,
+
+ // Only DOM nodes need the global jQuery cache; JS object data is
+ // attached directly to the object so GC can occur automatically
+ cache = isNode ? jQuery.cache : elem,
+
+ // Only defining an ID for JS objects if its cache already exists allows
+ // the code to shortcut on the same path as a DOM node with no cache
+ id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando;
+
+ // Avoid doing any more work than we need to when trying to get data on an
+ // object that has no data at all
+ if ( (!id || (pvt && id && (cache[ id ] && !cache[ id ][ internalKey ]))) && getByName && data === undefined ) {
+ return;
+ }
+
+ if ( !id ) {
+ // Only DOM nodes need a new unique ID for each element since their data
+ // ends up in the global cache
+ if ( isNode ) {
+ elem[ jQuery.expando ] = id = ++jQuery.uuid;
+ } else {
+ id = jQuery.expando;
+ }
+ }
+
+ if ( !cache[ id ] ) {
+ cache[ id ] = {};
+
+ // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
+ // metadata on plain JS objects when the object is serialized using
+ // JSON.stringify
+ if ( !isNode ) {
+ cache[ id ].toJSON = jQuery.noop;
+ }
+ }
+
+ // An object can be passed to jQuery.data instead of a key/value pair; this gets
+ // shallow copied over onto the existing cache
+ if ( typeof name === "object" || typeof name === "function" ) {
+ if ( pvt ) {
+ cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name);
+ } else {
+ cache[ id ] = jQuery.extend(cache[ id ], name);
+ }
+ }
+
+ thisCache = cache[ id ];
+
+ // Internal jQuery data is stored in a separate object inside the object's data
+ // cache in order to avoid key collisions between internal data and user-defined
+ // data
+ if ( pvt ) {
+ if ( !thisCache[ internalKey ] ) {
+ thisCache[ internalKey ] = {};
+ }
+
+ thisCache = thisCache[ internalKey ];
+ }
+
+ if ( data !== undefined ) {
+ thisCache[ jQuery.camelCase( name ) ] = data;
+ }
+
+ // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should
+ // not attempt to inspect the internal events object using jQuery.data, as this
+ // internal data object is undocumented and subject to change.
+ if ( name === "events" && !thisCache[name] ) {
+ return thisCache[ internalKey ] && thisCache[ internalKey ].events;
+ }
+
+ // Check for both converted-to-camel and non-converted data property names
+ // If a data property was specified
+ if ( getByName ) {
+
+ // First Try to find as-is property data
+ ret = thisCache[ name ];
+
+ // Test for null|undefined property data
+ if ( ret == null ) {
+
+ // Try to find the camelCased property
+ ret = thisCache[ jQuery.camelCase( name ) ];
+ }
+ } else {
+ ret = thisCache;
+ }
+
+ return ret;
+ },
+
+ removeData: function( elem, name, pvt /* Internal Use Only */ ) {
+ if ( !jQuery.acceptData( elem ) ) {
+ return;
+ }
+
+ var thisCache,
+
+ // Reference to internal data cache key
+ internalKey = jQuery.expando,
+
+ isNode = elem.nodeType,
+
+ // See jQuery.data for more information
+ cache = isNode ? jQuery.cache : elem,
+
+ // See jQuery.data for more information
+ id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
+
+ // If there is already no cache entry for this object, there is no
+ // purpose in continuing
+ if ( !cache[ id ] ) {
+ return;
+ }
+
+ if ( name ) {
+
+ thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ];
+
+ if ( thisCache ) {
+
+ // Support interoperable removal of hyphenated or camelcased keys
+ if ( !thisCache[ name ] ) {
+ name = jQuery.camelCase( name );
+ }
+
+ delete thisCache[ name ];
+
+ // If there is no data left in the cache, we want to continue
+ // and let the cache object itself get destroyed
+ if ( !isEmptyDataObject(thisCache) ) {
+ return;
+ }
+ }
+ }
+
+ // See jQuery.data for more information
+ if ( pvt ) {
+ delete cache[ id ][ internalKey ];
+
+ // Don't destroy the parent cache unless the internal data object
+ // had been the only thing left in it
+ if ( !isEmptyDataObject(cache[ id ]) ) {
+ return;
+ }
+ }
+
+ var internalCache = cache[ id ][ internalKey ];
+
+ // Browsers that fail expando deletion also refuse to delete expandos on
+ // the window, but it will allow it on all other JS objects; other browsers
+ // don't care
+ // Ensure that `cache` is not a window object #10080
+ if ( jQuery.support.deleteExpando || !cache.setInterval ) {
+ delete cache[ id ];
+ } else {
+ cache[ id ] = null;
+ }
+
+ // We destroyed the entire user cache at once because it's faster than
+ // iterating through each key, but we need to continue to persist internal
+ // data if it existed
+ if ( internalCache ) {
+ cache[ id ] = {};
+ // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
+ // metadata on plain JS objects when the object is serialized using
+ // JSON.stringify
+ if ( !isNode ) {
+ cache[ id ].toJSON = jQuery.noop;
+ }
+
+ cache[ id ][ internalKey ] = internalCache;
+
+ // Otherwise, we need to eliminate the expando on the node to avoid
+ // false lookups in the cache for entries that no longer exist
+ } else if ( isNode ) {
+ // IE does not allow us to delete expando properties from nodes,
+ // nor does it have a removeAttribute function on Document nodes;
+ // we must handle all of these cases
+ if ( jQuery.support.deleteExpando ) {
+ delete elem[ jQuery.expando ];
+ } else if ( elem.removeAttribute ) {
+ elem.removeAttribute( jQuery.expando );
+ } else {
+ elem[ jQuery.expando ] = null;
+ }
+ }
+ },
+
+ // For internal use only.
+ _data: function( elem, name, data ) {
+ return jQuery.data( elem, name, data, true );
+ },
+
+ // A method for determining if a DOM node can handle the data expando
+ acceptData: function( elem ) {
+ if ( elem.nodeName ) {
+ var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
+
+ if ( match ) {
+ return !(match === true || elem.getAttribute("classid") !== match);
+ }
+ }
+
+ return true;
+ }
+});
+
+jQuery.fn.extend({
+ data: function( key, value ) {
+ var data = null;
+
+ if ( typeof key === "undefined" ) {
+ if ( this.length ) {
+ data = jQuery.data( this[0] );
+
+ if ( this[0].nodeType === 1 ) {
+ var attr = this[0].attributes, name;
+ for ( var i = 0, l = attr.length; i < l; i++ ) {
+ name = attr[i].name;
+
+ if ( name.indexOf( "data-" ) === 0 ) {
+ name = jQuery.camelCase( name.substring(5) );
+
+ dataAttr( this[0], name, data[ name ] );
+ }
+ }
+ }
+ }
+
+ return data;
+
+ } else if ( typeof key === "object" ) {
+ return this.each(function() {
+ jQuery.data( this, key );
+ });
+ }
+
+ var parts = key.split(".");
+ parts[1] = parts[1] ? "." + parts[1] : "";
+
+ if ( value === undefined ) {
+ data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
+
+ // Try to fetch any internally stored data first
+ if ( data === undefined && this.length ) {
+ data = jQuery.data( this[0], key );
+ data = dataAttr( this[0], key, data );
+ }
+
+ return data === undefined && parts[1] ?
+ this.data( parts[0] ) :
+ data;
+
+ } else {
+ return this.each(function() {
+ var $this = jQuery( this ),
+ args = [ parts[0], value ];
+
+ $this.triggerHandler( "setData" + parts[1] + "!", args );
+ jQuery.data( this, key, value );
+ $this.triggerHandler( "changeData" + parts[1] + "!", args );
+ });
+ }
+ },
+
+ removeData: function( key ) {
+ return this.each(function() {
+ jQuery.removeData( this, key );
+ });
+ }
+});
+
+function dataAttr( elem, key, data ) {
+ // If nothing was found internally, try to fetch any
+ // data from the HTML5 data-* attribute
+ if ( data === undefined && elem.nodeType === 1 ) {
+ var name = "data-" + key.replace( rmultiDash, "$1-$2" ).toLowerCase();
+
+ data = elem.getAttribute( name );
+
+ if ( typeof data === "string" ) {
+ try {
+ data = data === "true" ? true :
+ data === "false" ? false :
+ data === "null" ? null :
+ !jQuery.isNaN( data ) ? parseFloat( data ) :
+ rbrace.test( data ) ? jQuery.parseJSON( data ) :
+ data;
+ } catch( e ) {}
+
+ // Make sure we set the data so it isn't changed later
+ jQuery.data( elem, key, data );
+
+ } else {
+ data = undefined;
+ }
+ }
+
+ return data;
+}
+
+// TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON
+// property to be considered empty objects; this property always exists in
+// order to make sure JSON.stringify does not expose internal metadata
+function isEmptyDataObject( obj ) {
+ for ( var name in obj ) {
+ if ( name !== "toJSON" ) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+
+
+
+function handleQueueMarkDefer( elem, type, src ) {
+ var deferDataKey = type + "defer",
+ queueDataKey = type + "queue",
+ markDataKey = type + "mark",
+ defer = jQuery.data( elem, deferDataKey, undefined, true );
+ if ( defer &&
+ ( src === "queue" || !jQuery.data( elem, queueDataKey, undefined, true ) ) &&
+ ( src === "mark" || !jQuery.data( elem, markDataKey, undefined, true ) ) ) {
+ // Give room for hard-coded callbacks to fire first
+ // and eventually mark/queue something else on the element
+ setTimeout( function() {
+ if ( !jQuery.data( elem, queueDataKey, undefined, true ) &&
+ !jQuery.data( elem, markDataKey, undefined, true ) ) {
+ jQuery.removeData( elem, deferDataKey, true );
+ defer.resolve();
+ }
+ }, 0 );
+ }
+}
+
+jQuery.extend({
+
+ _mark: function( elem, type ) {
+ if ( elem ) {
+ type = (type || "fx") + "mark";
+ jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true );
+ }
+ },
+
+ _unmark: function( force, elem, type ) {
+ if ( force !== true ) {
+ type = elem;
+ elem = force;
+ force = false;
+ }
+ if ( elem ) {
+ type = type || "fx";
+ var key = type + "mark",
+ count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 );
+ if ( count ) {
+ jQuery.data( elem, key, count, true );
+ } else {
+ jQuery.removeData( elem, key, true );
+ handleQueueMarkDefer( elem, type, "mark" );
+ }
+ }
+ },
+
+ queue: function( elem, type, data ) {
+ if ( elem ) {
+ type = (type || "fx") + "queue";
+ var q = jQuery.data( elem, type, undefined, true );
+ // Speed up dequeue by getting out quickly if this is just a lookup
+ if ( data ) {
+ if ( !q || jQuery.isArray(data) ) {
+ q = jQuery.data( elem, type, jQuery.makeArray(data), true );
+ } else {
+ q.push( data );
+ }
+ }
+ return q || [];
+ }
+ },
+
+ dequeue: function( elem, type ) {
+ type = type || "fx";
+
+ var queue = jQuery.queue( elem, type ),
+ fn = queue.shift(),
+ defer;
+
+ // If the fx queue is dequeued, always remove the progress sentinel
+ if ( fn === "inprogress" ) {
+ fn = queue.shift();
+ }
+
+ if ( fn ) {
+ // Add a progress sentinel to prevent the fx queue from being
+ // automatically dequeued
+ if ( type === "fx" ) {
+ queue.unshift("inprogress");
+ }
+
+ fn.call(elem, function() {
+ jQuery.dequeue(elem, type);
+ });
+ }
+
+ if ( !queue.length ) {
+ jQuery.removeData( elem, type + "queue", true );
+ handleQueueMarkDefer( elem, type, "queue" );
+ }
+ }
+});
+
+jQuery.fn.extend({
+ queue: function( type, data ) {
+ if ( typeof type !== "string" ) {
+ data = type;
+ type = "fx";
+ }
+
+ if ( data === undefined ) {
+ return jQuery.queue( this[0], type );
+ }
+ return this.each(function() {
+ var queue = jQuery.queue( this, type, data );
+
+ if ( type === "fx" && queue[0] !== "inprogress" ) {
+ jQuery.dequeue( this, type );
+ }
+ });
+ },
+ dequeue: function( type ) {
+ return this.each(function() {
+ jQuery.dequeue( this, type );
+ });
+ },
+ // Based off of the plugin by Clint Helfers, with permission.
+ // http://blindsignals.com/index.php/2009/07/jquery-delay/
+ delay: function( time, type ) {
+ time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
+ type = type || "fx";
+
+ return this.queue( type, function() {
+ var elem = this;
+ setTimeout(function() {
+ jQuery.dequeue( elem, type );
+ }, time );
+ });
+ },
+ clearQueue: function( type ) {
+ return this.queue( type || "fx", [] );
+ },
+ // Get a promise resolved when queues of a certain type
+ // are emptied (fx is the type by default)
+ promise: function( type, object ) {
+ if ( typeof type !== "string" ) {
+ object = type;
+ type = undefined;
+ }
+ type = type || "fx";
+ var defer = jQuery.Deferred(),
+ elements = this,
+ i = elements.length,
+ count = 1,
+ deferDataKey = type + "defer",
+ queueDataKey = type + "queue",
+ markDataKey = type + "mark",
+ tmp;
+ function resolve() {
+ if ( !( --count ) ) {
+ defer.resolveWith( elements, [ elements ] );
+ }
+ }
+ while( i-- ) {
+ if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
+ ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
+ jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
+ jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) {
+ count++;
+ tmp.done( resolve );
+ }
+ }
+ resolve();
+ return defer.promise();
+ }
+});
+
+
+
+
+var rclass = /[\n\t\r]/g,
+ rspace = /\s+/,
+ rreturn = /\r/g,
+ rtype = /^(?:button|input)$/i,
+ rfocusable = /^(?:button|input|object|select|textarea)$/i,
+ rclickable = /^a(?:rea)?$/i,
+ rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
+ nodeHook, boolHook;
+
+jQuery.fn.extend({
+ attr: function( name, value ) {
+ return jQuery.access( this, name, value, true, jQuery.attr );
+ },
+
+ removeAttr: function( name ) {
+ return this.each(function() {
+ jQuery.removeAttr( this, name );
+ });
+ },
+
+ prop: function( name, value ) {
+ return jQuery.access( this, name, value, true, jQuery.prop );
+ },
+
+ removeProp: function( name ) {
+ name = jQuery.propFix[ name ] || name;
+ return this.each(function() {
+ // try/catch handles cases where IE balks (such as removing a property on window)
+ try {
+ this[ name ] = undefined;
+ delete this[ name ];
+ } catch( e ) {}
+ });
+ },
+
+ addClass: function( value ) {
+ var classNames, i, l, elem,
+ setClass, c, cl;
+
+ if ( jQuery.isFunction( value ) ) {
+ return this.each(function( j ) {
+ jQuery( this ).addClass( value.call(this, j, this.className) );
+ });
+ }
+
+ if ( value && typeof value === "string" ) {
+ classNames = value.split( rspace );
+
+ for ( i = 0, l = this.length; i < l; i++ ) {
+ elem = this[ i ];
+
+ if ( elem.nodeType === 1 ) {
+ if ( !elem.className && classNames.length === 1 ) {
+ elem.className = value;
+
+ } else {
+ setClass = " " + elem.className + " ";
+
+ for ( c = 0, cl = classNames.length; c < cl; c++ ) {
+ if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
+ setClass += classNames[ c ] + " ";
+ }
+ }
+ elem.className = jQuery.trim( setClass );
+ }
+ }
+ }
+ }
+
+ return this;
+ },
+
+ removeClass: function( value ) {
+ var classNames, i, l, elem, className, c, cl;
+
+ if ( jQuery.isFunction( value ) ) {
+ return this.each(function( j ) {
+ jQuery( this ).removeClass( value.call(this, j, this.className) );
+ });
+ }
+
+ if ( (value && typeof value === "string") || value === undefined ) {
+ classNames = (value || "").split( rspace );
+
+ for ( i = 0, l = this.length; i < l; i++ ) {
+ elem = this[ i ];
+
+ if ( elem.nodeType === 1 && elem.className ) {
+ if ( value ) {
+ className = (" " + elem.className + " ").replace( rclass, " " );
+ for ( c = 0, cl = classNames.length; c < cl; c++ ) {
+ className = className.replace(" " + classNames[ c ] + " ", " ");
+ }
+ elem.className = jQuery.trim( className );
+
+ } else {
+ elem.className = "";
+ }
+ }
+ }
+ }
+
+ return this;
+ },
+
+ toggleClass: function( value, stateVal ) {
+ var type = typeof value,
+ isBool = typeof stateVal === "boolean";
+
+ if ( jQuery.isFunction( value ) ) {
+ return this.each(function( i ) {
+ jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
+ });
+ }
+
+ return this.each(function() {
+ if ( type === "string" ) {
+ // toggle individual class names
+ var className,
+ i = 0,
+ self = jQuery( this ),
+ state = stateVal,
+ classNames = value.split( rspace );
+
+ while ( (className = classNames[ i++ ]) ) {
+ // check each className given, space seperated list
+ state = isBool ? state : !self.hasClass( className );
+ self[ state ? "addClass" : "removeClass" ]( className );
+ }
+
+ } else if ( type === "undefined" || type === "boolean" ) {
+ if ( this.className ) {
+ // store className if set
+ jQuery._data( this, "__className__", this.className );
+ }
+
+ // toggle whole className
+ this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
+ }
+ });
+ },
+
+ hasClass: function( selector ) {
+ var className = " " + selector + " ";
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
+ return true;
+ }
+ }
+
+ return false;
+ },
+
+ val: function( value ) {
+ var hooks, ret,
+ elem = this[0];
+
+ if ( !arguments.length ) {
+ if ( elem ) {
+ hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];
+
+ if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
+ return ret;
+ }
+
+ ret = elem.value;
+
+ return typeof ret === "string" ?
+ // handle most common string cases
+ ret.replace(rreturn, "") :
+ // handle cases where value is null/undef or number
+ ret == null ? "" : ret;
+ }
+
+ return undefined;
+ }
+
+ var isFunction = jQuery.isFunction( value );
+
+ return this.each(function( i ) {
+ var self = jQuery(this), val;
+
+ if ( this.nodeType !== 1 ) {
+ return;
+ }
+
+ if ( isFunction ) {
+ val = value.call( this, i, self.val() );
+ } else {
+ val = value;
+ }
+
+ // Treat null/undefined as ""; convert numbers to string
+ if ( val == null ) {
+ val = "";
+ } else if ( typeof val === "number" ) {
+ val += "";
+ } else if ( jQuery.isArray( val ) ) {
+ val = jQuery.map(val, function ( value ) {
+ return value == null ? "" : value + "";
+ });
+ }
+
+ hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ];
+
+ // If set returns undefined, fall back to normal setting
+ if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
+ this.value = val;
+ }
+ });
+ }
+});
+
+jQuery.extend({
+ valHooks: {
+ option: {
+ get: function( elem ) {
+ // attributes.value is undefined in Blackberry 4.7 but
+ // uses .value. See #6932
+ var val = elem.attributes.value;
+ return !val || val.specified ? elem.value : elem.text;
+ }
+ },
+ select: {
+ get: function( elem ) {
+ var value,
+ index = elem.selectedIndex,
+ values = [],
+ options = elem.options,
+ one = elem.type === "select-one";
+
+ // Nothing was selected
+ if ( index < 0 ) {
+ return null;
+ }
+
+ // Loop through all the selected options
+ for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
+ var option = options[ i ];
+
+ // Don't return options that are disabled or in a disabled optgroup
+ if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
+ (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
+
+ // Get the specific value for the option
+ value = jQuery( option ).val();
+
+ // We don't need an array for one selects
+ if ( one ) {
+ return value;
+ }
+
+ // Multi-Selects return an array
+ values.push( value );
+ }
+ }
+
+ // Fixes Bug #2551 -- select.val() broken in IE after form.reset()
+ if ( one && !values.length && options.length ) {
+ return jQuery( options[ index ] ).val();
+ }
+
+ return values;
+ },
+
+ set: function( elem, value ) {
+ var values = jQuery.makeArray( value );
+
+ jQuery(elem).find("option").each(function() {
+ this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
+ });
+
+ if ( !values.length ) {
+ elem.selectedIndex = -1;
+ }
+ return values;
+ }
+ }
+ },
+
+ attrFn: {
+ val: true,
+ css: true,
+ html: true,
+ text: true,
+ data: true,
+ width: true,
+ height: true,
+ offset: true
+ },
+
+ attrFix: {
+ // Always normalize to ensure hook usage
+ tabindex: "tabIndex"
+ },
+
+ attr: function( elem, name, value, pass ) {
+ var nType = elem.nodeType;
+
+ // don't get/set attributes on text, comment and attribute nodes
+ if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
+ return undefined;
+ }
+
+ if ( pass && name in jQuery.attrFn ) {
+ return jQuery( elem )[ name ]( value );
+ }
+
+ // Fallback to prop when attributes are not supported
+ if ( !("getAttribute" in elem) ) {
+ return jQuery.prop( elem, name, value );
+ }
+
+ var ret, hooks,
+ notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
+
+ // Normalize the name if needed
+ if ( notxml ) {
+ name = jQuery.attrFix[ name ] || name;
+
+ hooks = jQuery.attrHooks[ name ];
+
+ if ( !hooks ) {
+ // Use boolHook for boolean attributes
+ if ( rboolean.test( name ) ) {
+ hooks = boolHook;
+
+ // Use nodeHook if available( IE6/7 )
+ } else if ( nodeHook ) {
+ hooks = nodeHook;
+ }
+ }
+ }
+
+ if ( value !== undefined ) {
+
+ if ( value === null ) {
+ jQuery.removeAttr( elem, name );
+ return undefined;
+
+ } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
+ return ret;
+
+ } else {
+ elem.setAttribute( name, "" + value );
+ return value;
+ }
+
+ } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
+ return ret;
+
+ } else {
+
+ ret = elem.getAttribute( name );
+
+ // Non-existent attributes return null, we normalize to undefined
+ return ret === null ?
+ undefined :
+ ret;
+ }
+ },
+
+ removeAttr: function( elem, name ) {
+ var propName;
+ if ( elem.nodeType === 1 ) {
+ name = jQuery.attrFix[ name ] || name;
+
+ jQuery.attr( elem, name, "" );
+ elem.removeAttribute( name );
+
+ // Set corresponding property to false for boolean attributes
+ if ( rboolean.test( name ) && (propName = jQuery.propFix[ name ] || name) in elem ) {
+ elem[ propName ] = false;
+ }
+ }
+ },
+
+ attrHooks: {
+ type: {
+ set: function( elem, value ) {
+ // We can't allow the type property to be changed (since it causes problems in IE)
+ if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
+ jQuery.error( "type property can't be changed" );
+ } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
+ // Setting the type on a radio button after the value resets the value in IE6-9
+ // Reset value to it's default in case type is set after value
+ // This is for element creation
+ var val = elem.value;
+ elem.setAttribute( "type", value );
+ if ( val ) {
+ elem.value = val;
+ }
+ return value;
+ }
+ }
+ },
+ // Use the value property for back compat
+ // Use the nodeHook for button elements in IE6/7 (#1954)
+ value: {
+ get: function( elem, name ) {
+ if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
+ return nodeHook.get( elem, name );
+ }
+ return name in elem ?
+ elem.value :
+ null;
+ },
+ set: function( elem, value, name ) {
+ if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
+ return nodeHook.set( elem, value, name );
+ }
+ // Does not return so that setAttribute is also used
+ elem.value = value;
+ }
+ }
+ },
+
+ propFix: {
+ tabindex: "tabIndex",
+ readonly: "readOnly",
+ "for": "htmlFor",
+ "class": "className",
+ maxlength: "maxLength",
+ cellspacing: "cellSpacing",
+ cellpadding: "cellPadding",
+ rowspan: "rowSpan",
+ colspan: "colSpan",
+ usemap: "useMap",
+ frameborder: "frameBorder",
+ contenteditable: "contentEditable"
+ },
+
+ prop: function( elem, name, value ) {
+ var nType = elem.nodeType;
+
+ // don't get/set properties on text, comment and attribute nodes
+ if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
+ return undefined;
+ }
+
+ var ret, hooks,
+ notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
+
+ if ( notxml ) {
+ // Fix name and attach hooks
+ name = jQuery.propFix[ name ] || name;
+ hooks = jQuery.propHooks[ name ];
+ }
+
+ if ( value !== undefined ) {
+ if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
+ return ret;
+
+ } else {
+ return (elem[ name ] = value);
+ }
+
+ } else {
+ if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
+ return ret;
+
+ } else {
+ return elem[ name ];
+ }
+ }
+ },
+
+ propHooks: {
+ tabIndex: {
+ get: function( elem ) {
+ // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
+ // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
+ var attributeNode = elem.getAttributeNode("tabindex");
+
+ return attributeNode && attributeNode.specified ?
+ parseInt( attributeNode.value, 10 ) :
+ rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
+ 0 :
+ undefined;
+ }
+ }
+ }
+});
+
+// Add the tabindex propHook to attrHooks for back-compat
+jQuery.attrHooks.tabIndex = jQuery.propHooks.tabIndex;
+
+// Hook for boolean attributes
+boolHook = {
+ get: function( elem, name ) {
+ // Align boolean attributes with corresponding properties
+ // Fall back to attribute presence where some booleans are not supported
+ var attrNode;
+ return jQuery.prop( elem, name ) === true || ( attrNode = elem.getAttributeNode( name ) ) && attrNode.nodeValue !== false ?
+ name.toLowerCase() :
+ undefined;
+ },
+ set: function( elem, value, name ) {
+ var propName;
+ if ( value === false ) {
+ // Remove boolean attributes when set to false
+ jQuery.removeAttr( elem, name );
+ } else {
+ // value is true since we know at this point it's type boolean and not false
+ // Set boolean attributes to the same name and set the DOM property
+ propName = jQuery.propFix[ name ] || name;
+ if ( propName in elem ) {
+ // Only set the IDL specifically if it already exists on the element
+ elem[ propName ] = true;
+ }
+
+ elem.setAttribute( name, name.toLowerCase() );
+ }
+ return name;
+ }
+};
+
+// IE6/7 do not support getting/setting some attributes with get/setAttribute
+if ( !jQuery.support.getSetAttribute ) {
+
+ // Use this for any attribute in IE6/7
+ // This fixes almost every IE6/7 issue
+ nodeHook = jQuery.valHooks.button = {
+ get: function( elem, name ) {
+ var ret;
+ ret = elem.getAttributeNode( name );
+ // Return undefined if nodeValue is empty string
+ return ret && ret.nodeValue !== "" ?
+ ret.nodeValue :
+ undefined;
+ },
+ set: function( elem, value, name ) {
+ // Set the existing or create a new attribute node
+ var ret = elem.getAttributeNode( name );
+ if ( !ret ) {
+ ret = document.createAttribute( name );
+ elem.setAttributeNode( ret );
+ }
+ return (ret.nodeValue = value + "");
+ }
+ };
+
+ // Set width and height to auto instead of 0 on empty string( Bug #8150 )
+ // This is for removals
+ jQuery.each([ "width", "height" ], function( i, name ) {
+ jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
+ set: function( elem, value ) {
+ if ( value === "" ) {
+ elem.setAttribute( name, "auto" );
+ return value;
+ }
+ }
+ });
+ });
+}
+
+
+// Some attributes require a special call on IE
+if ( !jQuery.support.hrefNormalized ) {
+ jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
+ jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
+ get: function( elem ) {
+ var ret = elem.getAttribute( name, 2 );
+ return ret === null ? undefined : ret;
+ }
+ });
+ });
+}
+
+if ( !jQuery.support.style ) {
+ jQuery.attrHooks.style = {
+ get: function( elem ) {
+ // Return undefined in the case of empty string
+ // Normalize to lowercase since IE uppercases css property names
+ return elem.style.cssText.toLowerCase() || undefined;
+ },
+ set: function( elem, value ) {
+ return (elem.style.cssText = "" + value);
+ }
+ };
+}
+
+// Safari mis-reports the default selected property of an option
+// Accessing the parent's selectedIndex property fixes it
+if ( !jQuery.support.optSelected ) {
+ jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
+ get: function( elem ) {
+ var parent = elem.parentNode;
+
+ if ( parent ) {
+ parent.selectedIndex;
+
+ // Make sure that it also works with optgroups, see #5701
+ if ( parent.parentNode ) {
+ parent.parentNode.selectedIndex;
+ }
+ }
+ return null;
+ }
+ });
+}
+
+// Radios and checkboxes getter/setter
+if ( !jQuery.support.checkOn ) {
+ jQuery.each([ "radio", "checkbox" ], function() {
+ jQuery.valHooks[ this ] = {
+ get: function( elem ) {
+ // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
+ return elem.getAttribute("value") === null ? "on" : elem.value;
+ }
+ };
+ });
+}
+jQuery.each([ "radio", "checkbox" ], function() {
+ jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
+ set: function( elem, value ) {
+ if ( jQuery.isArray( value ) ) {
+ return (elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0);
+ }
+ }
+ });
+});
+
+
+
+
+var rnamespaces = /\.(.*)$/,
+ rformElems = /^(?:textarea|input|select)$/i,
+ rperiod = /\./g,
+ rspaces = / /g,
+ rescape = /[^\w\s.|`]/g,
+ fcleanup = function( nm ) {
+ return nm.replace(rescape, "\\$&");
+ };
+
+/*
+ * A number of helper functions used for managing events.
+ * Many of the ideas behind this code originated from
+ * Dean Edwards' addEvent library.
+ */
+jQuery.event = {
+
+ // Bind an event to an element
+ // Original by Dean Edwards
+ add: function( elem, types, handler, data ) {
+ if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+ return;
+ }
+
+ if ( handler === false ) {
+ handler = returnFalse;
+ } else if ( !handler ) {
+ // Fixes bug #7229. Fix recommended by jdalton
+ return;
+ }
+
+ var handleObjIn, handleObj;
+
+ if ( handler.handler ) {
+ handleObjIn = handler;
+ handler = handleObjIn.handler;
+ }
+
+ // Make sure that the function being executed has a unique ID
+ if ( !handler.guid ) {
+ handler.guid = jQuery.guid++;
+ }
+
+ // Init the element's event structure
+ var elemData = jQuery._data( elem );
+
+ // If no elemData is found then we must be trying to bind to one of the
+ // banned noData elements
+ if ( !elemData ) {
+ return;
+ }
+
+ var events = elemData.events,
+ eventHandle = elemData.handle;
+
+ if ( !events ) {
+ elemData.events = events = {};
+ }
+
+ if ( !eventHandle ) {
+ elemData.handle = eventHandle = function( e ) {
+ // Discard the second event of a jQuery.event.trigger() and
+ // when an event is called after a page has unloaded
+ return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
+ jQuery.event.handle.apply( eventHandle.elem, arguments ) :
+ undefined;
+ };
+ }
+
+ // Add elem as a property of the handle function
+ // This is to prevent a memory leak with non-native events in IE.
+ eventHandle.elem = elem;
+
+ // Handle multiple events separated by a space
+ // jQuery(...).bind("mouseover mouseout", fn);
+ types = types.split(" ");
+
+ var type, i = 0, namespaces;
+
+ while ( (type = types[ i++ ]) ) {
+ handleObj = handleObjIn ?
+ jQuery.extend({}, handleObjIn) :
+ { handler: handler, data: data };
+
+ // Namespaced event handlers
+ if ( type.indexOf(".") > -1 ) {
+ namespaces = type.split(".");
+ type = namespaces.shift();
+ handleObj.namespace = namespaces.slice(0).sort().join(".");
+
+ } else {
+ namespaces = [];
+ handleObj.namespace = "";
+ }
+
+ handleObj.type = type;
+ if ( !handleObj.guid ) {
+ handleObj.guid = handler.guid;
+ }
+
+ // Get the current list of functions bound to this event
+ var handlers = events[ type ],
+ special = jQuery.event.special[ type ] || {};
+
+ // Init the event handler queue
+ if ( !handlers ) {
+ handlers = events[ type ] = [];
+
+ // Check for a special event handler
+ // Only use addEventListener/attachEvent if the special
+ // events handler returns false
+ if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
+ // Bind the global event handler to the element
+ if ( elem.addEventListener ) {
+ elem.addEventListener( type, eventHandle, false );
+
+ } else if ( elem.attachEvent ) {
+ elem.attachEvent( "on" + type, eventHandle );
+ }
+ }
+ }
+
+ if ( special.add ) {
+ special.add.call( elem, handleObj );
+
+ if ( !handleObj.handler.guid ) {
+ handleObj.handler.guid = handler.guid;
+ }
+ }
+
+ // Add the function to the element's handler list
+ handlers.push( handleObj );
+
+ // Keep track of which events have been used, for event optimization
+ jQuery.event.global[ type ] = true;
+ }
+
+ // Nullify elem to prevent memory leaks in IE
+ elem = null;
+ },
+
+ global: {},
+
+ // Detach an event or set of events from an element
+ remove: function( elem, types, handler, pos ) {
+ // don't do events on text and comment nodes
+ if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+ return;
+ }
+
+ if ( handler === false ) {
+ handler = returnFalse;
+ }
+
+ var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
+ elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
+ events = elemData && elemData.events;
+
+ if ( !elemData || !events ) {
+ return;
+ }
+
+ // types is actually an event object here
+ if ( types && types.type ) {
+ handler = types.handler;
+ types = types.type;
+ }
+
+ // Unbind all events for the element
+ if ( !types || typeof types === "string" && types.charAt(0) === "." ) {
+ types = types || "";
+
+ for ( type in events ) {
+ jQuery.event.remove( elem, type + types );
+ }
+
+ return;
+ }
+
+ // Handle multiple events separated by a space
+ // jQuery(...).unbind("mouseover mouseout", fn);
+ types = types.split(" ");
+
+ while ( (type = types[ i++ ]) ) {
+ origType = type;
+ handleObj = null;
+ all = type.indexOf(".") < 0;
+ namespaces = [];
+
+ if ( !all ) {
+ // Namespaced event handlers
+ namespaces = type.split(".");
+ type = namespaces.shift();
+
+ namespace = new RegExp("(^|\\.)" +
+ jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");
+ }
+
+ eventType = events[ type ];
+
+ if ( !eventType ) {
+ continue;
+ }
+
+ if ( !handler ) {
+ for ( j = 0; j < eventType.length; j++ ) {
+ handleObj = eventType[ j ];
+
+ if ( all || namespace.test( handleObj.namespace ) ) {
+ jQuery.event.remove( elem, origType, handleObj.handler, j );
+ eventType.splice( j--, 1 );
+ }
+ }
+
+ continue;
+ }
+
+ special = jQuery.event.special[ type ] || {};
+
+ for ( j = pos || 0; j < eventType.length; j++ ) {
+ handleObj = eventType[ j ];
+
+ if ( handler.guid === handleObj.guid ) {
+ // remove the given handler for the given type
+ if ( all || namespace.test( handleObj.namespace ) ) {
+ if ( pos == null ) {
+ eventType.splice( j--, 1 );
+ }
+
+ if ( special.remove ) {
+ special.remove.call( elem, handleObj );
+ }
+ }
+
+ if ( pos != null ) {
+ break;
+ }
+ }
+ }
+
+ // remove generic event handler if no more handlers exist
+ if ( eventType.length === 0 || pos != null && eventType.length === 1 ) {
+ if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
+ jQuery.removeEvent( elem, type, elemData.handle );
+ }
+
+ ret = null;
+ delete events[ type ];
+ }
+ }
+
+ // Remove the expando if it's no longer used
+ if ( jQuery.isEmptyObject( events ) ) {
+ var handle = elemData.handle;
+ if ( handle ) {
+ handle.elem = null;
+ }
+
+ delete elemData.events;
+ delete elemData.handle;
+
+ if ( jQuery.isEmptyObject( elemData ) ) {
+ jQuery.removeData( elem, undefined, true );
+ }
+ }
+ },
+
+ // Events that are safe to short-circuit if no handlers are attached.
+ // Native DOM events should not be added, they may have inline handlers.
+ customEvent: {
+ "getData": true,
+ "setData": true,
+ "changeData": true
+ },
+
+ trigger: function( event, data, elem, onlyHandlers ) {
+ // Event object or event type
+ var type = event.type || event,
+ namespaces = [],
+ exclusive;
+
+ if ( type.indexOf("!") >= 0 ) {
+ // Exclusive events trigger only for the exact event (no namespaces)
+ type = type.slice(0, -1);
+ exclusive = true;
+ }
+
+ if ( type.indexOf(".") >= 0 ) {
+ // Namespaced trigger; create a regexp to match event type in handle()
+ namespaces = type.split(".");
+ type = namespaces.shift();
+ namespaces.sort();
+ }
+
+ if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
+ // No jQuery handlers for this event type, and it can't have inline handlers
+ return;
+ }
+
+ // Caller can pass in an Event, Object, or just an event type string
+ event = typeof event === "object" ?
+ // jQuery.Event object
+ event[ jQuery.expando ] ? event :
+ // Object literal
+ new jQuery.Event( type, event ) :
+ // Just the event type (string)
+ new jQuery.Event( type );
+
+ event.type = type;
+ event.exclusive = exclusive;
+ event.namespace = namespaces.join(".");
+ event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)");
+
+ // triggerHandler() and global events don't bubble or run the default action
+ if ( onlyHandlers || !elem ) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+
+ // Handle a global trigger
+ if ( !elem ) {
+ // TODO: Stop taunting the data cache; remove global events and always attach to document
+ jQuery.each( jQuery.cache, function() {
+ // internalKey variable is just used to make it easier to find
+ // and potentially change this stuff later; currently it just
+ // points to jQuery.expando
+ var internalKey = jQuery.expando,
+ internalCache = this[ internalKey ];
+ if ( internalCache && internalCache.events && internalCache.events[ type ] ) {
+ jQuery.event.trigger( event, data, internalCache.handle.elem );
+ }
+ });
+ return;
+ }
+
+ // Don't do events on text and comment nodes
+ if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+ return;
+ }
+
+ // Clean up the event in case it is being reused
+ event.result = undefined;
+ event.target = elem;
+
+ // Clone any incoming data and prepend the event, creating the handler arg list
+ data = data != null ? jQuery.makeArray( data ) : [];
+ data.unshift( event );
+
+ var cur = elem,
+ // IE doesn't like method names with a colon (#3533, #8272)
+ ontype = type.indexOf(":") < 0 ? "on" + type : "";
+
+ // Fire event on the current element, then bubble up the DOM tree
+ do {
+ var handle = jQuery._data( cur, "handle" );
+
+ event.currentTarget = cur;
+ if ( handle ) {
+ handle.apply( cur, data );
+ }
+
+ // Trigger an inline bound script
+ if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) {
+ event.result = false;
+ event.preventDefault();
+ }
+
+ // Bubble up to document, then to window
+ cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window;
+ } while ( cur && !event.isPropagationStopped() );
+
+ // If nobody prevented the default action, do it now
+ if ( !event.isDefaultPrevented() ) {
+ var old,
+ special = jQuery.event.special[ type ] || {};
+
+ if ( (!special._default || special._default.call( elem.ownerDocument, event ) === false) &&
+ !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
+
+ // Call a native DOM method on the target with the same name name as the event.
+ // Can't use an .isFunction)() check here because IE6/7 fails that test.
+ // IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch.
+ try {
+ if ( ontype && elem[ type ] ) {
+ // Don't re-trigger an onFOO event when we call its FOO() method
+ old = elem[ ontype ];
+
+ if ( old ) {
+ elem[ ontype ] = null;
+ }
+
+ jQuery.event.triggered = type;
+ elem[ type ]();
+ }
+ } catch ( ieError ) {}
+
+ if ( old ) {
+ elem[ ontype ] = old;
+ }
+
+ jQuery.event.triggered = undefined;
+ }
+ }
+
+ return event.result;
+ },
+
+ handle: function( event ) {
+ event = jQuery.event.fix( event || window.event );
+ // Snapshot the handlers list since a called handler may add/remove events.
+ var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0),
+ run_all = !event.exclusive && !event.namespace,
+ args = Array.prototype.slice.call( arguments, 0 );
+
+ // Use the fix-ed Event rather than the (read-only) native event
+ args[0] = event;
+ event.currentTarget = this;
+
+ for ( var j = 0, l = handlers.length; j < l; j++ ) {
+ var handleObj = handlers[ j ];
+
+ // Triggered event must 1) be non-exclusive and have no namespace, or
+ // 2) have namespace(s) a subset or equal to those in the bound event.
+ if ( run_all || event.namespace_re.test( handleObj.namespace ) ) {
+ // Pass in a reference to the handler function itself
+ // So that we can later remove it
+ event.handler = handleObj.handler;
+ event.data = handleObj.data;
+ event.handleObj = handleObj;
+
+ var ret = handleObj.handler.apply( this, args );
+
+ if ( ret !== undefined ) {
+ event.result = ret;
+ if ( ret === false ) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ }
+
+ if ( event.isImmediatePropagationStopped() ) {
+ break;
+ }
+ }
+ }
+ return event.result;
+ },
+
+ props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
+
+ fix: function( event ) {
+ if ( event[ jQuery.expando ] ) {
+ return event;
+ }
+
+ // store a copy of the original event object
+ // and "clone" to set read-only properties
+ var originalEvent = event;
+ event = jQuery.Event( originalEvent );
+
+ for ( var i = this.props.length, prop; i; ) {
+ prop = this.props[ --i ];
+ event[ prop ] = originalEvent[ prop ];
+ }
+
+ // Fix target property, if necessary
+ if ( !event.target ) {
+ // Fixes #1925 where srcElement might not be defined either
+ event.target = event.srcElement || document;
+ }
+
+ // check if target is a textnode (safari)
+ if ( event.target.nodeType === 3 ) {
+ event.target = event.target.parentNode;
+ }
+
+ // Add relatedTarget, if necessary
+ if ( !event.relatedTarget && event.fromElement ) {
+ event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
+ }
+
+ // Calculate pageX/Y if missing and clientX/Y available
+ if ( event.pageX == null && event.clientX != null ) {
+ var eventDocument = event.target.ownerDocument || document,
+ doc = eventDocument.documentElement,
+ body = eventDocument.body;
+
+ event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
+ event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
+ }
+
+ // Add which for key events
+ if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
+ event.which = event.charCode != null ? event.charCode : event.keyCode;
+ }
+
+ // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
+ if ( !event.metaKey && event.ctrlKey ) {
+ event.metaKey = event.ctrlKey;
+ }
+
+ // Add which for click: 1 === left; 2 === middle; 3 === right
+ // Note: button is not normalized, so don't use it
+ if ( !event.which && event.button !== undefined ) {
+ event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
+ }
+
+ return event;
+ },
+
+ // Deprecated, use jQuery.guid instead
+ guid: 1E8,
+
+ // Deprecated, use jQuery.proxy instead
+ proxy: jQuery.proxy,
+
+ special: {
+ ready: {
+ // Make sure the ready event is setup
+ setup: jQuery.bindReady,
+ teardown: jQuery.noop
+ },
+
+ live: {
+ add: function( handleObj ) {
+ jQuery.event.add( this,
+ liveConvert( handleObj.origType, handleObj.selector ),
+ jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) );
+ },
+
+ remove: function( handleObj ) {
+ jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj );
+ }
+ },
+
+ beforeunload: {
+ setup: function( data, namespaces, eventHandle ) {
+ // We only want to do this special case on windows
+ if ( jQuery.isWindow( this ) ) {
+ this.onbeforeunload = eventHandle;
+ }
+ },
+
+ teardown: function( namespaces, eventHandle ) {
+ if ( this.onbeforeunload === eventHandle ) {
+ this.onbeforeunload = null;
+ }
+ }
+ }
+ }
+};
+
+jQuery.removeEvent = document.removeEventListener ?
+ function( elem, type, handle ) {
+ if ( elem.removeEventListener ) {
+ elem.removeEventListener( type, handle, false );
+ }
+ } :
+ function( elem, type, handle ) {
+ if ( elem.detachEvent ) {
+ elem.detachEvent( "on" + type, handle );
+ }
+ };
+
+jQuery.Event = function( src, props ) {
+ // Allow instantiation without the 'new' keyword
+ if ( !this.preventDefault ) {
+ return new jQuery.Event( src, props );
+ }
+
+ // Event object
+ if ( src && src.type ) {
+ this.originalEvent = src;
+ this.type = src.type;
+
+ // Events bubbling up the document may have been marked as prevented
+ // by a handler lower down the tree; reflect the correct value.
+ this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false ||
+ src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse;
+
+ // Event type
+ } else {
+ this.type = src;
+ }
+
+ // Put explicitly provided properties onto the event object
+ if ( props ) {
+ jQuery.extend( this, props );
+ }
+
+ // timeStamp is buggy for some events on Firefox(#3843)
+ // So we won't rely on the native value
+ this.timeStamp = jQuery.now();
+
+ // Mark it as fixed
+ this[ jQuery.expando ] = true;
+};
+
+function returnFalse() {
+ return false;
+}
+function returnTrue() {
+ return true;
+}
+
+// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
+// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
+jQuery.Event.prototype = {
+ preventDefault: function() {
+ this.isDefaultPrevented = returnTrue;
+
+ var e = this.originalEvent;
+ if ( !e ) {
+ return;
+ }
+
+ // if preventDefault exists run it on the original event
+ if ( e.preventDefault ) {
+ e.preventDefault();
+
+ // otherwise set the returnValue property of the original event to false (IE)
+ } else {
+ e.returnValue = false;
+ }
+ },
+ stopPropagation: function() {
+ this.isPropagationStopped = returnTrue;
+
+ var e = this.originalEvent;
+ if ( !e ) {
+ return;
+ }
+ // if stopPropagation exists run it on the original event
+ if ( e.stopPropagation ) {
+ e.stopPropagation();
+ }
+ // otherwise set the cancelBubble property of the original event to true (IE)
+ e.cancelBubble = true;
+ },
+ stopImmediatePropagation: function() {
+ this.isImmediatePropagationStopped = returnTrue;
+ this.stopPropagation();
+ },
+ isDefaultPrevented: returnFalse,
+ isPropagationStopped: returnFalse,
+ isImmediatePropagationStopped: returnFalse
+};
+
+// Checks if an event happened on an element within another element
+// Used in jQuery.event.special.mouseenter and mouseleave handlers
+var withinElement = function( event ) {
+
+ // Check if mouse(over|out) are still within the same parent element
+ var related = event.relatedTarget,
+ inside = false,
+ eventType = event.type;
+
+ event.type = event.data;
+
+ if ( related !== this ) {
+
+ if ( related ) {
+ inside = jQuery.contains( this, related );
+ }
+
+ if ( !inside ) {
+
+ jQuery.event.handle.apply( this, arguments );
+
+ event.type = eventType;
+ }
+ }
+},
+
+// In case of event delegation, we only need to rename the event.type,
+// liveHandler will take care of the rest.
+delegate = function( event ) {
+ event.type = event.data;
+ jQuery.event.handle.apply( this, arguments );
+};
+
+// Create mouseenter and mouseleave events
+jQuery.each({
+ mouseenter: "mouseover",
+ mouseleave: "mouseout"
+}, function( orig, fix ) {
+ jQuery.event.special[ orig ] = {
+ setup: function( data ) {
+ jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig );
+ },
+ teardown: function( data ) {
+ jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement );
+ }
+ };
+});
+
+// submit delegation
+if ( !jQuery.support.submitBubbles ) {
+
+ jQuery.event.special.submit = {
+ setup: function( data, namespaces ) {
+ if ( !jQuery.nodeName( this, "form" ) ) {
+ jQuery.event.add(this, "click.specialSubmit", function( e ) {
+ var elem = e.target,
+ type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
+
+ if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) {
+ trigger( "submit", this, arguments );
+ }
+ });
+
+ jQuery.event.add(this, "keypress.specialSubmit", function( e ) {
+ var elem = e.target,
+ type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
+
+ if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) {
+ trigger( "submit", this, arguments );
+ }
+ });
+
+ } else {
+ return false;
+ }
+ },
+
+ teardown: function( namespaces ) {
+ jQuery.event.remove( this, ".specialSubmit" );
+ }
+ };
+
+}
+
+// change delegation, happens here so we have bind.
+if ( !jQuery.support.changeBubbles ) {
+
+ var changeFilters,
+
+ getVal = function( elem ) {
+ var type = jQuery.nodeName( elem, "input" ) ? elem.type : "",
+ val = elem.value;
+
+ if ( type === "radio" || type === "checkbox" ) {
+ val = elem.checked;
+
+ } else if ( type === "select-multiple" ) {
+ val = elem.selectedIndex > -1 ?
+ jQuery.map( elem.options, function( elem ) {
+ return elem.selected;
+ }).join("-") :
+ "";
+
+ } else if ( jQuery.nodeName( elem, "select" ) ) {
+ val = elem.selectedIndex;
+ }
+
+ return val;
+ },
+
+ testChange = function testChange( e ) {
+ var elem = e.target, data, val;
+
+ if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) {
+ return;
+ }
+
+ data = jQuery._data( elem, "_change_data" );
+ val = getVal(elem);
+
+ // the current data will be also retrieved by beforeactivate
+ if ( e.type !== "focusout" || elem.type !== "radio" ) {
+ jQuery._data( elem, "_change_data", val );
+ }
+
+ if ( data === undefined || val === data ) {
+ return;
+ }
+
+ if ( data != null || val ) {
+ e.type = "change";
+ e.liveFired = undefined;
+ jQuery.event.trigger( e, arguments[1], elem );
+ }
+ };
+
+ jQuery.event.special.change = {
+ filters: {
+ focusout: testChange,
+
+ beforedeactivate: testChange,
+
+ click: function( e ) {
+ var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
+
+ if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) {
+ testChange.call( this, e );
+ }
+ },
+
+ // Change has to be called before submit
+ // Keydown will be called before keypress, which is used in submit-event delegation
+ keydown: function( e ) {
+ var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
+
+ if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) ||
+ (e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
+ type === "select-multiple" ) {
+ testChange.call( this, e );
+ }
+ },
+
+ // Beforeactivate happens also before the previous element is blurred
+ // with this event you can't trigger a change event, but you can store
+ // information
+ beforeactivate: function( e ) {
+ var elem = e.target;
+ jQuery._data( elem, "_change_data", getVal(elem) );
+ }
+ },
+
+ setup: function( data, namespaces ) {
+ if ( this.type === "file" ) {
+ return false;
+ }
+
+ for ( var type in changeFilters ) {
+ jQuery.event.add( this, type + ".specialChange", changeFilters[type] );
+ }
+
+ return rformElems.test( this.nodeName );
+ },
+
+ teardown: function( namespaces ) {
+ jQuery.event.remove( this, ".specialChange" );
+
+ return rformElems.test( this.nodeName );
+ }
+ };
+
+ changeFilters = jQuery.event.special.change.filters;
+
+ // Handle when the input is .focus()'d
+ changeFilters.focus = changeFilters.beforeactivate;
+}
+
+function trigger( type, elem, args ) {
+ // Piggyback on a donor event to simulate a different one.
+ // Fake originalEvent to avoid donor's stopPropagation, but if the
+ // simulated event prevents default then we do the same on the donor.
+ // Don't pass args or remember liveFired; they apply to the donor event.
+ var event = jQuery.extend( {}, args[ 0 ] );
+ event.type = type;
+ event.originalEvent = {};
+ event.liveFired = undefined;
+ jQuery.event.handle.call( elem, event );
+ if ( event.isDefaultPrevented() ) {
+ args[ 0 ].preventDefault();
+ }
+}
+
+// Create "bubbling" focus and blur events
+if ( !jQuery.support.focusinBubbles ) {
+ jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
+
+ // Attach a single capturing handler while someone wants focusin/focusout
+ var attaches = 0;
+
+ jQuery.event.special[ fix ] = {
+ setup: function() {
+ if ( attaches++ === 0 ) {
+ document.addEventListener( orig, handler, true );
+ }
+ },
+ teardown: function() {
+ if ( --attaches === 0 ) {
+ document.removeEventListener( orig, handler, true );
+ }
+ }
+ };
+
+ function handler( donor ) {
+ // Donor event is always a native one; fix it and switch its type.
+ // Let focusin/out handler cancel the donor focus/blur event.
+ var e = jQuery.event.fix( donor );
+ e.type = fix;
+ e.originalEvent = {};
+ jQuery.event.trigger( e, null, e.target );
+ if ( e.isDefaultPrevented() ) {
+ donor.preventDefault();
+ }
+ }
+ });
+}
+
+jQuery.each(["bind", "one"], function( i, name ) {
+ jQuery.fn[ name ] = function( type, data, fn ) {
+ var handler;
+
+ // Handle object literals
+ if ( typeof type === "object" ) {
+ for ( var key in type ) {
+ this[ name ](key, data, type[key], fn);
+ }
+ return this;
+ }
+
+ if ( arguments.length === 2 || data === false ) {
+ fn = data;
+ data = undefined;
+ }
+
+ if ( name === "one" ) {
+ handler = function( event ) {
+ jQuery( this ).unbind( event, handler );
+ return fn.apply( this, arguments );
+ };
+ handler.guid = fn.guid || jQuery.guid++;
+ } else {
+ handler = fn;
+ }
+
+ if ( type === "unload" && name !== "one" ) {
+ this.one( type, data, fn );
+
+ } else {
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ jQuery.event.add( this[i], type, handler, data );
+ }
+ }
+
+ return this;
+ };
+});
+
+jQuery.fn.extend({
+ unbind: function( type, fn ) {
+ // Handle object literals
+ if ( typeof type === "object" && !type.preventDefault ) {
+ for ( var key in type ) {
+ this.unbind(key, type[key]);
+ }
+
+ } else {
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ jQuery.event.remove( this[i], type, fn );
+ }
+ }
+
+ return this;
+ },
+
+ delegate: function( selector, types, data, fn ) {
+ return this.live( types, data, fn, selector );
+ },
+
+ undelegate: function( selector, types, fn ) {
+ if ( arguments.length === 0 ) {
+ return this.unbind( "live" );
+
+ } else {
+ return this.die( types, null, fn, selector );
+ }
+ },
+
+ trigger: function( type, data ) {
+ return this.each(function() {
+ jQuery.event.trigger( type, data, this );
+ });
+ },
+
+ triggerHandler: function( type, data ) {
+ if ( this[0] ) {
+ return jQuery.event.trigger( type, data, this[0], true );
+ }
+ },
+
+ toggle: function( fn ) {
+ // Save reference to arguments for access in closure
+ var args = arguments,
+ guid = fn.guid || jQuery.guid++,
+ i = 0,
+ toggler = function( event ) {
+ // Figure out which function to execute
+ var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i;
+ jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 );
+
+ // Make sure that clicks stop
+ event.preventDefault();
+
+ // and execute the function
+ return args[ lastToggle ].apply( this, arguments ) || false;
+ };
+
+ // link all the functions, so any of them can unbind this click handler
+ toggler.guid = guid;
+ while ( i < args.length ) {
+ args[ i++ ].guid = guid;
+ }
+
+ return this.click( toggler );
+ },
+
+ hover: function( fnOver, fnOut ) {
+ return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
+ }
+});
+
+var liveMap = {
+ focus: "focusin",
+ blur: "focusout",
+ mouseenter: "mouseover",
+ mouseleave: "mouseout"
+};
+
+jQuery.each(["live", "die"], function( i, name ) {
+ jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) {
+ var type, i = 0, match, namespaces, preType,
+ selector = origSelector || this.selector,
+ context = origSelector ? this : jQuery( this.context );
+
+ if ( typeof types === "object" && !types.preventDefault ) {
+ for ( var key in types ) {
+ context[ name ]( key, data, types[key], selector );
+ }
+
+ return this;
+ }
+
+ if ( name === "die" && !types &&
+ origSelector && origSelector.charAt(0) === "." ) {
+
+ context.unbind( origSelector );
+
+ return this;
+ }
+
+ if ( data === false || jQuery.isFunction( data ) ) {
+ fn = data || returnFalse;
+ data = undefined;
+ }
+
+ types = (types || "").split(" ");
+
+ while ( (type = types[ i++ ]) != null ) {
+ match = rnamespaces.exec( type );
+ namespaces = "";
+
+ if ( match ) {
+ namespaces = match[0];
+ type = type.replace( rnamespaces, "" );
+ }
+
+ if ( type === "hover" ) {
+ types.push( "mouseenter" + namespaces, "mouseleave" + namespaces );
+ continue;
+ }
+
+ preType = type;
+
+ if ( liveMap[ type ] ) {
+ types.push( liveMap[ type ] + namespaces );
+ type = type + namespaces;
+
+ } else {
+ type = (liveMap[ type ] || type) + namespaces;
+ }
+
+ if ( name === "live" ) {
+ // bind live handler
+ for ( var j = 0, l = context.length; j < l; j++ ) {
+ jQuery.event.add( context[j], "live." + liveConvert( type, selector ),
+ { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } );
+ }
+
+ } else {
+ // unbind live handler
+ context.unbind( "live." + liveConvert( type, selector ), fn );
+ }
+ }
+
+ return this;
+ };
+});
+
+function liveHandler( event ) {
+ var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret,
+ elems = [],
+ selectors = [],
+ events = jQuery._data( this, "events" );
+
+ // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911)
+ if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) {
+ return;
+ }
+
+ if ( event.namespace ) {
+ namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)");
+ }
+
+ event.liveFired = this;
+
+ var live = events.live.slice(0);
+
+ for ( j = 0; j < live.length; j++ ) {
+ handleObj = live[j];
+
+ if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) {
+ selectors.push( handleObj.selector );
+
+ } else {
+ live.splice( j--, 1 );
+ }
+ }
+
+ match = jQuery( event.target ).closest( selectors, event.currentTarget );
+
+ for ( i = 0, l = match.length; i < l; i++ ) {
+ close = match[i];
+
+ for ( j = 0; j < live.length; j++ ) {
+ handleObj = live[j];
+
+ if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) {
+ elem = close.elem;
+ related = null;
+
+ // Those two events require additional checking
+ if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) {
+ event.type = handleObj.preType;
+ related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0];
+
+ // Make sure not to accidentally match a child element with the same selector
+ if ( related && jQuery.contains( elem, related ) ) {
+ related = elem;
+ }
+ }
+
+ if ( !related || related !== elem ) {
+ elems.push({ elem: elem, handleObj: handleObj, level: close.level });
+ }
+ }
+ }
+ }
+
+ for ( i = 0, l = elems.length; i < l; i++ ) {
+ match = elems[i];
+
+ if ( maxLevel && match.level > maxLevel ) {
+ break;
+ }
+
+ event.currentTarget = match.elem;
+ event.data = match.handleObj.data;
+ event.handleObj = match.handleObj;
+
+ ret = match.handleObj.origHandler.apply( match.elem, arguments );
+
+ if ( ret === false || event.isPropagationStopped() ) {
+ maxLevel = match.level;
+
+ if ( ret === false ) {
+ stop = false;
+ }
+ if ( event.isImmediatePropagationStopped() ) {
+ break;
+ }
+ }
+ }
+
+ return stop;
+}
+
+function liveConvert( type, selector ) {
+ return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&");
+}
+
+jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
+ "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
+ "change select submit keydown keypress keyup error").split(" "), function( i, name ) {
+
+ // Handle event binding
+ jQuery.fn[ name ] = function( data, fn ) {
+ if ( fn == null ) {
+ fn = data;
+ data = null;
+ }
+
+ return arguments.length > 0 ?
+ this.bind( name, data, fn ) :
+ this.trigger( name );
+ };
+
+ if ( jQuery.attrFn ) {
+ jQuery.attrFn[ name ] = true;
+ }
+});
+
+
+
+/*!
+ * Sizzle CSS Selector Engine
+ * Copyright 2011, The Dojo Foundation
+ * Released under the MIT, BSD, and GPL Licenses.
+ * More information: http://sizzlejs.com/
+ */
+(function(){
+
+var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
+ done = 0,
+ toString = Object.prototype.toString,
+ hasDuplicate = false,
+ baseHasDuplicate = true,
+ rBackslash = /\\/g,
+ rNonWord = /\W/;
+
+// Here we check if the JavaScript engine is using some sort of
+// optimization where it does not always call our comparision
+// function. If that is the case, discard the hasDuplicate value.
+// Thus far that includes Google Chrome.
+[0, 0].sort(function() {
+ baseHasDuplicate = false;
+ return 0;
+});
+
+var Sizzle = function( selector, context, results, seed ) {
+ results = results || [];
+ context = context || document;
+
+ var origContext = context;
+
+ if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
+ return [];
+ }
+
+ if ( !selector || typeof selector !== "string" ) {
+ return results;
+ }
+
+ var m, set, checkSet, extra, ret, cur, pop, i,
+ prune = true,
+ contextXML = Sizzle.isXML( context ),
+ parts = [],
+ soFar = selector;
+
+ // Reset the position of the chunker regexp (start from head)
+ do {
+ chunker.exec( "" );
+ m = chunker.exec( soFar );
+
+ if ( m ) {
+ soFar = m[3];
+
+ parts.push( m[1] );
+
+ if ( m[2] ) {
+ extra = m[3];
+ break;
+ }
+ }
+ } while ( m );
+
+ if ( parts.length > 1 && origPOS.exec( selector ) ) {
+
+ if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
+ set = posProcess( parts[0] + parts[1], context );
+
+ } else {
+ set = Expr.relative[ parts[0] ] ?
+ [ context ] :
+ Sizzle( parts.shift(), context );
+
+ while ( parts.length ) {
+ selector = parts.shift();
+
+ if ( Expr.relative[ selector ] ) {
+ selector += parts.shift();
+ }
+
+ set = posProcess( selector, set );
+ }
+ }
+
+ } else {
+ // Take a shortcut and set the context if the root selector is an ID
+ // (but not if it'll be faster if the inner selector is an ID)
+ if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
+ Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
+
+ ret = Sizzle.find( parts.shift(), context, contextXML );
+ context = ret.expr ?
+ Sizzle.filter( ret.expr, ret.set )[0] :
+ ret.set[0];
+ }
+
+ if ( context ) {
+ ret = seed ?
+ { expr: parts.pop(), set: makeArray(seed) } :
+ Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
+
+ set = ret.expr ?
+ Sizzle.filter( ret.expr, ret.set ) :
+ ret.set;
+
+ if ( parts.length > 0 ) {
+ checkSet = makeArray( set );
+
+ } else {
+ prune = false;
+ }
+
+ while ( parts.length ) {
+ cur = parts.pop();
+ pop = cur;
+
+ if ( !Expr.relative[ cur ] ) {
+ cur = "";
+ } else {
+ pop = parts.pop();
+ }
+
+ if ( pop == null ) {
+ pop = context;
+ }
+
+ Expr.relative[ cur ]( checkSet, pop, contextXML );
+ }
+
+ } else {
+ checkSet = parts = [];
+ }
+ }
+
+ if ( !checkSet ) {
+ checkSet = set;
+ }
+
+ if ( !checkSet ) {
+ Sizzle.error( cur || selector );
+ }
+
+ if ( toString.call(checkSet) === "[object Array]" ) {
+ if ( !prune ) {
+ results.push.apply( results, checkSet );
+
+ } else if ( context && context.nodeType === 1 ) {
+ for ( i = 0; checkSet[i] != null; i++ ) {
+ if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
+ results.push( set[i] );
+ }
+ }
+
+ } else {
+ for ( i = 0; checkSet[i] != null; i++ ) {
+ if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
+ results.push( set[i] );
+ }
+ }
+ }
+
+ } else {
+ makeArray( checkSet, results );
+ }
+
+ if ( extra ) {
+ Sizzle( extra, origContext, results, seed );
+ Sizzle.uniqueSort( results );
+ }
+
+ return results;
+};
+
+Sizzle.uniqueSort = function( results ) {
+ if ( sortOrder ) {
+ hasDuplicate = baseHasDuplicate;
+ results.sort( sortOrder );
+
+ if ( hasDuplicate ) {
+ for ( var i = 1; i < results.length; i++ ) {
+ if ( results[i] === results[ i - 1 ] ) {
+ results.splice( i--, 1 );
+ }
+ }
+ }
+ }
+
+ return results;
+};
+
+Sizzle.matches = function( expr, set ) {
+ return Sizzle( expr, null, null, set );
+};
+
+Sizzle.matchesSelector = function( node, expr ) {
+ return Sizzle( expr, null, null, [node] ).length > 0;
+};
+
+Sizzle.find = function( expr, context, isXML ) {
+ var set;
+
+ if ( !expr ) {
+ return [];
+ }
+
+ for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
+ var match,
+ type = Expr.order[i];
+
+ if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
+ var left = match[1];
+ match.splice( 1, 1 );
+
+ if ( left.substr( left.length - 1 ) !== "\\" ) {
+ match[1] = (match[1] || "").replace( rBackslash, "" );
+ set = Expr.find[ type ]( match, context, isXML );
+
+ if ( set != null ) {
+ expr = expr.replace( Expr.match[ type ], "" );
+ break;
+ }
+ }
+ }
+ }
+
+ if ( !set ) {
+ set = typeof context.getElementsByTagName !== "undefined" ?
+ context.getElementsByTagName( "*" ) :
+ [];
+ }
+
+ return { set: set, expr: expr };
+};
+
+Sizzle.filter = function( expr, set, inplace, not ) {
+ var match, anyFound,
+ old = expr,
+ result = [],
+ curLoop = set,
+ isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
+
+ while ( expr && set.length ) {
+ for ( var type in Expr.filter ) {
+ if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
+ var found, item,
+ filter = Expr.filter[ type ],
+ left = match[1];
+
+ anyFound = false;
+
+ match.splice(1,1);
+
+ if ( left.substr( left.length - 1 ) === "\\" ) {
+ continue;
+ }
+
+ if ( curLoop === result ) {
+ result = [];
+ }
+
+ if ( Expr.preFilter[ type ] ) {
+ match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
+
+ if ( !match ) {
+ anyFound = found = true;
+
+ } else if ( match === true ) {
+ continue;
+ }
+ }
+
+ if ( match ) {
+ for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
+ if ( item ) {
+ found = filter( item, match, i, curLoop );
+ var pass = not ^ !!found;
+
+ if ( inplace && found != null ) {
+ if ( pass ) {
+ anyFound = true;
+
+ } else {
+ curLoop[i] = false;
+ }
+
+ } else if ( pass ) {
+ result.push( item );
+ anyFound = true;
+ }
+ }
+ }
+ }
+
+ if ( found !== undefined ) {
+ if ( !inplace ) {
+ curLoop = result;
+ }
+
+ expr = expr.replace( Expr.match[ type ], "" );
+
+ if ( !anyFound ) {
+ return [];
+ }
+
+ break;
+ }
+ }
+ }
+
+ // Improper expression
+ if ( expr === old ) {
+ if ( anyFound == null ) {
+ Sizzle.error( expr );
+
+ } else {
+ break;
+ }
+ }
+
+ old = expr;
+ }
+
+ return curLoop;
+};
+
+Sizzle.error = function( msg ) {
+ throw "Syntax error, unrecognized expression: " + msg;
+};
+
+var Expr = Sizzle.selectors = {
+ order: [ "ID", "NAME", "TAG" ],
+
+ match: {
+ ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
+ CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
+ NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
+ ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
+ TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
+ CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
+ POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
+ PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
+ },
+
+ leftMatch: {},
+
+ attrMap: {
+ "class": "className",
+ "for": "htmlFor"
+ },
+
+ attrHandle: {
+ href: function( elem ) {
+ return elem.getAttribute( "href" );
+ },
+ type: function( elem ) {
+ return elem.getAttribute( "type" );
+ }
+ },
+
+ relative: {
+ "+": function(checkSet, part){
+ var isPartStr = typeof part === "string",
+ isTag = isPartStr && !rNonWord.test( part ),
+ isPartStrNotTag = isPartStr && !isTag;
+
+ if ( isTag ) {
+ part = part.toLowerCase();
+ }
+
+ for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
+ if ( (elem = checkSet[i]) ) {
+ while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
+
+ checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
+ elem || false :
+ elem === part;
+ }
+ }
+
+ if ( isPartStrNotTag ) {
+ Sizzle.filter( part, checkSet, true );
+ }
+ },
+
+ ">": function( checkSet, part ) {
+ var elem,
+ isPartStr = typeof part === "string",
+ i = 0,
+ l = checkSet.length;
+
+ if ( isPartStr && !rNonWord.test( part ) ) {
+ part = part.toLowerCase();
+
+ for ( ; i < l; i++ ) {
+ elem = checkSet[i];
+
+ if ( elem ) {
+ var parent = elem.parentNode;
+ checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
+ }
+ }
+
+ } else {
+ for ( ; i < l; i++ ) {
+ elem = checkSet[i];
+
+ if ( elem ) {
+ checkSet[i] = isPartStr ?
+ elem.parentNode :
+ elem.parentNode === part;
+ }
+ }
+
+ if ( isPartStr ) {
+ Sizzle.filter( part, checkSet, true );
+ }
+ }
+ },
+
+ "": function(checkSet, part, isXML){
+ var nodeCheck,
+ doneName = done++,
+ checkFn = dirCheck;
+
+ if ( typeof part === "string" && !rNonWord.test( part ) ) {
+ part = part.toLowerCase();
+ nodeCheck = part;
+ checkFn = dirNodeCheck;
+ }
+
+ checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
+ },
+
+ "~": function( checkSet, part, isXML ) {
+ var nodeCheck,
+ doneName = done++,
+ checkFn = dirCheck;
+
+ if ( typeof part === "string" && !rNonWord.test( part ) ) {
+ part = part.toLowerCase();
+ nodeCheck = part;
+ checkFn = dirNodeCheck;
+ }
+
+ checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
+ }
+ },
+
+ find: {
+ ID: function( match, context, isXML ) {
+ if ( typeof context.getElementById !== "undefined" && !isXML ) {
+ var m = context.getElementById(match[1]);
+ // Check parentNode to catch when Blackberry 4.6 returns
+ // nodes that are no longer in the document #6963
+ return m && m.parentNode ? [m] : [];
+ }
+ },
+
+ NAME: function( match, context ) {
+ if ( typeof context.getElementsByName !== "undefined" ) {
+ var ret = [],
+ results = context.getElementsByName( match[1] );
+
+ for ( var i = 0, l = results.length; i < l; i++ ) {
+ if ( results[i].getAttribute("name") === match[1] ) {
+ ret.push( results[i] );
+ }
+ }
+
+ return ret.length === 0 ? null : ret;
+ }
+ },
+
+ TAG: function( match, context ) {
+ if ( typeof context.getElementsByTagName !== "undefined" ) {
+ return context.getElementsByTagName( match[1] );
+ }
+ }
+ },
+ preFilter: {
+ CLASS: function( match, curLoop, inplace, result, not, isXML ) {
+ match = " " + match[1].replace( rBackslash, "" ) + " ";
+
+ if ( isXML ) {
+ return match;
+ }
+
+ for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
+ if ( elem ) {
+ if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
+ if ( !inplace ) {
+ result.push( elem );
+ }
+
+ } else if ( inplace ) {
+ curLoop[i] = false;
+ }
+ }
+ }
+
+ return false;
+ },
+
+ ID: function( match ) {
+ return match[1].replace( rBackslash, "" );
+ },
+
+ TAG: function( match, curLoop ) {
+ return match[1].replace( rBackslash, "" ).toLowerCase();
+ },
+
+ CHILD: function( match ) {
+ if ( match[1] === "nth" ) {
+ if ( !match[2] ) {
+ Sizzle.error( match[0] );
+ }
+
+ match[2] = match[2].replace(/^\+|\s*/g, '');
+
+ // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
+ var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
+ match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
+ !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
+
+ // calculate the numbers (first)n+(last) including if they are negative
+ match[2] = (test[1] + (test[2] || 1)) - 0;
+ match[3] = test[3] - 0;
+ }
+ else if ( match[2] ) {
+ Sizzle.error( match[0] );
+ }
+
+ // TODO: Move to normal caching system
+ match[0] = done++;
+
+ return match;
+ },
+
+ ATTR: function( match, curLoop, inplace, result, not, isXML ) {
+ var name = match[1] = match[1].replace( rBackslash, "" );
+
+ if ( !isXML && Expr.attrMap[name] ) {
+ match[1] = Expr.attrMap[name];
+ }
+
+ // Handle if an un-quoted value was used
+ match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
+
+ if ( match[2] === "~=" ) {
+ match[4] = " " + match[4] + " ";
+ }
+
+ return match;
+ },
+
+ PSEUDO: function( match, curLoop, inplace, result, not ) {
+ if ( match[1] === "not" ) {
+ // If we're dealing with a complex expression, or a simple one
+ if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
+ match[3] = Sizzle(match[3], null, null, curLoop);
+
+ } else {
+ var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
+
+ if ( !inplace ) {
+ result.push.apply( result, ret );
+ }
+
+ return false;
+ }
+
+ } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
+ return true;
+ }
+
+ return match;
+ },
+
+ POS: function( match ) {
+ match.unshift( true );
+
+ return match;
+ }
+ },
+
+ filters: {
+ enabled: function( elem ) {
+ return elem.disabled === false && elem.type !== "hidden";
+ },
+
+ disabled: function( elem ) {
+ return elem.disabled === true;
+ },
+
+ checked: function( elem ) {
+ return elem.checked === true;
+ },
+
+ selected: function( elem ) {
+ // Accessing this property makes selected-by-default
+ // options in Safari work properly
+ if ( elem.parentNode ) {
+ elem.parentNode.selectedIndex;
+ }
+
+ return elem.selected === true;
+ },
+
+ parent: function( elem ) {
+ return !!elem.firstChild;
+ },
+
+ empty: function( elem ) {
+ return !elem.firstChild;
+ },
+
+ has: function( elem, i, match ) {
+ return !!Sizzle( match[3], elem ).length;
+ },
+
+ header: function( elem ) {
+ return (/h\d/i).test( elem.nodeName );
+ },
+
+ text: function( elem ) {
+ var attr = elem.getAttribute( "type" ), type = elem.type;
+ // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
+ // use getAttribute instead to test this case
+ return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
+ },
+
+ radio: function( elem ) {
+ return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
+ },
+
+ checkbox: function( elem ) {
+ return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
+ },
+
+ file: function( elem ) {
+ return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
+ },
+
+ password: function( elem ) {
+ return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
+ },
+
+ submit: function( elem ) {
+ var name = elem.nodeName.toLowerCase();
+ return (name === "input" || name === "button") && "submit" === elem.type;
+ },
+
+ image: function( elem ) {
+ return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
+ },
+
+ reset: function( elem ) {
+ var name = elem.nodeName.toLowerCase();
+ return (name === "input" || name === "button") && "reset" === elem.type;
+ },
+
+ button: function( elem ) {
+ var name = elem.nodeName.toLowerCase();
+ return name === "input" && "button" === elem.type || name === "button";
+ },
+
+ input: function( elem ) {
+ return (/input|select|textarea|button/i).test( elem.nodeName );
+ },
+
+ focus: function( elem ) {
+ return elem === elem.ownerDocument.activeElement;
+ }
+ },
+ setFilters: {
+ first: function( elem, i ) {
+ return i === 0;
+ },
+
+ last: function( elem, i, match, array ) {
+ return i === array.length - 1;
+ },
+
+ even: function( elem, i ) {
+ return i % 2 === 0;
+ },
+
+ odd: function( elem, i ) {
+ return i % 2 === 1;
+ },
+
+ lt: function( elem, i, match ) {
+ return i < match[3] - 0;
+ },
+
+ gt: function( elem, i, match ) {
+ return i > match[3] - 0;
+ },
+
+ nth: function( elem, i, match ) {
+ return match[3] - 0 === i;
+ },
+
+ eq: function( elem, i, match ) {
+ return match[3] - 0 === i;
+ }
+ },
+ filter: {
+ PSEUDO: function( elem, match, i, array ) {
+ var name = match[1],
+ filter = Expr.filters[ name ];
+
+ if ( filter ) {
+ return filter( elem, i, match, array );
+
+ } else if ( name === "contains" ) {
+ return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
+
+ } else if ( name === "not" ) {
+ var not = match[3];
+
+ for ( var j = 0, l = not.length; j < l; j++ ) {
+ if ( not[j] === elem ) {
+ return false;
+ }
+ }
+
+ return true;
+
+ } else {
+ Sizzle.error( name );
+ }
+ },
+
+ CHILD: function( elem, match ) {
+ var type = match[1],
+ node = elem;
+
+ switch ( type ) {
+ case "only":
+ case "first":
+ while ( (node = node.previousSibling) ) {
+ if ( node.nodeType === 1 ) {
+ return false;
+ }
+ }
+
+ if ( type === "first" ) {
+ return true;
+ }
+
+ node = elem;
+
+ case "last":
+ while ( (node = node.nextSibling) ) {
+ if ( node.nodeType === 1 ) {
+ return false;
+ }
+ }
+
+ return true;
+
+ case "nth":
+ var first = match[2],
+ last = match[3];
+
+ if ( first === 1 && last === 0 ) {
+ return true;
+ }
+
+ var doneName = match[0],
+ parent = elem.parentNode;
+
+ if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
+ var count = 0;
+
+ for ( node = parent.firstChild; node; node = node.nextSibling ) {
+ if ( node.nodeType === 1 ) {
+ node.nodeIndex = ++count;
+ }
+ }
+
+ parent.sizcache = doneName;
+ }
+
+ var diff = elem.nodeIndex - last;
+
+ if ( first === 0 ) {
+ return diff === 0;
+
+ } else {
+ return ( diff % first === 0 && diff / first >= 0 );
+ }
+ }
+ },
+
+ ID: function( elem, match ) {
+ return elem.nodeType === 1 && elem.getAttribute("id") === match;
+ },
+
+ TAG: function( elem, match ) {
+ return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
+ },
+
+ CLASS: function( elem, match ) {
+ return (" " + (elem.className || elem.getAttribute("class")) + " ")
+ .indexOf( match ) > -1;
+ },
+
+ ATTR: function( elem, match ) {
+ var name = match[1],
+ result = Expr.attrHandle[ name ] ?
+ Expr.attrHandle[ name ]( elem ) :
+ elem[ name ] != null ?
+ elem[ name ] :
+ elem.getAttribute( name ),
+ value = result + "",
+ type = match[2],
+ check = match[4];
+
+ return result == null ?
+ type === "!=" :
+ type === "=" ?
+ value === check :
+ type === "*=" ?
+ value.indexOf(check) >= 0 :
+ type === "~=" ?
+ (" " + value + " ").indexOf(check) >= 0 :
+ !check ?
+ value && result !== false :
+ type === "!=" ?
+ value !== check :
+ type === "^=" ?
+ value.indexOf(check) === 0 :
+ type === "$=" ?
+ value.substr(value.length - check.length) === check :
+ type === "|=" ?
+ value === check || value.substr(0, check.length + 1) === check + "-" :
+ false;
+ },
+
+ POS: function( elem, match, i, array ) {
+ var name = match[2],
+ filter = Expr.setFilters[ name ];
+
+ if ( filter ) {
+ return filter( elem, i, match, array );
+ }
+ }
+ }
+};
+
+var origPOS = Expr.match.POS,
+ fescape = function(all, num){
+ return "\\" + (num - 0 + 1);
+ };
+
+for ( var type in Expr.match ) {
+ Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
+ Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
+}
+
+var makeArray = function( array, results ) {
+ array = Array.prototype.slice.call( array, 0 );
+
+ if ( results ) {
+ results.push.apply( results, array );
+ return results;
+ }
+
+ return array;
+};
+
+// Perform a simple check to determine if the browser is capable of
+// converting a NodeList to an array using builtin methods.
+// Also verifies that the returned array holds DOM nodes
+// (which is not the case in the Blackberry browser)
+try {
+ Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
+
+// Provide a fallback method if it does not work
+} catch( e ) {
+ makeArray = function( array, results ) {
+ var i = 0,
+ ret = results || [];
+
+ if ( toString.call(array) === "[object Array]" ) {
+ Array.prototype.push.apply( ret, array );
+
+ } else {
+ if ( typeof array.length === "number" ) {
+ for ( var l = array.length; i < l; i++ ) {
+ ret.push( array[i] );
+ }
+
+ } else {
+ for ( ; array[i]; i++ ) {
+ ret.push( array[i] );
+ }
+ }
+ }
+
+ return ret;
+ };
+}
+
+var sortOrder, siblingCheck;
+
+if ( document.documentElement.compareDocumentPosition ) {
+ sortOrder = function( a, b ) {
+ if ( a === b ) {
+ hasDuplicate = true;
+ return 0;
+ }
+
+ if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
+ return a.compareDocumentPosition ? -1 : 1;
+ }
+
+ return a.compareDocumentPosition(b) & 4 ? -1 : 1;
+ };
+
+} else {
+ sortOrder = function( a, b ) {
+ // The nodes are identical, we can exit early
+ if ( a === b ) {
+ hasDuplicate = true;
+ return 0;
+
+ // Fallback to using sourceIndex (in IE) if it's available on both nodes
+ } else if ( a.sourceIndex && b.sourceIndex ) {
+ return a.sourceIndex - b.sourceIndex;
+ }
+
+ var al, bl,
+ ap = [],
+ bp = [],
+ aup = a.parentNode,
+ bup = b.parentNode,
+ cur = aup;
+
+ // If the nodes are siblings (or identical) we can do a quick check
+ if ( aup === bup ) {
+ return siblingCheck( a, b );
+
+ // If no parents were found then the nodes are disconnected
+ } else if ( !aup ) {
+ return -1;
+
+ } else if ( !bup ) {
+ return 1;
+ }
+
+ // Otherwise they're somewhere else in the tree so we need
+ // to build up a full list of the parentNodes for comparison
+ while ( cur ) {
+ ap.unshift( cur );
+ cur = cur.parentNode;
+ }
+
+ cur = bup;
+
+ while ( cur ) {
+ bp.unshift( cur );
+ cur = cur.parentNode;
+ }
+
+ al = ap.length;
+ bl = bp.length;
+
+ // Start walking down the tree looking for a discrepancy
+ for ( var i = 0; i < al && i < bl; i++ ) {
+ if ( ap[i] !== bp[i] ) {
+ return siblingCheck( ap[i], bp[i] );
+ }
+ }
+
+ // We ended someplace up the tree so do a sibling check
+ return i === al ?
+ siblingCheck( a, bp[i], -1 ) :
+ siblingCheck( ap[i], b, 1 );
+ };
+
+ siblingCheck = function( a, b, ret ) {
+ if ( a === b ) {
+ return ret;
+ }
+
+ var cur = a.nextSibling;
+
+ while ( cur ) {
+ if ( cur === b ) {
+ return -1;
+ }
+
+ cur = cur.nextSibling;
+ }
+
+ return 1;
+ };
+}
+
+// Utility function for retreiving the text value of an array of DOM nodes
+Sizzle.getText = function( elems ) {
+ var ret = "", elem;
+
+ for ( var i = 0; elems[i]; i++ ) {
+ elem = elems[i];
+
+ // Get the text from text nodes and CDATA nodes
+ if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
+ ret += elem.nodeValue;
+
+ // Traverse everything else, except comment nodes
+ } else if ( elem.nodeType !== 8 ) {
+ ret += Sizzle.getText( elem.childNodes );
+ }
+ }
+
+ return ret;
+};
+
+// Check to see if the browser returns elements by name when
+// querying by getElementById (and provide a workaround)
+(function(){
+ // We're going to inject a fake input element with a specified name
+ var form = document.createElement("div"),
+ id = "script" + (new Date()).getTime(),
+ root = document.documentElement;
+
+ form.innerHTML = "";
+
+ // Inject it into the root element, check its status, and remove it quickly
+ root.insertBefore( form, root.firstChild );
+
+ // The workaround has to do additional checks after a getElementById
+ // Which slows things down for other browsers (hence the branching)
+ if ( document.getElementById( id ) ) {
+ Expr.find.ID = function( match, context, isXML ) {
+ if ( typeof context.getElementById !== "undefined" && !isXML ) {
+ var m = context.getElementById(match[1]);
+
+ return m ?
+ m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
+ [m] :
+ undefined :
+ [];
+ }
+ };
+
+ Expr.filter.ID = function( elem, match ) {
+ var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
+
+ return elem.nodeType === 1 && node && node.nodeValue === match;
+ };
+ }
+
+ root.removeChild( form );
+
+ // release memory in IE
+ root = form = null;
+})();
+
+(function(){
+ // Check to see if the browser returns only elements
+ // when doing getElementsByTagName("*")
+
+ // Create a fake element
+ var div = document.createElement("div");
+ div.appendChild( document.createComment("") );
+
+ // Make sure no comments are found
+ if ( div.getElementsByTagName("*").length > 0 ) {
+ Expr.find.TAG = function( match, context ) {
+ var results = context.getElementsByTagName( match[1] );
+
+ // Filter out possible comments
+ if ( match[1] === "*" ) {
+ var tmp = [];
+
+ for ( var i = 0; results[i]; i++ ) {
+ if ( results[i].nodeType === 1 ) {
+ tmp.push( results[i] );
+ }
+ }
+
+ results = tmp;
+ }
+
+ return results;
+ };
+ }
+
+ // Check to see if an attribute returns normalized href attributes
+ div.innerHTML = "";
+
+ if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
+ div.firstChild.getAttribute("href") !== "#" ) {
+
+ Expr.attrHandle.href = function( elem ) {
+ return elem.getAttribute( "href", 2 );
+ };
+ }
+
+ // release memory in IE
+ div = null;
+})();
+
+if ( document.querySelectorAll ) {
+ (function(){
+ var oldSizzle = Sizzle,
+ div = document.createElement("div"),
+ id = "__sizzle__";
+
+ div.innerHTML = "";
+
+ // Safari can't handle uppercase or unicode characters when
+ // in quirks mode.
+ if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
+ return;
+ }
+
+ Sizzle = function( query, context, extra, seed ) {
+ context = context || document;
+
+ // Only use querySelectorAll on non-XML documents
+ // (ID selectors don't work in non-HTML documents)
+ if ( !seed && !Sizzle.isXML(context) ) {
+ // See if we find a selector to speed up
+ var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
+
+ if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
+ // Speed-up: Sizzle("TAG")
+ if ( match[1] ) {
+ return makeArray( context.getElementsByTagName( query ), extra );
+
+ // Speed-up: Sizzle(".CLASS")
+ } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
+ return makeArray( context.getElementsByClassName( match[2] ), extra );
+ }
+ }
+
+ if ( context.nodeType === 9 ) {
+ // Speed-up: Sizzle("body")
+ // The body element only exists once, optimize finding it
+ if ( query === "body" && context.body ) {
+ return makeArray( [ context.body ], extra );
+
+ // Speed-up: Sizzle("#ID")
+ } else if ( match && match[3] ) {
+ var elem = context.getElementById( match[3] );
+
+ // Check parentNode to catch when Blackberry 4.6 returns
+ // nodes that are no longer in the document #6963
+ if ( elem && elem.parentNode ) {
+ // Handle the case where IE and Opera return items
+ // by name instead of ID
+ if ( elem.id === match[3] ) {
+ return makeArray( [ elem ], extra );
+ }
+
+ } else {
+ return makeArray( [], extra );
+ }
+ }
+
+ try {
+ return makeArray( context.querySelectorAll(query), extra );
+ } catch(qsaError) {}
+
+ // qSA works strangely on Element-rooted queries
+ // We can work around this by specifying an extra ID on the root
+ // and working up from there (Thanks to Andrew Dupont for the technique)
+ // IE 8 doesn't work on object elements
+ } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
+ var oldContext = context,
+ old = context.getAttribute( "id" ),
+ nid = old || id,
+ hasParent = context.parentNode,
+ relativeHierarchySelector = /^\s*[+~]/.test( query );
+
+ if ( !old ) {
+ context.setAttribute( "id", nid );
+ } else {
+ nid = nid.replace( /'/g, "\\$&" );
+ }
+ if ( relativeHierarchySelector && hasParent ) {
+ context = context.parentNode;
+ }
+
+ try {
+ if ( !relativeHierarchySelector || hasParent ) {
+ return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
+ }
+
+ } catch(pseudoError) {
+ } finally {
+ if ( !old ) {
+ oldContext.removeAttribute( "id" );
+ }
+ }
+ }
+ }
+
+ return oldSizzle(query, context, extra, seed);
+ };
+
+ for ( var prop in oldSizzle ) {
+ Sizzle[ prop ] = oldSizzle[ prop ];
+ }
+
+ // release memory in IE
+ div = null;
+ })();
+}
+
+(function(){
+ var html = document.documentElement,
+ matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
+
+ if ( matches ) {
+ // Check to see if it's possible to do matchesSelector
+ // on a disconnected node (IE 9 fails this)
+ var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
+ pseudoWorks = false;
+
+ try {
+ // This should fail with an exception
+ // Gecko does not error, returns false instead
+ matches.call( document.documentElement, "[test!='']:sizzle" );
+
+ } catch( pseudoError ) {
+ pseudoWorks = true;
+ }
+
+ Sizzle.matchesSelector = function( node, expr ) {
+ // Make sure that attribute selectors are quoted
+ expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
+
+ if ( !Sizzle.isXML( node ) ) {
+ try {
+ if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
+ var ret = matches.call( node, expr );
+
+ // IE 9's matchesSelector returns false on disconnected nodes
+ if ( ret || !disconnectedMatch ||
+ // As well, disconnected nodes are said to be in a document
+ // fragment in IE 9, so check for that
+ node.document && node.document.nodeType !== 11 ) {
+ return ret;
+ }
+ }
+ } catch(e) {}
+ }
+
+ return Sizzle(expr, null, null, [node]).length > 0;
+ };
+ }
+})();
+
+(function(){
+ var div = document.createElement("div");
+
+ div.innerHTML = "";
+
+ // Opera can't find a second classname (in 9.6)
+ // Also, make sure that getElementsByClassName actually exists
+ if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
+ return;
+ }
+
+ // Safari caches class attributes, doesn't catch changes (in 3.2)
+ div.lastChild.className = "e";
+
+ if ( div.getElementsByClassName("e").length === 1 ) {
+ return;
+ }
+
+ Expr.order.splice(1, 0, "CLASS");
+ Expr.find.CLASS = function( match, context, isXML ) {
+ if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
+ return context.getElementsByClassName(match[1]);
+ }
+ };
+
+ // release memory in IE
+ div = null;
+})();
+
+function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
+ for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+ var elem = checkSet[i];
+
+ if ( elem ) {
+ var match = false;
+
+ elem = elem[dir];
+
+ while ( elem ) {
+ if ( elem.sizcache === doneName ) {
+ match = checkSet[elem.sizset];
+ break;
+ }
+
+ if ( elem.nodeType === 1 && !isXML ){
+ elem.sizcache = doneName;
+ elem.sizset = i;
+ }
+
+ if ( elem.nodeName.toLowerCase() === cur ) {
+ match = elem;
+ break;
+ }
+
+ elem = elem[dir];
+ }
+
+ checkSet[i] = match;
+ }
+ }
+}
+
+function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
+ for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+ var elem = checkSet[i];
+
+ if ( elem ) {
+ var match = false;
+
+ elem = elem[dir];
+
+ while ( elem ) {
+ if ( elem.sizcache === doneName ) {
+ match = checkSet[elem.sizset];
+ break;
+ }
+
+ if ( elem.nodeType === 1 ) {
+ if ( !isXML ) {
+ elem.sizcache = doneName;
+ elem.sizset = i;
+ }
+
+ if ( typeof cur !== "string" ) {
+ if ( elem === cur ) {
+ match = true;
+ break;
+ }
+
+ } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
+ match = elem;
+ break;
+ }
+ }
+
+ elem = elem[dir];
+ }
+
+ checkSet[i] = match;
+ }
+ }
+}
+
+if ( document.documentElement.contains ) {
+ Sizzle.contains = function( a, b ) {
+ return a !== b && (a.contains ? a.contains(b) : true);
+ };
+
+} else if ( document.documentElement.compareDocumentPosition ) {
+ Sizzle.contains = function( a, b ) {
+ return !!(a.compareDocumentPosition(b) & 16);
+ };
+
+} else {
+ Sizzle.contains = function() {
+ return false;
+ };
+}
+
+Sizzle.isXML = function( elem ) {
+ // documentElement is verified for cases where it doesn't yet exist
+ // (such as loading iframes in IE - #4833)
+ var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
+
+ return documentElement ? documentElement.nodeName !== "HTML" : false;
+};
+
+var posProcess = function( selector, context ) {
+ var match,
+ tmpSet = [],
+ later = "",
+ root = context.nodeType ? [context] : context;
+
+ // Position selectors must be done after the filter
+ // And so must :not(positional) so we move all PSEUDOs to the end
+ while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
+ later += match[0];
+ selector = selector.replace( Expr.match.PSEUDO, "" );
+ }
+
+ selector = Expr.relative[selector] ? selector + "*" : selector;
+
+ for ( var i = 0, l = root.length; i < l; i++ ) {
+ Sizzle( selector, root[i], tmpSet );
+ }
+
+ return Sizzle.filter( later, tmpSet );
+};
+
+// EXPOSE
+jQuery.find = Sizzle;
+jQuery.expr = Sizzle.selectors;
+jQuery.expr[":"] = jQuery.expr.filters;
+jQuery.unique = Sizzle.uniqueSort;
+jQuery.text = Sizzle.getText;
+jQuery.isXMLDoc = Sizzle.isXML;
+jQuery.contains = Sizzle.contains;
+
+
+})();
+
+
+var runtil = /Until$/,
+ rparentsprev = /^(?:parents|prevUntil|prevAll)/,
+ // Note: This RegExp should be improved, or likely pulled from Sizzle
+ rmultiselector = /,/,
+ isSimple = /^.[^:#\[\.,]*$/,
+ slice = Array.prototype.slice,
+ POS = jQuery.expr.match.POS,
+ // methods guaranteed to produce a unique set when starting from a unique set
+ guaranteedUnique = {
+ children: true,
+ contents: true,
+ next: true,
+ prev: true
+ };
+
+jQuery.fn.extend({
+ find: function( selector ) {
+ var self = this,
+ i, l;
+
+ if ( typeof selector !== "string" ) {
+ return jQuery( selector ).filter(function() {
+ for ( i = 0, l = self.length; i < l; i++ ) {
+ if ( jQuery.contains( self[ i ], this ) ) {
+ return true;
+ }
+ }
+ });
+ }
+
+ var ret = this.pushStack( "", "find", selector ),
+ length, n, r;
+
+ for ( i = 0, l = this.length; i < l; i++ ) {
+ length = ret.length;
+ jQuery.find( selector, this[i], ret );
+
+ if ( i > 0 ) {
+ // Make sure that the results are unique
+ for ( n = length; n < ret.length; n++ ) {
+ for ( r = 0; r < length; r++ ) {
+ if ( ret[r] === ret[n] ) {
+ ret.splice(n--, 1);
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ return ret;
+ },
+
+ has: function( target ) {
+ var targets = jQuery( target );
+ return this.filter(function() {
+ for ( var i = 0, l = targets.length; i < l; i++ ) {
+ if ( jQuery.contains( this, targets[i] ) ) {
+ return true;
+ }
+ }
+ });
+ },
+
+ not: function( selector ) {
+ return this.pushStack( winnow(this, selector, false), "not", selector);
+ },
+
+ filter: function( selector ) {
+ return this.pushStack( winnow(this, selector, true), "filter", selector );
+ },
+
+ is: function( selector ) {
+ return !!selector && ( typeof selector === "string" ?
+ jQuery.filter( selector, this ).length > 0 :
+ this.filter( selector ).length > 0 );
+ },
+
+ closest: function( selectors, context ) {
+ var ret = [], i, l, cur = this[0];
+
+ // Array
+ if ( jQuery.isArray( selectors ) ) {
+ var match, selector,
+ matches = {},
+ level = 1;
+
+ if ( cur && selectors.length ) {
+ for ( i = 0, l = selectors.length; i < l; i++ ) {
+ selector = selectors[i];
+
+ if ( !matches[ selector ] ) {
+ matches[ selector ] = POS.test( selector ) ?
+ jQuery( selector, context || this.context ) :
+ selector;
+ }
+ }
+
+ while ( cur && cur.ownerDocument && cur !== context ) {
+ for ( selector in matches ) {
+ match = matches[ selector ];
+
+ if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) {
+ ret.push({ selector: selector, elem: cur, level: level });
+ }
+ }
+
+ cur = cur.parentNode;
+ level++;
+ }
+ }
+
+ return ret;
+ }
+
+ // String
+ var pos = POS.test( selectors ) || typeof selectors !== "string" ?
+ jQuery( selectors, context || this.context ) :
+ 0;
+
+ for ( i = 0, l = this.length; i < l; i++ ) {
+ cur = this[i];
+
+ while ( cur ) {
+ if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
+ ret.push( cur );
+ break;
+
+ } else {
+ cur = cur.parentNode;
+ if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
+ break;
+ }
+ }
+ }
+ }
+
+ ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
+
+ return this.pushStack( ret, "closest", selectors );
+ },
+
+ // Determine the position of an element within
+ // the matched set of elements
+ index: function( elem ) {
+
+ // No argument, return index in parent
+ if ( !elem ) {
+ return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
+ }
+
+ // index in selector
+ if ( typeof elem === "string" ) {
+ return jQuery.inArray( this[0], jQuery( elem ) );
+ }
+
+ // Locate the position of the desired element
+ return jQuery.inArray(
+ // If it receives a jQuery object, the first element is used
+ elem.jquery ? elem[0] : elem, this );
+ },
+
+ add: function( selector, context ) {
+ var set = typeof selector === "string" ?
+ jQuery( selector, context ) :
+ jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
+ all = jQuery.merge( this.get(), set );
+
+ return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
+ all :
+ jQuery.unique( all ) );
+ },
+
+ andSelf: function() {
+ return this.add( this.prevObject );
+ }
+});
+
+// A painfully simple check to see if an element is disconnected
+// from a document (should be improved, where feasible).
+function isDisconnected( node ) {
+ return !node || !node.parentNode || node.parentNode.nodeType === 11;
+}
+
+jQuery.each({
+ parent: function( elem ) {
+ var parent = elem.parentNode;
+ return parent && parent.nodeType !== 11 ? parent : null;
+ },
+ parents: function( elem ) {
+ return jQuery.dir( elem, "parentNode" );
+ },
+ parentsUntil: function( elem, i, until ) {
+ return jQuery.dir( elem, "parentNode", until );
+ },
+ next: function( elem ) {
+ return jQuery.nth( elem, 2, "nextSibling" );
+ },
+ prev: function( elem ) {
+ return jQuery.nth( elem, 2, "previousSibling" );
+ },
+ nextAll: function( elem ) {
+ return jQuery.dir( elem, "nextSibling" );
+ },
+ prevAll: function( elem ) {
+ return jQuery.dir( elem, "previousSibling" );
+ },
+ nextUntil: function( elem, i, until ) {
+ return jQuery.dir( elem, "nextSibling", until );
+ },
+ prevUntil: function( elem, i, until ) {
+ return jQuery.dir( elem, "previousSibling", until );
+ },
+ siblings: function( elem ) {
+ return jQuery.sibling( elem.parentNode.firstChild, elem );
+ },
+ children: function( elem ) {
+ return jQuery.sibling( elem.firstChild );
+ },
+ contents: function( elem ) {
+ return jQuery.nodeName( elem, "iframe" ) ?
+ elem.contentDocument || elem.contentWindow.document :
+ jQuery.makeArray( elem.childNodes );
+ }
+}, function( name, fn ) {
+ jQuery.fn[ name ] = function( until, selector ) {
+ var ret = jQuery.map( this, fn, until ),
+ // The variable 'args' was introduced in
+ // https://github.com/jquery/jquery/commit/52a0238
+ // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
+ // http://code.google.com/p/v8/issues/detail?id=1050
+ args = slice.call(arguments);
+
+ if ( !runtil.test( name ) ) {
+ selector = until;
+ }
+
+ if ( selector && typeof selector === "string" ) {
+ ret = jQuery.filter( selector, ret );
+ }
+
+ ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
+
+ if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
+ ret = ret.reverse();
+ }
+
+ return this.pushStack( ret, name, args.join(",") );
+ };
+});
+
+jQuery.extend({
+ filter: function( expr, elems, not ) {
+ if ( not ) {
+ expr = ":not(" + expr + ")";
+ }
+
+ return elems.length === 1 ?
+ jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
+ jQuery.find.matches(expr, elems);
+ },
+
+ dir: function( elem, dir, until ) {
+ var matched = [],
+ cur = elem[ dir ];
+
+ while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
+ if ( cur.nodeType === 1 ) {
+ matched.push( cur );
+ }
+ cur = cur[dir];
+ }
+ return matched;
+ },
+
+ nth: function( cur, result, dir, elem ) {
+ result = result || 1;
+ var num = 0;
+
+ for ( ; cur; cur = cur[dir] ) {
+ if ( cur.nodeType === 1 && ++num === result ) {
+ break;
+ }
+ }
+
+ return cur;
+ },
+
+ sibling: function( n, elem ) {
+ var r = [];
+
+ for ( ; n; n = n.nextSibling ) {
+ if ( n.nodeType === 1 && n !== elem ) {
+ r.push( n );
+ }
+ }
+
+ return r;
+ }
+});
+
+// Implement the identical functionality for filter and not
+function winnow( elements, qualifier, keep ) {
+
+ // Can't pass null or undefined to indexOf in Firefox 4
+ // Set to 0 to skip string check
+ qualifier = qualifier || 0;
+
+ if ( jQuery.isFunction( qualifier ) ) {
+ return jQuery.grep(elements, function( elem, i ) {
+ var retVal = !!qualifier.call( elem, i, elem );
+ return retVal === keep;
+ });
+
+ } else if ( qualifier.nodeType ) {
+ return jQuery.grep(elements, function( elem, i ) {
+ return (elem === qualifier) === keep;
+ });
+
+ } else if ( typeof qualifier === "string" ) {
+ var filtered = jQuery.grep(elements, function( elem ) {
+ return elem.nodeType === 1;
+ });
+
+ if ( isSimple.test( qualifier ) ) {
+ return jQuery.filter(qualifier, filtered, !keep);
+ } else {
+ qualifier = jQuery.filter( qualifier, filtered );
+ }
+ }
+
+ return jQuery.grep(elements, function( elem, i ) {
+ return (jQuery.inArray( elem, qualifier ) >= 0) === keep;
+ });
+}
+
+
+
+
+var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
+ rleadingWhitespace = /^\s+/,
+ rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
+ rtagName = /<([\w:]+)/,
+ rtbody = /", "" ],
+ legend: [ 1, "" ],
+ thead: [ 1, "
Javascript library for localised formatting and parsing of:
+ *
+ *
Numbers
+ *
Dates and times
+ *
Currency
+ *
+ *
+ *
The library classes are configured with standard POSIX locale definitions
+ * derived from Unicode's Common Locale Data Repository (CLDR).
+ *
+ *
Website: JsWorld
+ *
+ * @author Vladimir Dzhuvinov
+ * @version 2.5 (2011-12-23)
+ */
+
+
+
+/**
+ * @namespace Namespace container for the JsWorld library objects.
+ */
+jsworld = {};
+
+
+/**
+ * @function
+ *
+ * @description Formats a JavaScript Date object as an ISO-8601 date/time
+ * string.
+ *
+ * @param {Date} [d] A valid JavaScript Date object. If undefined the
+ * current date/time will be used.
+ * @param {Boolean} [withTZ] Include timezone offset, default false.
+ *
+ * @returns {String} The date/time formatted as YYYY-MM-DD HH:MM:SS.
+ */
+jsworld.formatIsoDateTime = function(d, withTZ) {
+
+ if (typeof d === "undefined")
+ d = new Date(); // now
+
+ if (typeof withTZ === "undefined")
+ withTZ = false;
+
+ var s = jsworld.formatIsoDate(d) + " " + jsworld.formatIsoTime(d);
+
+ if (withTZ) {
+
+ var diff = d.getHours() - d.getUTCHours();
+ var hourDiff = Math.abs(diff);
+
+ var minuteUTC = d.getUTCMinutes();
+ var minute = d.getMinutes();
+
+ if (minute != minuteUTC && minuteUTC < 30 && diff < 0)
+ hourDiff--;
+
+ if (minute != minuteUTC && minuteUTC > 30 && diff > 0)
+ hourDiff--;
+
+ var minuteDiff;
+ if (minute != minuteUTC)
+ minuteDiff = ":30";
+ else
+ minuteDiff = ":00";
+
+ var timezone;
+ if (hourDiff < 10)
+ timezone = "0" + hourDiff + minuteDiff;
+
+ else
+ timezone = "" + hourDiff + minuteDiff;
+
+ if (diff < 0)
+ timezone = "-" + timezone;
+
+ else
+ timezone = "+" + timezone;
+
+ s = s + timezone;
+ }
+
+ return s;
+};
+
+
+/**
+ * @function
+ *
+ * @description Formats a JavaScript Date object as an ISO-8601 date string.
+ *
+ * @param {Date} [d] A valid JavaScript Date object. If undefined the current
+ * date will be used.
+ *
+ * @returns {String} The date formatted as YYYY-MM-DD.
+ */
+jsworld.formatIsoDate = function(d) {
+
+ if (typeof d === "undefined")
+ d = new Date(); // now
+
+ var year = d.getFullYear();
+ var month = d.getMonth() + 1;
+ var day = d.getDate();
+
+ return year + "-" + jsworld._zeroPad(month, 2) + "-" + jsworld._zeroPad(day, 2);
+};
+
+
+/**
+ * @function
+ *
+ * @description Formats a JavaScript Date object as an ISO-8601 time string.
+ *
+ * @param {Date} [d] A valid JavaScript Date object. If undefined the current
+ * time will be used.
+ *
+ * @returns {String} The time formatted as HH:MM:SS.
+ */
+jsworld.formatIsoTime = function(d) {
+
+ if (typeof d === "undefined")
+ d = new Date(); // now
+
+ var hour = d.getHours();
+ var minute = d.getMinutes();
+ var second = d.getSeconds();
+
+ return jsworld._zeroPad(hour, 2) + ":" + jsworld._zeroPad(minute, 2) + ":" + jsworld._zeroPad(second, 2);
+};
+
+
+/**
+ * @function
+ *
+ * @description Parses an ISO-8601 formatted date/time string to a JavaScript
+ * Date object.
+ *
+ * @param {String} isoDateTimeVal An ISO-8601 formatted date/time string.
+ *
+ *
Accepted formats:
+ *
+ *
+ *
YYYY-MM-DD HH:MM:SS
+ *
YYYYMMDD HHMMSS
+ *
YYYY-MM-DD HHMMSS
+ *
YYYYMMDD HH:MM:SS
+ *
+ *
+ * @returns {Date} The corresponding Date object.
+ *
+ * @throws Error on a badly formatted date/time string or on a invalid date.
+ */
+jsworld.parseIsoDateTime = function(isoDateTimeVal) {
+
+ if (typeof isoDateTimeVal != "string")
+ throw "Error: The parameter must be a string";
+
+ // First, try to match "YYYY-MM-DD HH:MM:SS" format
+ var matches = isoDateTimeVal.match(/^(\d\d\d\d)-(\d\d)-(\d\d)[T ](\d\d):(\d\d):(\d\d)/);
+
+ // If unsuccessful, try to match "YYYYMMDD HHMMSS" format
+ if (matches === null)
+ matches = isoDateTimeVal.match(/^(\d\d\d\d)(\d\d)(\d\d)[T ](\d\d)(\d\d)(\d\d)/);
+
+ // ... try to match "YYYY-MM-DD HHMMSS" format
+ if (matches === null)
+ matches = isoDateTimeVal.match(/^(\d\d\d\d)-(\d\d)-(\d\d)[T ](\d\d)(\d\d)(\d\d)/);
+
+ // ... try to match "YYYYMMDD HH:MM:SS" format
+ if (matches === null)
+ matches = isoDateTimeVal.match(/^(\d\d\d\d)-(\d\d)-(\d\d)[T ](\d\d):(\d\d):(\d\d)/);
+
+ // Report bad date/time string
+ if (matches === null)
+ throw "Error: Invalid ISO-8601 date/time string";
+
+ // Force base 10 parse int as some values may have leading zeros!
+ // (to avoid implicit octal base conversion)
+ var year = parseInt(matches[1], 10);
+ var month = parseInt(matches[2], 10);
+ var day = parseInt(matches[3], 10);
+
+ var hour = parseInt(matches[4], 10);
+ var mins = parseInt(matches[5], 10);
+ var secs = parseInt(matches[6], 10);
+
+ // Simple value range check, leap years not checked
+ // Note: the originial ISO time spec for leap hours (24:00:00) and seconds (00:00:60) is not supported
+ if (month < 1 || month > 12 ||
+ day < 1 || day > 31 ||
+ hour < 0 || hour > 23 ||
+ mins < 0 || mins > 59 ||
+ secs < 0 || secs > 59 )
+
+ throw "Error: Invalid ISO-8601 date/time value";
+
+ var d = new Date(year, month - 1, day, hour, mins, secs);
+
+ // Check if the input date was valid
+ // (JS Date does automatic forward correction)
+ if (d.getDate() != day || d.getMonth() +1 != month)
+ throw "Error: Invalid date";
+
+ return d;
+};
+
+
+/**
+ * @function
+ *
+ * @description Parses an ISO-8601 formatted date string to a JavaScript
+ * Date object.
+ *
+ * @param {String} isoDateVal An ISO-8601 formatted date string.
+ *
+ *
Accepted formats:
+ *
+ *
+ *
YYYY-MM-DD
+ *
YYYYMMDD
+ *
+ *
+ * @returns {Date} The corresponding Date object.
+ *
+ * @throws Error on a badly formatted date string or on a invalid date.
+ */
+jsworld.parseIsoDate = function(isoDateVal) {
+
+ if (typeof isoDateVal != "string")
+ throw "Error: The parameter must be a string";
+
+ // First, try to match "YYYY-MM-DD" format
+ var matches = isoDateVal.match(/^(\d\d\d\d)-(\d\d)-(\d\d)/);
+
+ // If unsuccessful, try to match "YYYYMMDD" format
+ if (matches === null)
+ matches = isoDateVal.match(/^(\d\d\d\d)(\d\d)(\d\d)/);
+
+ // Report bad date/time string
+ if (matches === null)
+ throw "Error: Invalid ISO-8601 date string";
+
+ // Force base 10 parse int as some values may have leading zeros!
+ // (to avoid implicit octal base conversion)
+ var year = parseInt(matches[1], 10);
+ var month = parseInt(matches[2], 10);
+ var day = parseInt(matches[3], 10);
+
+ // Simple value range check, leap years not checked
+ if (month < 1 || month > 12 ||
+ day < 1 || day > 31 )
+
+ throw "Error: Invalid ISO-8601 date value";
+
+ var d = new Date(year, month - 1, day);
+
+ // Check if the input date was valid
+ // (JS Date does automatic forward correction)
+ if (d.getDate() != day || d.getMonth() +1 != month)
+ throw "Error: Invalid date";
+
+ return d;
+};
+
+
+/**
+ * @function
+ *
+ * @description Parses an ISO-8601 formatted time string to a JavaScript
+ * Date object.
+ *
+ * @param {String} isoTimeVal An ISO-8601 formatted time string.
+ *
+ *
Accepted formats:
+ *
+ *
+ *
HH:MM:SS
+ *
HHMMSS
+ *
+ *
+ * @returns {Date} The corresponding Date object, with year, month and day set
+ * to zero.
+ *
+ * @throws Error on a badly formatted time string.
+ */
+jsworld.parseIsoTime = function(isoTimeVal) {
+
+ if (typeof isoTimeVal != "string")
+ throw "Error: The parameter must be a string";
+
+ // First, try to match "HH:MM:SS" format
+ var matches = isoTimeVal.match(/^(\d\d):(\d\d):(\d\d)/);
+
+ // If unsuccessful, try to match "HHMMSS" format
+ if (matches === null)
+ matches = isoTimeVal.match(/^(\d\d)(\d\d)(\d\d)/);
+
+ // Report bad date/time string
+ if (matches === null)
+ throw "Error: Invalid ISO-8601 date/time string";
+
+ // Force base 10 parse int as some values may have leading zeros!
+ // (to avoid implicit octal base conversion)
+ var hour = parseInt(matches[1], 10);
+ var mins = parseInt(matches[2], 10);
+ var secs = parseInt(matches[3], 10);
+
+ // Simple value range check, leap years not checked
+ if (hour < 0 || hour > 23 ||
+ mins < 0 || mins > 59 ||
+ secs < 0 || secs > 59 )
+
+ throw "Error: Invalid ISO-8601 time value";
+
+ return new Date(0, 0, 0, hour, mins, secs);
+};
+
+
+/**
+ * @private
+ *
+ * @description Trims leading and trailing whitespace from a string.
+ *
+ *
Used non-regexp the method from http://blog.stevenlevithan.com/archives/faster-trim-javascript
+ *
+ * @param {String} str The string to trim.
+ *
+ * @returns {String} The trimmed string.
+ */
+jsworld._trim = function(str) {
+
+ var whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
+
+ for (var i = 0; i < str.length; i++) {
+
+ if (whitespace.indexOf(str.charAt(i)) === -1) {
+ str = str.substring(i);
+ break;
+ }
+ }
+
+ for (i = str.length - 1; i >= 0; i--) {
+ if (whitespace.indexOf(str.charAt(i)) === -1) {
+ str = str.substring(0, i + 1);
+ break;
+ }
+ }
+
+ return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
+};
+
+
+
+/**
+ * @private
+ *
+ * @description Returns true if the argument represents a decimal number.
+ *
+ * @param {Number|String} arg The argument to test.
+ *
+ * @returns {Boolean} true if the argument represents a decimal number,
+ * otherwise false.
+ */
+jsworld._isNumber = function(arg) {
+
+ if (typeof arg == "number")
+ return true;
+
+ if (typeof arg != "string")
+ return false;
+
+ // ensure string
+ var s = arg + "";
+
+ return (/^-?(\d+|\d*\.\d+)$/).test(s);
+};
+
+
+/**
+ * @private
+ *
+ * @description Returns true if the argument represents a decimal integer.
+ *
+ * @param {Number|String} arg The argument to test.
+ *
+ * @returns {Boolean} true if the argument represents an integer, otherwise
+ * false.
+ */
+jsworld._isInteger = function(arg) {
+
+ if (typeof arg != "number" && typeof arg != "string")
+ return false;
+
+ // convert to string
+ var s = arg + "";
+
+ return (/^-?\d+$/).test(s);
+};
+
+
+/**
+ * @private
+ *
+ * @description Returns true if the argument represents a decimal float.
+ *
+ * @param {Number|String} arg The argument to test.
+ *
+ * @returns {Boolean} true if the argument represents a float, otherwise false.
+ */
+jsworld._isFloat = function(arg) {
+
+ if (typeof arg != "number" && typeof arg != "string")
+ return false;
+
+ // convert to string
+ var s = arg + "";
+
+ return (/^-?\.\d+?$/).test(s);
+};
+
+
+/**
+ * @private
+ *
+ * @description Checks if the specified formatting option is contained
+ * within the options string.
+ *
+ * @param {String} option The option to search for.
+ * @param {String} optionsString The options string.
+ *
+ * @returns {Boolean} true if the flag is found, else false
+ */
+jsworld._hasOption = function(option, optionsString) {
+
+ if (typeof option != "string" || typeof optionsString != "string")
+ return false;
+
+ if (optionsString.indexOf(option) != -1)
+ return true;
+ else
+ return false;
+};
+
+
+/**
+ * @private
+ *
+ * @description String replacement function.
+ *
+ * @param {String} s The string to work on.
+ * @param {String} target The string to search for.
+ * @param {String} replacement The replacement.
+ *
+ * @returns {String} The new string.
+ */
+jsworld._stringReplaceAll = function(s, target, replacement) {
+
+ var out;
+
+ if (target.length == 1 && replacement.length == 1) {
+ // simple char/char case somewhat faster
+ out = "";
+
+ for (var i = 0; i < s.length; i++) {
+
+ if (s.charAt(i) == target.charAt(0))
+ out = out + replacement.charAt(0);
+ else
+ out = out + s.charAt(i);
+ }
+
+ return out;
+ }
+ else {
+ // longer target and replacement strings
+ out = s;
+
+ var index = out.indexOf(target);
+
+ while (index != -1) {
+
+ out = out.replace(target, replacement);
+
+ index = out.indexOf(target);
+ }
+
+ return out;
+ }
+};
+
+
+/**
+ * @private
+ *
+ * @description Tests if a string starts with the specified substring.
+ *
+ * @param {String} testedString The string to test.
+ * @param {String} sub The string to match.
+ *
+ * @returns {Boolean} true if the test succeeds.
+ */
+jsworld._stringStartsWith = function (testedString, sub) {
+
+ if (testedString.length < sub.length)
+ return false;
+
+ for (var i = 0; i < sub.length; i++) {
+ if (testedString.charAt(i) != sub.charAt(i))
+ return false;
+ }
+
+ return true;
+};
+
+
+/**
+ * @private
+ *
+ * @description Gets the requested precision from an options string.
+ *
+ *
Example: ".3" returns 3 decimal places precision.
+ *
+ * @param {String} optionsString The options string.
+ *
+ * @returns {integer Number} The requested precision, -1 if not specified.
+ */
+jsworld._getPrecision = function (optionsString) {
+
+ if (typeof optionsString != "string")
+ return -1;
+
+ var m = optionsString.match(/\.(\d)/);
+ if (m)
+ return parseInt(m[1], 10);
+ else
+ return -1;
+};
+
+
+/**
+ * @private
+ *
+ * @description Takes a decimal numeric amount (optionally as string) and
+ * returns its integer and fractional parts packed into an object.
+ *
+ * @param {Number|String} amount The amount, e.g. "123.45" or "-56.78"
+ *
+ * @returns {object} Parsed amount object with properties:
+ * {String} integer : the integer part
+ * {String} fraction : the fraction part
+ */
+jsworld._splitNumber = function (amount) {
+
+ if (typeof amount == "number")
+ amount = amount + "";
+
+ var obj = {};
+
+ // remove negative sign
+ if (amount.charAt(0) == "-")
+ amount = amount.substring(1);
+
+ // split amount into integer and decimal parts
+ var amountParts = amount.split(".");
+ if (!amountParts[1])
+ amountParts[1] = ""; // we need "" instead of null
+
+ obj.integer = amountParts[0];
+ obj.fraction = amountParts[1];
+
+ return obj;
+};
+
+
+/**
+ * @private
+ *
+ * @description Formats the integer part using the specified grouping
+ * and thousands separator.
+ *
+ * @param {String} intPart The integer part of the amount, as string.
+ * @param {String} grouping The grouping definition.
+ * @param {String} thousandsSep The thousands separator.
+ *
+ * @returns {String} The formatted integer part.
+ */
+jsworld._formatIntegerPart = function (intPart, grouping, thousandsSep) {
+
+ // empty separator string? no grouping?
+ // -> return immediately with no formatting!
+ if (thousandsSep == "" || grouping == "-1")
+ return intPart;
+
+ // turn the semicolon-separated string of integers into an array
+ var groupSizes = grouping.split(";");
+
+ // the formatted output string
+ var out = "";
+
+ // the intPart string position to process next,
+ // start at string end, e.g. "10000000 0) {
+
+ // get next group size (if any, otherwise keep last)
+ if (groupSizes.length > 0)
+ size = parseInt(groupSizes.shift(), 10);
+
+ // int parse error?
+ if (isNaN(size))
+ throw "Error: Invalid grouping";
+
+ // size is -1? -> no more grouping, so just copy string remainder
+ if (size == -1) {
+ out = intPart.substring(0, pos) + out;
+ break;
+ }
+
+ pos -= size; // move to next sep. char. position
+
+ // position underrun? -> just copy string remainder
+ if (pos < 1) {
+ out = intPart.substring(0, pos + size) + out;
+ break;
+ }
+
+ // extract group and apply sep. char.
+ out = thousandsSep + intPart.substring(pos, pos + size) + out;
+ }
+
+ return out;
+};
+
+
+/**
+ * @private
+ *
+ * @description Formats the fractional part to the specified decimal
+ * precision.
+ *
+ * @param {String} fracPart The fractional part of the amount
+ * @param {integer Number} precision The desired decimal precision
+ *
+ * @returns {String} The formatted fractional part.
+ */
+jsworld._formatFractionPart = function (fracPart, precision) {
+
+ // append zeroes up to precision if necessary
+ for (var i=0; fracPart.length < precision; i++)
+ fracPart = fracPart + "0";
+
+ return fracPart;
+};
+
+
+/**
+ * @private
+ *
+ * @desription Converts a number to string and pad it with leading zeroes if the
+ * string is shorter than length.
+ *
+ * @param {integer Number} number The number value subjected to selective padding.
+ * @param {integer Number} length If the number has fewer digits than this length
+ * apply padding.
+ *
+ * @returns {String} The formatted string.
+ */
+jsworld._zeroPad = function(number, length) {
+
+ // ensure string
+ var s = number + "";
+
+ while (s.length < length)
+ s = "0" + s;
+
+ return s;
+};
+
+
+/**
+ * @private
+ * @description Converts a number to string and pads it with leading spaces if
+ * the string is shorter than length.
+ *
+ * @param {integer Number} number The number value subjected to selective padding.
+ * @param {integer Number} length If the number has fewer digits than this length
+ * apply padding.
+ *
+ * @returns {String} The formatted string.
+ */
+jsworld._spacePad = function(number, length) {
+
+ // ensure string
+ var s = number + "";
+
+ while (s.length < length)
+ s = " " + s;
+
+ return s;
+};
+
+
+
+/**
+ * @class
+ * Represents a POSIX-style locale with its numeric, monetary and date/time
+ * properties. Also provides a set of locale helper methods.
+ *
+ *
The locale properties follow the POSIX standards:
+ *
+ *
+ *
+ * @public
+ * @constructor
+ * @description Creates a new locale object (POSIX-style) with the specified
+ * properties.
+ *
+ * @param {object} properties An object containing the raw locale properties:
+ *
+ * @param {String} properties.decimal_point
+ *
+ * A string containing the symbol that shall be used as the decimal
+ * delimiter (radix character) in numeric, non-monetary formatted
+ * quantities. This property cannot be omitted and cannot be set to the
+ * empty string.
+ *
+ *
+ * @param {String} properties.thousands_sep
+ *
+ * A string containing the symbol that shall be used as a separator for
+ * groups of digits to the left of the decimal delimiter in numeric,
+ * non-monetary formatted monetary quantities.
+ *
+ *
+ * @param {String} properties.grouping
+ *
+ * Defines the size of each group of digits in formatted non-monetary
+ * quantities. The operand is a sequence of integers separated by
+ * semicolons. Each integer specifies the number of digits in each group,
+ * with the initial integer defining the size of the group immediately
+ * preceding the decimal delimiter, and the following integers defining
+ * the preceding groups. If the last integer is not -1, then the size of
+ * the previous group (if any) shall be repeatedly used for the
+ * remainder of the digits. If the last integer is -1, then no further
+ * grouping shall be performed.
+ *
+ *
+ * @param {String} properties.int_curr_symbol
+ *
+ * The first three letters signify the ISO-4217 currency code,
+ * the fourth letter is the international symbol separation character
+ * (normally a space).
+ *
+ *
+ * @param {String} properties.currency_symbol
+ *
+ * The local shorthand currency symbol, e.g. "$" for the en_US locale
+ *
+ *
+ * @param {String} properties.mon_decimal_point
+ *
+ * The symbol to be used as the decimal delimiter (radix character)
+ *
+ *
+ * @param {String} properties.mon_thousands_sep
+ *
+ * The symbol to be used as a separator for groups of digits to the
+ * left of the decimal delimiter.
+ *
+ *
+ * @param {String} properties.mon_grouping
+ *
+ * A string that defines the size of each group of digits. The
+ * operand is a sequence of integers separated by semicolons (";").
+ * Each integer specifies the number of digits in each group, with the
+ * initial integer defining the size of the group preceding the
+ * decimal delimiter, and the following integers defining the
+ * preceding groups. If the last integer is not -1, then the size of
+ * the previous group (if any) must be repeatedly used for the
+ * remainder of the digits. If the last integer is -1, then no
+ * further grouping is to be performed.
+ *
+ *
+ * @param {String} properties.positive_sign
+ *
+ * The string to indicate a non-negative monetary amount.
+ *
+ *
+ * @param {String} properties.negative_sign
+ *
+ * The string to indicate a negative monetary amount.
+ *
+ *
+ * @param {integer Number} properties.frac_digits
+ *
+ * An integer representing the number of fractional digits (those to
+ * the right of the decimal delimiter) to be written in a formatted
+ * monetary quantity using currency_symbol.
+ *
+ *
+ * @param {integer Number} properties.int_frac_digits
+ *
+ * An integer representing the number of fractional digits (those to
+ * the right of the decimal delimiter) to be written in a formatted
+ * monetary quantity using int_curr_symbol.
+ *
+ *
+ * @param {integer Number} properties.p_cs_precedes
+ *
+ * An integer set to 1 if the currency_symbol precedes the value for a
+ * monetary quantity with a non-negative value, and set to 0 if the
+ * symbol succeeds the value.
+ *
+ *
+ * @param {integer Number} properties.n_cs_precedes
+ *
+ * An integer set to 1 if the currency_symbol precedes the value for a
+ * monetary quantity with a negative value, and set to 0 if the symbol
+ * succeeds the value.
+ *
+ *
+ * @param {integer Number} properties.p_sep_by_space
+ *
+ * Set to a value indicating the separation of the currency_symbol,
+ * the sign string, and the value for a non-negative formatted monetary
+ * quantity:
+ *
+ *
0 No space separates the currency symbol and value.
+ *
+ *
1 If the currency symbol and sign string are adjacent, a space
+ * separates them from the value; otherwise, a space separates
+ * the currency symbol from the value.
+ *
+ *
2 If the currency symbol and sign string are adjacent, a space
+ * separates them; otherwise, a space separates the sign string
+ * from the value.
+ *
+ *
+ * @param {integer Number} properties.n_sep_by_space
+ *
+ * Set to a value indicating the separation of the currency_symbol,
+ * the sign string, and the value for a negative formatted monetary
+ * quantity. Rules same as for p_sep_by_space.
+ *
+ *
+ * @param {integer Number} properties.p_sign_posn
+ *
+ * An integer set to a value indicating the positioning of the
+ * positive_sign for a monetary quantity with a non-negative value:
+ *
+ *
0 Parentheses enclose the quantity and the currency_symbol.
+ *
+ *
1 The sign string precedes the quantity and the currency_symbol.
+ *
+ *
2 The sign string succeeds the quantity and the currency_symbol.
+ *
+ *
3 The sign string precedes the currency_symbol.
+ *
+ *
4 The sign string succeeds the currency_symbol.
+ *
+ *
+ * @param {integer Number} properties.n_sign_posn
+ *
+ * An integer set to a value indicating the positioning of the
+ * negative_sign for a negative formatted monetary quantity. Rules same
+ * as for p_sign_posn.
+ *
+ *
+ * @param {integer Number} properties.int_p_cs_precedes
+ *
+ * An integer set to 1 if the int_curr_symbol precedes the value for a
+ * monetary quantity with a non-negative value, and set to 0 if the
+ * symbol succeeds the value.
+ *
+ *
+ * @param {integer Number} properties.int_n_cs_precedes
+ *
+ * An integer set to 1 if the int_curr_symbol precedes the value for a
+ * monetary quantity with a negative value, and set to 0 if the symbol
+ * succeeds the value.
+ *
+ *
+ * @param {integer Number} properties.int_p_sep_by_space
+ *
+ * Set to a value indicating the separation of the int_curr_symbol,
+ * the sign string, and the value for a non-negative internationally
+ * formatted monetary quantity. Rules same as for p_sep_by_space.
+ *
+ *
+ * @param {integer Number} properties.int_n_sep_by_space
+ *
+ * Set to a value indicating the separation of the int_curr_symbol,
+ * the sign string, and the value for a negative internationally
+ * formatted monetary quantity. Rules same as for p_sep_by_space.
+ *
+ *
+ * @param {integer Number} properties.int_p_sign_posn
+ *
+ * An integer set to a value indicating the positioning of the
+ * positive_sign for a positive monetary quantity formatted with the
+ * international format. Rules same as for p_sign_posn.
+ *
+ *
+ * @param {integer Number} properties.int_n_sign_posn
+ *
+ * An integer set to a value indicating the positioning of the
+ * negative_sign for a negative monetary quantity formatted with the
+ * international format. Rules same as for p_sign_posn.
+ *
+ *
+ * @param {String[] | String} properties.abday
+ *
+ * The abbreviated weekday names, corresponding to the %a conversion
+ * specification. The property must be either an array of 7 strings or
+ * a string consisting of 7 semicolon-separated substrings, each
+ * surrounded by double-quotes. The first must be the abbreviated name
+ * of the day corresponding to Sunday, the second the abbreviated name
+ * of the day corresponding to Monday, and so on.
+ *
+ *
+ * @param {String[] | String} properties.day
+ *
+ * The full weekday names, corresponding to the %A conversion
+ * specification. The property must be either an array of 7 strings or
+ * a string consisting of 7 semicolon-separated substrings, each
+ * surrounded by double-quotes. The first must be the full name of the
+ * day corresponding to Sunday, the second the full name of the day
+ * corresponding to Monday, and so on.
+ *
+ *
+ * @param {String[] | String} properties.abmon
+ *
+ * The abbreviated month names, corresponding to the %b conversion
+ * specification. The property must be either an array of 12 strings or
+ * a string consisting of 12 semicolon-separated substrings, each
+ * surrounded by double-quotes. The first must be the abbreviated name
+ * of the first month of the year (January), the second the abbreviated
+ * name of the second month, and so on.
+ *
+ *
+ * @param {String[] | String} properties.mon
+ *
+ * The full month names, corresponding to the %B conversion
+ * specification. The property must be either an array of 12 strings or
+ * a string consisting of 12 semicolon-separated substrings, each
+ * surrounded by double-quotes. The first must be the full name of the
+ * first month of the year (January), the second the full name of the second
+ * month, and so on.
+ *
+ *
+ * @param {String} properties.d_fmt
+ *
+ * The appropriate date representation. The string may contain any
+ * combination of characters and conversion specifications (%).
+ *
+ *
+ * @param {String} properties.t_fmt
+ *
+ * The appropriate time representation. The string may contain any
+ * combination of characters and conversion specifications (%).
+ *
+ *
+ * @param {String} properties.d_t_fmt
+ *
+ * The appropriate date and time representation. The string may contain
+ * any combination of characters and conversion specifications (%).
+ *
+ *
+ * @param {String[] | String} properties.am_pm
+ *
+ * The appropriate representation of the ante-meridiem and post-meridiem
+ * strings, corresponding to the %p conversion specification. The property
+ * must be either an array of 2 strings or a string consisting of 2
+ * semicolon-separated substrings, each surrounded by double-quotes.
+ * The first string must represent the ante-meridiem designation, the
+ * last string the post-meridiem designation.
+ *
+ *
+ * @throws @throws Error on a undefined or invalid locale property.
+ */
+jsworld.Locale = function(properties) {
+
+
+ /**
+ * @private
+ *
+ * @description Identifies the class for internal library purposes.
+ */
+ this._className = "jsworld.Locale";
+
+
+ /**
+ * @private
+ *
+ * @description Parses a day or month name definition list, which
+ * could be a ready JS array, e.g. ["Mon", "Tue", "Wed"...] or
+ * it could be a string formatted according to the classic POSIX
+ * definition e.g. "Mon";"Tue";"Wed";...
+ *
+ * @param {String[] | String} namesAn array or string defining
+ * the week/month names.
+ * @param {integer Number} expectedItems The number of expected list
+ * items, e.g. 7 for weekdays, 12 for months.
+ *
+ * @returns {String[]} The parsed (and checked) items.
+ *
+ * @throws Error on missing definition, unexpected item count or
+ * missing double-quotes.
+ */
+ this._parseList = function(names, expectedItems) {
+
+ var array = [];
+
+ if (names == null) {
+ throw "Names not defined";
+ }
+ else if (typeof names == "object") {
+ // we got a ready array
+ array = names;
+ }
+ else if (typeof names == "string") {
+ // we got the names in the classic POSIX form, do parse
+ array = names.split(";", expectedItems);
+
+ for (var i = 0; i < array.length; i++) {
+ // check for and strip double quotes
+ if (array[i][0] == "\"" && array[i][array[i].length - 1] == "\"")
+ array[i] = array[i].slice(1, -1);
+ else
+ throw "Missing double quotes";
+ }
+ }
+ else {
+ throw "Names must be an array or a string";
+ }
+
+ if (array.length != expectedItems)
+ throw "Expected " + expectedItems + " items, got " + array.length;
+
+ return array;
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Validates a date/time format string, such as "H:%M:%S".
+ * Checks that the argument is of type "string" and is not empty.
+ *
+ * @param {String} formatString The format string.
+ *
+ * @returns {String} The validated string.
+ *
+ * @throws Error on null or empty string.
+ */
+ this._validateFormatString = function(formatString) {
+
+ if (typeof formatString == "string" && formatString.length > 0)
+ return formatString;
+ else
+ throw "Empty or no string";
+ };
+
+
+ // LC_NUMERIC
+
+ if (properties == null || typeof properties != "object")
+ throw "Error: Invalid/missing locale properties";
+
+
+ if (typeof properties.decimal_point != "string")
+ throw "Error: Invalid/missing decimal_point property";
+
+ this.decimal_point = properties.decimal_point;
+
+
+ if (typeof properties.thousands_sep != "string")
+ throw "Error: Invalid/missing thousands_sep property";
+
+ this.thousands_sep = properties.thousands_sep;
+
+
+ if (typeof properties.grouping != "string")
+ throw "Error: Invalid/missing grouping property";
+
+ this.grouping = properties.grouping;
+
+
+ // LC_MONETARY
+
+ if (typeof properties.int_curr_symbol != "string")
+ throw "Error: Invalid/missing int_curr_symbol property";
+
+ if (! /[A-Za-z]{3}.?/.test(properties.int_curr_symbol))
+ throw "Error: Invalid int_curr_symbol property";
+
+ this.int_curr_symbol = properties.int_curr_symbol;
+
+
+ if (typeof properties.currency_symbol != "string")
+ throw "Error: Invalid/missing currency_symbol property";
+
+ this.currency_symbol = properties.currency_symbol;
+
+
+ if (typeof properties.frac_digits != "number" && properties.frac_digits < 0)
+ throw "Error: Invalid/missing frac_digits property";
+
+ this.frac_digits = properties.frac_digits;
+
+
+ // may be empty string/null for currencies with no fractional part
+ if (properties.mon_decimal_point === null || properties.mon_decimal_point == "") {
+
+ if (this.frac_digits > 0)
+ throw "Error: Undefined mon_decimal_point property";
+ else
+ properties.mon_decimal_point = "";
+ }
+
+ if (typeof properties.mon_decimal_point != "string")
+ throw "Error: Invalid/missing mon_decimal_point property";
+
+ this.mon_decimal_point = properties.mon_decimal_point;
+
+
+ if (typeof properties.mon_thousands_sep != "string")
+ throw "Error: Invalid/missing mon_thousands_sep property";
+
+ this.mon_thousands_sep = properties.mon_thousands_sep;
+
+
+ if (typeof properties.mon_grouping != "string")
+ throw "Error: Invalid/missing mon_grouping property";
+
+ this.mon_grouping = properties.mon_grouping;
+
+
+ if (typeof properties.positive_sign != "string")
+ throw "Error: Invalid/missing positive_sign property";
+
+ this.positive_sign = properties.positive_sign;
+
+
+ if (typeof properties.negative_sign != "string")
+ throw "Error: Invalid/missing negative_sign property";
+
+ this.negative_sign = properties.negative_sign;
+
+
+
+ if (properties.p_cs_precedes !== 0 && properties.p_cs_precedes !== 1)
+ throw "Error: Invalid/missing p_cs_precedes property, must be 0 or 1";
+
+ this.p_cs_precedes = properties.p_cs_precedes;
+
+
+ if (properties.n_cs_precedes !== 0 && properties.n_cs_precedes !== 1)
+ throw "Error: Invalid/missing n_cs_precedes, must be 0 or 1";
+
+ this.n_cs_precedes = properties.n_cs_precedes;
+
+
+ if (properties.p_sep_by_space !== 0 &&
+ properties.p_sep_by_space !== 1 &&
+ properties.p_sep_by_space !== 2)
+ throw "Error: Invalid/missing p_sep_by_space property, must be 0, 1 or 2";
+
+ this.p_sep_by_space = properties.p_sep_by_space;
+
+
+ if (properties.n_sep_by_space !== 0 &&
+ properties.n_sep_by_space !== 1 &&
+ properties.n_sep_by_space !== 2)
+ throw "Error: Invalid/missing n_sep_by_space property, must be 0, 1, or 2";
+
+ this.n_sep_by_space = properties.n_sep_by_space;
+
+
+ if (properties.p_sign_posn !== 0 &&
+ properties.p_sign_posn !== 1 &&
+ properties.p_sign_posn !== 2 &&
+ properties.p_sign_posn !== 3 &&
+ properties.p_sign_posn !== 4)
+ throw "Error: Invalid/missing p_sign_posn property, must be 0, 1, 2, 3 or 4";
+
+ this.p_sign_posn = properties.p_sign_posn;
+
+
+ if (properties.n_sign_posn !== 0 &&
+ properties.n_sign_posn !== 1 &&
+ properties.n_sign_posn !== 2 &&
+ properties.n_sign_posn !== 3 &&
+ properties.n_sign_posn !== 4)
+ throw "Error: Invalid/missing n_sign_posn property, must be 0, 1, 2, 3 or 4";
+
+ this.n_sign_posn = properties.n_sign_posn;
+
+
+ if (typeof properties.int_frac_digits != "number" && properties.int_frac_digits < 0)
+ throw "Error: Invalid/missing int_frac_digits property";
+
+ this.int_frac_digits = properties.int_frac_digits;
+
+
+ if (properties.int_p_cs_precedes !== 0 && properties.int_p_cs_precedes !== 1)
+ throw "Error: Invalid/missing int_p_cs_precedes property, must be 0 or 1";
+
+ this.int_p_cs_precedes = properties.int_p_cs_precedes;
+
+
+ if (properties.int_n_cs_precedes !== 0 && properties.int_n_cs_precedes !== 1)
+ throw "Error: Invalid/missing int_n_cs_precedes property, must be 0 or 1";
+
+ this.int_n_cs_precedes = properties.int_n_cs_precedes;
+
+
+ if (properties.int_p_sep_by_space !== 0 &&
+ properties.int_p_sep_by_space !== 1 &&
+ properties.int_p_sep_by_space !== 2)
+ throw "Error: Invalid/missing int_p_sep_by_spacev, must be 0, 1 or 2";
+
+ this.int_p_sep_by_space = properties.int_p_sep_by_space;
+
+
+ if (properties.int_n_sep_by_space !== 0 &&
+ properties.int_n_sep_by_space !== 1 &&
+ properties.int_n_sep_by_space !== 2)
+ throw "Error: Invalid/missing int_n_sep_by_space property, must be 0, 1, or 2";
+
+ this.int_n_sep_by_space = properties.int_n_sep_by_space;
+
+
+ if (properties.int_p_sign_posn !== 0 &&
+ properties.int_p_sign_posn !== 1 &&
+ properties.int_p_sign_posn !== 2 &&
+ properties.int_p_sign_posn !== 3 &&
+ properties.int_p_sign_posn !== 4)
+ throw "Error: Invalid/missing int_p_sign_posn property, must be 0, 1, 2, 3 or 4";
+
+ this.int_p_sign_posn = properties.int_p_sign_posn;
+
+
+ if (properties.int_n_sign_posn !== 0 &&
+ properties.int_n_sign_posn !== 1 &&
+ properties.int_n_sign_posn !== 2 &&
+ properties.int_n_sign_posn !== 3 &&
+ properties.int_n_sign_posn !== 4)
+ throw "Error: Invalid/missing int_n_sign_posn property, must be 0, 1, 2, 3 or 4";
+
+ this.int_n_sign_posn = properties.int_n_sign_posn;
+
+
+ // LC_TIME
+
+ if (properties == null || typeof properties != "object")
+ throw "Error: Invalid/missing time locale properties";
+
+
+ // parse the supported POSIX LC_TIME properties
+
+ // abday
+ try {
+ this.abday = this._parseList(properties.abday, 7);
+ }
+ catch (error) {
+ throw "Error: Invalid abday property: " + error;
+ }
+
+ // day
+ try {
+ this.day = this._parseList(properties.day, 7);
+ }
+ catch (error) {
+ throw "Error: Invalid day property: " + error;
+ }
+
+ // abmon
+ try {
+ this.abmon = this._parseList(properties.abmon, 12);
+ } catch (error) {
+ throw "Error: Invalid abmon property: " + error;
+ }
+
+ // mon
+ try {
+ this.mon = this._parseList(properties.mon, 12);
+ } catch (error) {
+ throw "Error: Invalid mon property: " + error;
+ }
+
+ // d_fmt
+ try {
+ this.d_fmt = this._validateFormatString(properties.d_fmt);
+ } catch (error) {
+ throw "Error: Invalid d_fmt property: " + error;
+ }
+
+ // t_fmt
+ try {
+ this.t_fmt = this._validateFormatString(properties.t_fmt);
+ } catch (error) {
+ throw "Error: Invalid t_fmt property: " + error;
+ }
+
+ // d_t_fmt
+ try {
+ this.d_t_fmt = this._validateFormatString(properties.d_t_fmt);
+ } catch (error) {
+ throw "Error: Invalid d_t_fmt property: " + error;
+ }
+
+ // am_pm
+ try {
+ var am_pm_strings = this._parseList(properties.am_pm, 2);
+ this.am = am_pm_strings[0];
+ this.pm = am_pm_strings[1];
+ } catch (error) {
+ // ignore empty/null string errors
+ this.am = "";
+ this.pm = "";
+ }
+
+
+ /**
+ * @public
+ *
+ * @description Returns the abbreviated name of the specified weekday.
+ *
+ * @param {integer Number} [weekdayNum] An integer between 0 and 6. Zero
+ * corresponds to Sunday, one to Monday, etc. If omitted the
+ * method will return an array of all abbreviated weekday
+ * names.
+ *
+ * @returns {String | String[]} The abbreviated name of the specified weekday
+ * or an array of all abbreviated weekday names.
+ *
+ * @throws Error on invalid argument.
+ */
+ this.getAbbreviatedWeekdayName = function(weekdayNum) {
+
+ if (typeof weekdayNum == "undefined" || weekdayNum === null)
+ return this.abday;
+
+ if (! jsworld._isInteger(weekdayNum) || weekdayNum < 0 || weekdayNum > 6)
+ throw "Error: Invalid weekday argument, must be an integer [0..6]";
+
+ return this.abday[weekdayNum];
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Returns the name of the specified weekday.
+ *
+ * @param {integer Number} [weekdayNum] An integer between 0 and 6. Zero
+ * corresponds to Sunday, one to Monday, etc. If omitted the
+ * method will return an array of all weekday names.
+ *
+ * @returns {String | String[]} The name of the specified weekday or an
+ * array of all weekday names.
+ *
+ * @throws Error on invalid argument.
+ */
+ this.getWeekdayName = function(weekdayNum) {
+
+ if (typeof weekdayNum == "undefined" || weekdayNum === null)
+ return this.day;
+
+ if (! jsworld._isInteger(weekdayNum) || weekdayNum < 0 || weekdayNum > 6)
+ throw "Error: Invalid weekday argument, must be an integer [0..6]";
+
+ return this.day[weekdayNum];
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Returns the abbreviated name of the specified month.
+ *
+ * @param {integer Number} [monthNum] An integer between 0 and 11. Zero
+ * corresponds to January, one to February, etc. If omitted the
+ * method will return an array of all abbreviated month names.
+ *
+ * @returns {String | String[]} The abbreviated name of the specified month
+ * or an array of all abbreviated month names.
+ *
+ * @throws Error on invalid argument.
+ */
+ this.getAbbreviatedMonthName = function(monthNum) {
+
+ if (typeof monthNum == "undefined" || monthNum === null)
+ return this.abmon;
+
+ if (! jsworld._isInteger(monthNum) || monthNum < 0 || monthNum > 11)
+ throw "Error: Invalid month argument, must be an integer [0..11]";
+
+ return this.abmon[monthNum];
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Returns the name of the specified month.
+ *
+ * @param {integer Number} [monthNum] An integer between 0 and 11. Zero
+ * corresponds to January, one to February, etc. If omitted the
+ * method will return an array of all month names.
+ *
+ * @returns {String | String[]} The name of the specified month or an array
+ * of all month names.
+ *
+ * @throws Error on invalid argument.
+ */
+ this.getMonthName = function(monthNum) {
+
+ if (typeof monthNum == "undefined" || monthNum === null)
+ return this.mon;
+
+ if (! jsworld._isInteger(monthNum) || monthNum < 0 || monthNum > 11)
+ throw "Error: Invalid month argument, must be an integer [0..11]";
+
+ return this.mon[monthNum];
+ };
+
+
+
+ /**
+ * @public
+ *
+ * @description Gets the decimal delimiter (radix) character for
+ * numeric quantities.
+ *
+ * @returns {String} The radix character.
+ */
+ this.getDecimalPoint = function() {
+
+ return this.decimal_point;
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the local shorthand currency symbol.
+ *
+ * @returns {String} The currency symbol.
+ */
+ this.getCurrencySymbol = function() {
+
+ return this.currency_symbol;
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the internaltion currency symbol (ISO-4217 code).
+ *
+ * @returns {String} The international currency symbol.
+ */
+ this.getIntCurrencySymbol = function() {
+
+ return this.int_curr_symbol.substring(0,3);
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the position of the local (shorthand) currency
+ * symbol relative to the amount. Assumes a non-negative amount.
+ *
+ * @returns {Boolean} True if the symbol precedes the amount, false if
+ * the symbol succeeds the amount.
+ */
+ this.currencySymbolPrecedes = function() {
+
+ if (this.p_cs_precedes == 1)
+ return true;
+ else
+ return false;
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the position of the international (ISO-4217 code)
+ * currency symbol relative to the amount. Assumes a non-negative
+ * amount.
+ *
+ * @returns {Boolean} True if the symbol precedes the amount, false if
+ * the symbol succeeds the amount.
+ */
+ this.intCurrencySymbolPrecedes = function() {
+
+ if (this.int_p_cs_precedes == 1)
+ return true;
+ else
+ return false;
+
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the decimal delimiter (radix) for monetary
+ * quantities.
+ *
+ * @returns {String} The radix character.
+ */
+ this.getMonetaryDecimalPoint = function() {
+
+ return this.mon_decimal_point;
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the number of fractional digits for local
+ * (shorthand) symbol formatting.
+ *
+ * @returns {integer Number} The number of fractional digits.
+ */
+ this.getFractionalDigits = function() {
+
+ return this.frac_digits;
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the number of fractional digits for
+ * international (ISO-4217 code) formatting.
+ *
+ * @returns {integer Number} The number of fractional digits.
+ */
+ this.getIntFractionalDigits = function() {
+
+ return this.int_frac_digits;
+ };
+};
+
+
+
+/**
+ * @class
+ * Class for localised formatting of numbers.
+ *
+ *
See:
+ * POSIX LC_NUMERIC.
+ *
+ *
+ * @public
+ * @constructor
+ * @description Creates a new numeric formatter for the specified locale.
+ *
+ * @param {jsworld.Locale} locale A locale object specifying the required
+ * POSIX LC_NUMERIC formatting properties.
+ *
+ * @throws Error on constructor failure.
+ */
+jsworld.NumericFormatter = function(locale) {
+
+ if (typeof locale != "object" || locale._className != "jsworld.Locale")
+ throw "Constructor error: You must provide a valid jsworld.Locale instance";
+
+ this.lc = locale;
+
+
+ /**
+ * @public
+ *
+ * @description Formats a decimal numeric value according to the preset
+ * locale.
+ *
+ * @param {Number|String} number The number to format.
+ * @param {String} [options] Options to modify the formatted output:
+ *
+ *
"^" suppress grouping
+ *
"+" force positive sign for positive amounts
+ *
"~" suppress positive/negative sign
+ *
".n" specify decimal precision 'n'
+ *
+ *
+ * @returns {String} The formatted number.
+ *
+ * @throws "Error: Invalid input" on bad input.
+ */
+ this.format = function(number, options) {
+
+ if (typeof number == "string")
+ number = jsworld._trim(number);
+
+ if (! jsworld._isNumber(number))
+ throw "Error: The input is not a number";
+
+ var floatAmount = parseFloat(number, 10);
+
+ // get the required precision
+ var reqPrecision = jsworld._getPrecision(options);
+
+ // round to required precision
+ if (reqPrecision != -1)
+ floatAmount = Math.round(floatAmount * Math.pow(10, reqPrecision)) / Math.pow(10, reqPrecision);
+
+
+ // convert the float number to string and parse into
+ // object with properties integer and fraction
+ var parsedAmount = jsworld._splitNumber(String(floatAmount));
+
+ // format integer part with grouping chars
+ var formattedIntegerPart;
+
+ if (floatAmount === 0)
+ formattedIntegerPart = "0";
+ else
+ formattedIntegerPart = jsworld._hasOption("^", options) ?
+ parsedAmount.integer :
+ jsworld._formatIntegerPart(parsedAmount.integer,
+ this.lc.grouping,
+ this.lc.thousands_sep);
+
+ // format the fractional part
+ var formattedFractionPart =
+ reqPrecision != -1 ?
+ jsworld._formatFractionPart(parsedAmount.fraction, reqPrecision) :
+ parsedAmount.fraction;
+
+
+ // join the integer and fraction parts using the decimal_point property
+ var formattedAmount =
+ formattedFractionPart.length ?
+ formattedIntegerPart + this.lc.decimal_point + formattedFractionPart :
+ formattedIntegerPart;
+
+ // prepend sign?
+ if (jsworld._hasOption("~", options) || floatAmount === 0) {
+ // suppress both '+' and '-' signs, i.e. return abs value
+ return formattedAmount;
+ }
+ else {
+ if (jsworld._hasOption("+", options) || floatAmount < 0) {
+ if (floatAmount > 0)
+ // force '+' sign for positive amounts
+ return "+" + formattedAmount;
+ else if (floatAmount < 0)
+ // prepend '-' sign
+ return "-" + formattedAmount;
+ else
+ // zero case
+ return formattedAmount;
+ }
+ else {
+ // positive amount with no '+' sign
+ return formattedAmount;
+ }
+ }
+ };
+};
+
+
+/**
+ * @class
+ * Class for localised formatting of dates and times.
+ *
+ *
See:
+ * POSIX LC_TIME.
+ *
+ * @public
+ * @constructor
+ * @description Creates a new date/time formatter for the specified locale.
+ *
+ * @param {jsworld.Locale} locale A locale object specifying the required
+ * POSIX LC_TIME formatting properties.
+ *
+ * @throws Error on constructor failure.
+ */
+jsworld.DateTimeFormatter = function(locale) {
+
+
+ if (typeof locale != "object" || locale._className != "jsworld.Locale")
+ throw "Constructor error: You must provide a valid jsworld.Locale instance.";
+
+ this.lc = locale;
+
+
+ /**
+ * @public
+ *
+ * @description Formats a date according to the preset locale.
+ *
+ * @param {Date|String} date A valid Date object instance or a string
+ * containing a valid ISO-8601 formatted date, e.g. "2010-31-03"
+ * or "2010-03-31 23:59:59".
+ *
+ * @returns {String} The formatted date
+ *
+ * @throws Error on invalid date argument
+ */
+ this.formatDate = function(date) {
+
+ var d = null;
+
+ if (typeof date == "string") {
+ // assume ISO-8601 date string
+ try {
+ d = jsworld.parseIsoDate(date);
+ } catch (error) {
+ // try full ISO-8601 date/time string
+ d = jsworld.parseIsoDateTime(date);
+ }
+ }
+ else if (date !== null && typeof date == "object") {
+ // assume ready Date object
+ d = date;
+ }
+ else {
+ throw "Error: Invalid date argument, must be a Date object or an ISO-8601 date/time string";
+ }
+
+ return this._applyFormatting(d, this.lc.d_fmt);
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Formats a time according to the preset locale.
+ *
+ * @param {Date|String} date A valid Date object instance or a string
+ * containing a valid ISO-8601 formatted time, e.g. "23:59:59"
+ * or "2010-03-31 23:59:59".
+ *
+ * @returns {String} The formatted time.
+ *
+ * @throws Error on invalid date argument.
+ */
+ this.formatTime = function(date) {
+
+ var d = null;
+
+ if (typeof date == "string") {
+ // assume ISO-8601 time string
+ try {
+ d = jsworld.parseIsoTime(date);
+ } catch (error) {
+ // try full ISO-8601 date/time string
+ d = jsworld.parseIsoDateTime(date);
+ }
+ }
+ else if (date !== null && typeof date == "object") {
+ // assume ready Date object
+ d = date;
+ }
+ else {
+ throw "Error: Invalid date argument, must be a Date object or an ISO-8601 date/time string";
+ }
+
+ return this._applyFormatting(d, this.lc.t_fmt);
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Formats a date/time value according to the preset
+ * locale.
+ *
+ * @param {Date|String} date A valid Date object instance or a string
+ * containing a valid ISO-8601 formatted date/time, e.g.
+ * "2010-03-31 23:59:59".
+ *
+ * @returns {String} The formatted time.
+ *
+ * @throws Error on invalid argument.
+ */
+ this.formatDateTime = function(date) {
+
+ var d = null;
+
+ if (typeof date == "string") {
+ // assume ISO-8601 format
+ d = jsworld.parseIsoDateTime(date);
+ }
+ else if (date !== null && typeof date == "object") {
+ // assume ready Date object
+ d = date;
+ }
+ else {
+ throw "Error: Invalid date argument, must be a Date object or an ISO-8601 date/time string";
+ }
+
+ return this._applyFormatting(d, this.lc.d_t_fmt);
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Apples formatting to the Date object according to the
+ * format string.
+ *
+ * @param {Date} d A valid Date instance.
+ * @param {String} s The formatting string with '%' placeholders.
+ *
+ * @returns {String} The formatted string.
+ */
+ this._applyFormatting = function(d, s) {
+
+ s = s.replace(/%%/g, '%');
+ s = s.replace(/%a/g, this.lc.abday[d.getDay()]);
+ s = s.replace(/%A/g, this.lc.day[d.getDay()]);
+ s = s.replace(/%b/g, this.lc.abmon[d.getMonth()]);
+ s = s.replace(/%B/g, this.lc.mon[d.getMonth()]);
+ s = s.replace(/%d/g, jsworld._zeroPad(d.getDate(), 2));
+ s = s.replace(/%e/g, jsworld._spacePad(d.getDate(), 2));
+ s = s.replace(/%F/g, d.getFullYear() +
+ "-" +
+ jsworld._zeroPad(d.getMonth()+1, 2) +
+ "-" +
+ jsworld._zeroPad(d.getDate(), 2));
+ s = s.replace(/%h/g, this.lc.abmon[d.getMonth()]); // same as %b
+ s = s.replace(/%H/g, jsworld._zeroPad(d.getHours(), 2));
+ s = s.replace(/%I/g, jsworld._zeroPad(this._hours12(d.getHours()), 2));
+ s = s.replace(/%k/g, d.getHours());
+ s = s.replace(/%l/g, this._hours12(d.getHours()));
+ s = s.replace(/%m/g, jsworld._zeroPad(d.getMonth()+1, 2));
+ s = s.replace(/%n/g, "\n");
+ s = s.replace(/%M/g, jsworld._zeroPad(d.getMinutes(), 2));
+ s = s.replace(/%p/g, this._getAmPm(d.getHours()));
+ s = s.replace(/%P/g, this._getAmPm(d.getHours()).toLocaleLowerCase()); // safe?
+ s = s.replace(/%R/g, jsworld._zeroPad(d.getHours(), 2) +
+ ":" +
+ jsworld._zeroPad(d.getMinutes(), 2));
+ s = s.replace(/%S/g, jsworld._zeroPad(d.getSeconds(), 2));
+ s = s.replace(/%T/g, jsworld._zeroPad(d.getHours(), 2) +
+ ":" +
+ jsworld._zeroPad(d.getMinutes(), 2) +
+ ":" +
+ jsworld._zeroPad(d.getSeconds(), 2));
+ s = s.replace(/%w/g, this.lc.day[d.getDay()]);
+ s = s.replace(/%y/g, new String(d.getFullYear()).substring(2));
+ s = s.replace(/%Y/g, d.getFullYear());
+
+ s = s.replace(/%Z/g, ""); // to do: ignored until a reliable TMZ method found
+
+ s = s.replace(/%[a-zA-Z]/g, ""); // ignore all other % sequences
+
+ return s;
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Does 24 to 12 hour conversion.
+ *
+ * @param {integer Number} hour24 Hour [0..23].
+ *
+ * @returns {integer Number} Corresponding hour [1..12].
+ */
+ this._hours12 = function(hour24) {
+
+ if (hour24 === 0)
+ return 12; // 00h is 12AM
+
+ else if (hour24 > 12)
+ return hour24 - 12; // 1PM to 11PM
+
+ else
+ return hour24; // 1AM to 12PM
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Gets the appropriate localised AM or PM string depending
+ * on the day hour. Special cases: midnight is 12AM, noon is 12PM.
+ *
+ * @param {integer Number} hour24 Hour [0..23].
+ *
+ * @returns {String} The corresponding localised AM or PM string.
+ */
+ this._getAmPm = function(hour24) {
+
+ if (hour24 < 12)
+ return this.lc.am;
+ else
+ return this.lc.pm;
+ };
+};
+
+
+
+/**
+ * @class Class for localised formatting of currency amounts.
+ *
+ *
See:
+ * POSIX LC_MONETARY.
+ *
+ * @public
+ * @constructor
+ * @description Creates a new monetary formatter for the specified locale.
+ *
+ * @param {jsworld.Locale} locale A locale object specifying the required
+ * POSIX LC_MONETARY formatting properties.
+ * @param {String} [currencyCode] Set the currency explicitly by
+ * passing its international ISO-4217 code, e.g. "USD", "EUR", "GBP".
+ * Use this optional parameter to override the default local currency
+ * @param {String} [altIntSymbol] Non-local currencies are formatted
+ * with their international ISO-4217 code to prevent ambiguity.
+ * Use this optional argument to force a different symbol, such as the
+ * currency's shorthand sign. This is mostly useful when the shorthand
+ * sign is both internationally recognised and identifies the currency
+ * uniquely (e.g. the Euro sign).
+ *
+ * @throws Error on constructor failure.
+ */
+jsworld.MonetaryFormatter = function(locale, currencyCode, altIntSymbol) {
+
+ if (typeof locale != "object" || locale._className != "jsworld.Locale")
+ throw "Constructor error: You must provide a valid jsworld.Locale instance";
+
+ this.lc = locale;
+
+ /**
+ * @private
+ * @description Lookup table to determine the fraction digits for a
+ * specific currency; most currencies subdivide at 1/100 (2 fractional
+ * digits), so we store only those that deviate from the default.
+ *
+ *
The data is from Unicode's CLDR version 1.7.0. The two currencies
+ * with non-decimal subunits (MGA and MRO) are marked as having no
+ * fractional digits as well as all currencies that have no subunits
+ * in circulation.
+ *
+ *
It is "hard-wired" for referential convenience and is only looked
+ * up when an overriding currencyCode parameter is supplied.
+ */
+ this.currencyFractionDigits = {
+ "AFN" : 0, "ALL" : 0, "AMD" : 0, "BHD" : 3, "BIF" : 0,
+ "BYR" : 0, "CLF" : 0, "CLP" : 0, "COP" : 0, "CRC" : 0,
+ "DJF" : 0, "GNF" : 0, "GYD" : 0, "HUF" : 0, "IDR" : 0,
+ "IQD" : 0, "IRR" : 0, "ISK" : 0, "JOD" : 3, "JPY" : 0,
+ "KMF" : 0, "KRW" : 0, "KWD" : 3, "LAK" : 0, "LBP" : 0,
+ "LYD" : 3, "MGA" : 0, "MMK" : 0, "MNT" : 0, "MRO" : 0,
+ "MUR" : 0, "OMR" : 3, "PKR" : 0, "PYG" : 0, "RSD" : 0,
+ "RWF" : 0, "SLL" : 0, "SOS" : 0, "STD" : 0, "SYP" : 0,
+ "TND" : 3, "TWD" : 0, "TZS" : 0, "UGX" : 0, "UZS" : 0,
+ "VND" : 0, "VUV" : 0, "XAF" : 0, "XOF" : 0, "XPF" : 0,
+ "YER" : 0, "ZMK" : 0
+ };
+
+
+ // optional currencyCode argument?
+ if (typeof currencyCode == "string") {
+ // user wanted to override the local currency
+ this.currencyCode = currencyCode.toUpperCase();
+
+ // must override the frac digits too, for some
+ // currencies have 0, 2 or 3!
+ var numDigits = this.currencyFractionDigits[this.currencyCode];
+ if (typeof numDigits != "number")
+ numDigits = 2; // default for most currencies
+ this.lc.frac_digits = numDigits;
+ this.lc.int_frac_digits = numDigits;
+ }
+ else {
+ // use local currency
+ this.currencyCode = this.lc.int_curr_symbol.substring(0,3).toUpperCase();
+ }
+
+ // extract intl. currency separator
+ this.intSep = this.lc.int_curr_symbol.charAt(3);
+
+ // flag local or intl. sign formatting?
+ if (this.currencyCode == this.lc.int_curr_symbol.substring(0,3)) {
+ // currency matches the local one? ->
+ // formatting with local symbol and parameters
+ this.internationalFormatting = false;
+ this.curSym = this.lc.currency_symbol;
+ }
+ else {
+ // currency doesn't match the local ->
+
+ // do we have an overriding currency symbol?
+ if (typeof altIntSymbol == "string") {
+ // -> force formatting with local parameters, using alt symbol
+ this.curSym = altIntSymbol;
+ this.internationalFormatting = false;
+ }
+ else {
+ // -> force formatting with intl. sign and parameters
+ this.internationalFormatting = true;
+ }
+ }
+
+
+ /**
+ * @public
+ *
+ * @description Gets the currency symbol used in formatting.
+ *
+ * @returns {String} The currency symbol.
+ */
+ this.getCurrencySymbol = function() {
+
+ return this.curSym;
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the position of the currency symbol relative to
+ * the amount. Assumes a non-negative amount and local formatting.
+ *
+ * @param {String} intFlag Optional flag to force international
+ * formatting by passing the string "i".
+ *
+ * @returns {Boolean} True if the symbol precedes the amount, false if
+ * the symbol succeeds the amount.
+ */
+ this.currencySymbolPrecedes = function(intFlag) {
+
+ if (typeof intFlag == "string" && intFlag == "i") {
+ // international formatting was forced
+ if (this.lc.int_p_cs_precedes == 1)
+ return true;
+ else
+ return false;
+
+ }
+ else {
+ // check whether local formatting is on or off
+ if (this.internationalFormatting) {
+ if (this.lc.int_p_cs_precedes == 1)
+ return true;
+ else
+ return false;
+ }
+ else {
+ if (this.lc.p_cs_precedes == 1)
+ return true;
+ else
+ return false;
+ }
+ }
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the decimal delimiter (radix) used in formatting.
+ *
+ * @returns {String} The radix character.
+ */
+ this.getDecimalPoint = function() {
+
+ return this.lc.mon_decimal_point;
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Gets the number of fractional digits. Assumes local
+ * formatting.
+ *
+ * @param {String} intFlag Optional flag to force international
+ * formatting by passing the string "i".
+ *
+ * @returns {integer Number} The number of fractional digits.
+ */
+ this.getFractionalDigits = function(intFlag) {
+
+ if (typeof intFlag == "string" && intFlag == "i") {
+ // international formatting was forced
+ return this.lc.int_frac_digits;
+ }
+ else {
+ // check whether local formatting is on or off
+ if (this.internationalFormatting)
+ return this.lc.int_frac_digits;
+ else
+ return this.lc.frac_digits;
+ }
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Formats a monetary amount according to the preset
+ * locale.
+ *
+ *
+ * For local currencies the native shorthand symbol will be used for
+ * formatting.
+ * Example:
+ * locale is en_US
+ * currency is USD
+ * -> the "$" symbol will be used, e.g. $123.45
+ *
+ * For non-local currencies the international ISO-4217 code will be
+ * used for formatting.
+ * Example:
+ * locale is en_US (which has USD as currency)
+ * currency is EUR
+ * -> the ISO three-letter code will be used, e.g. EUR 123.45
+ *
+ * If the currency is non-local, but an alternative currency symbol was
+ * provided, this will be used instead.
+ * Example
+ * locale is en_US (which has USD as currency)
+ * currency is EUR
+ * an alternative symbol is provided - "€"
+ * -> the alternative symbol will be used, e.g. €123.45
+ *
+ *
+ * @param {Number|String} amount The amount to format as currency.
+ * @param {String} [options] Options to modify the formatted output:
+ *
+ *
"^" suppress grouping
+ *
"!" suppress the currency symbol
+ *
"~" suppress the currency symbol and the sign (positive or negative)
+ *
"i" force international sign (ISO-4217 code) formatting
+ *
".n" specify decimal precision
+ *
+ * @returns The formatted currency amount as string.
+ *
+ * @throws "Error: Invalid amount" on bad amount.
+ */
+ this.format = function(amount, options) {
+
+ // if the amount is passed as string, check that it parses to a float
+ var floatAmount;
+
+ if (typeof amount == "string") {
+ amount = jsworld._trim(amount);
+ floatAmount = parseFloat(amount);
+
+ if (typeof floatAmount != "number" || isNaN(floatAmount))
+ throw "Error: Amount string not a number";
+ }
+ else if (typeof amount == "number") {
+ floatAmount = amount;
+ }
+ else {
+ throw "Error: Amount not a number";
+ }
+
+ // get the required precision, ".n" option arg overrides default locale config
+ var reqPrecision = jsworld._getPrecision(options);
+
+ if (reqPrecision == -1) {
+ if (this.internationalFormatting || jsworld._hasOption("i", options))
+ reqPrecision = this.lc.int_frac_digits;
+ else
+ reqPrecision = this.lc.frac_digits;
+ }
+
+ // round
+ floatAmount = Math.round(floatAmount * Math.pow(10, reqPrecision)) / Math.pow(10, reqPrecision);
+
+
+ // convert the float amount to string and parse into
+ // object with properties integer and fraction
+ var parsedAmount = jsworld._splitNumber(String(floatAmount));
+
+ // format integer part with grouping chars
+ var formattedIntegerPart;
+
+ if (floatAmount === 0)
+ formattedIntegerPart = "0";
+ else
+ formattedIntegerPart = jsworld._hasOption("^", options) ?
+ parsedAmount.integer :
+ jsworld._formatIntegerPart(parsedAmount.integer,
+ this.lc.mon_grouping,
+ this.lc.mon_thousands_sep);
+
+
+ // format the fractional part
+ var formattedFractionPart;
+
+ if (reqPrecision == -1) {
+ // pad fraction with trailing zeros accoring to default locale [int_]frac_digits
+ if (this.internationalFormatting || jsworld._hasOption("i", options))
+ formattedFractionPart =
+ jsworld._formatFractionPart(parsedAmount.fraction, this.lc.int_frac_digits);
+ else
+ formattedFractionPart =
+ jsworld._formatFractionPart(parsedAmount.fraction, this.lc.frac_digits);
+ }
+ else {
+ // pad fraction with trailing zeros according to optional format parameter
+ formattedFractionPart =
+ jsworld._formatFractionPart(parsedAmount.fraction, reqPrecision);
+ }
+
+
+ // join integer and decimal parts using the mon_decimal_point property
+ var quantity;
+
+ if (this.lc.frac_digits > 0 || formattedFractionPart.length)
+ quantity = formattedIntegerPart + this.lc.mon_decimal_point + formattedFractionPart;
+ else
+ quantity = formattedIntegerPart;
+
+
+ // do final formatting with sign and symbol
+ if (jsworld._hasOption("~", options)) {
+ return quantity;
+ }
+ else {
+ var suppressSymbol = jsworld._hasOption("!", options) ? true : false;
+
+ var sign = floatAmount < 0 ? "-" : "+";
+
+ if (this.internationalFormatting || jsworld._hasOption("i", options)) {
+
+ // format with ISO-4217 code (suppressed or not)
+ if (suppressSymbol)
+ return this._formatAsInternationalCurrencyWithNoSym(sign, quantity);
+ else
+ return this._formatAsInternationalCurrency(sign, quantity);
+ }
+ else {
+ // format with local currency code (suppressed or not)
+ if (suppressSymbol)
+ return this._formatAsLocalCurrencyWithNoSym(sign, quantity);
+ else
+ return this._formatAsLocalCurrency(sign, quantity);
+ }
+ }
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Assembles the final string with sign, separator and symbol as local
+ * currency.
+ *
+ * @param {String} sign The amount sign: "+" or "-".
+ * @param {String} q The formatted quantity (unsigned).
+ *
+ * @returns {String} The final formatted string.
+ */
+ this._formatAsLocalCurrency = function (sign, q) {
+
+ // assemble final formatted amount by going over all possible value combinations of:
+ // sign {+,-} , sign position {0,1,2,3,4} , separator {0,1,2} , symbol position {0,1}
+ if (sign == "+") {
+
+ // parentheses
+ if (this.lc.p_sign_posn === 0 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 0) {
+ return "(" + q + this.curSym + ")";
+ }
+ else if (this.lc.p_sign_posn === 0 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 1) {
+ return "(" + this.curSym + q + ")";
+ }
+ else if (this.lc.p_sign_posn === 0 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 0) {
+ return "(" + q + " " + this.curSym + ")";
+ }
+ else if (this.lc.p_sign_posn === 0 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 1) {
+ return "(" + this.curSym + " " + q + ")";
+ }
+
+ // sign before q + sym
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 0) {
+ return this.lc.positive_sign + q + this.curSym;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.curSym + q;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 0) {
+ return this.lc.positive_sign + q + " " + this.curSym;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.curSym + " " + q;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 0) {
+ return this.lc.positive_sign + " " + q + this.curSym;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + " " + this.curSym + q;
+ }
+
+ // sign after q + sym
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 0) {
+ return q + this.curSym + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 1) {
+ return this.curSym + q + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 0) {
+ return q + " " + this.curSym + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 1) {
+ return this.curSym + " " + q + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 0) {
+ return q + this.curSym + " " + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 1) {
+ return this.curSym + q + " " + this.lc.positive_sign;
+ }
+
+ // sign before sym
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 0) {
+ return q + this.lc.positive_sign + this.curSym;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.curSym + q;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 0) {
+ return q + " " + this.lc.positive_sign + this.curSym;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.curSym + " " + q;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 0) {
+ return q + this.lc.positive_sign + " " + this.curSym;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + " " + this.curSym + q;
+ }
+
+ // sign after symbol
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 0) {
+ return q + this.curSym + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 1) {
+ return this.curSym + this.lc.positive_sign + q;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 0) {
+ return q + " " + this.curSym + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 1) {
+ return this.curSym + this.lc.positive_sign + " " + q;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 0) {
+ return q + this.curSym + " " + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 1) {
+ return this.curSym + " " + this.lc.positive_sign + q;
+ }
+
+ }
+ else if (sign == "-") {
+
+ // parentheses enclose q + sym
+ if (this.lc.n_sign_posn === 0 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 0) {
+ return "(" + q + this.curSym + ")";
+ }
+ else if (this.lc.n_sign_posn === 0 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 1) {
+ return "(" + this.curSym + q + ")";
+ }
+ else if (this.lc.n_sign_posn === 0 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 0) {
+ return "(" + q + " " + this.curSym + ")";
+ }
+ else if (this.lc.n_sign_posn === 0 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 1) {
+ return "(" + this.curSym + " " + q + ")";
+ }
+
+ // sign before q + sym
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 0) {
+ return this.lc.negative_sign + q + this.curSym;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.curSym + q;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 0) {
+ return this.lc.negative_sign + q + " " + this.curSym;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.curSym + " " + q;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 0) {
+ return this.lc.negative_sign + " " + q + this.curSym;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + " " + this.curSym + q;
+ }
+
+ // sign after q + sym
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 0) {
+ return q + this.curSym + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 1) {
+ return this.curSym + q + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 0) {
+ return q + " " + this.curSym + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 1) {
+ return this.curSym + " " + q + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 0) {
+ return q + this.curSym + " " + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 1) {
+ return this.curSym + q + " " + this.lc.negative_sign;
+ }
+
+ // sign before sym
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 0) {
+ return q + this.lc.negative_sign + this.curSym;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.curSym + q;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 0) {
+ return q + " " + this.lc.negative_sign + this.curSym;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.curSym + " " + q;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 0) {
+ return q + this.lc.negative_sign + " " + this.curSym;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + " " + this.curSym + q;
+ }
+
+ // sign after symbol
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 0) {
+ return q + this.curSym + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 1) {
+ return this.curSym + this.lc.negative_sign + q;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 0) {
+ return q + " " + this.curSym + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 1) {
+ return this.curSym + this.lc.negative_sign + " " + q;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 0) {
+ return q + this.curSym + " " + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 1) {
+ return this.curSym + " " + this.lc.negative_sign + q;
+ }
+ }
+
+ // throw error if we fall through
+ throw "Error: Invalid POSIX LC MONETARY definition";
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Assembles the final string with sign, separator and ISO-4217
+ * currency code.
+ *
+ * @param {String} sign The amount sign: "+" or "-".
+ * @param {String} q The formatted quantity (unsigned).
+ *
+ * @returns {String} The final formatted string.
+ */
+ this._formatAsInternationalCurrency = function (sign, q) {
+
+ // assemble the final formatted amount by going over all possible value combinations of:
+ // sign {+,-} , sign position {0,1,2,3,4} , separator {0,1,2} , symbol position {0,1}
+
+ if (sign == "+") {
+
+ // parentheses
+ if (this.lc.int_p_sign_posn === 0 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 0) {
+ return "(" + q + this.currencyCode + ")";
+ }
+ else if (this.lc.int_p_sign_posn === 0 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 1) {
+ return "(" + this.currencyCode + q + ")";
+ }
+ else if (this.lc.int_p_sign_posn === 0 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 0) {
+ return "(" + q + this.intSep + this.currencyCode + ")";
+ }
+ else if (this.lc.int_p_sign_posn === 0 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 1) {
+ return "(" + this.currencyCode + this.intSep + q + ")";
+ }
+
+ // sign before q + sym
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 0) {
+ return this.lc.positive_sign + q + this.currencyCode;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.currencyCode + q;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 0) {
+ return this.lc.positive_sign + q + this.intSep + this.currencyCode;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.currencyCode + this.intSep + q;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 0) {
+ return this.lc.positive_sign + this.intSep + q + this.currencyCode;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.intSep + this.currencyCode + q;
+ }
+
+ // sign after q + sym
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.currencyCode + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 1) {
+ return this.currencyCode + q + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.intSep + this.currencyCode + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 1) {
+ return this.currencyCode + this.intSep + q + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.currencyCode + this.intSep + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 1) {
+ return this.currencyCode + q + this.intSep + this.lc.positive_sign;
+ }
+
+ // sign before sym
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.lc.positive_sign + this.currencyCode;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.currencyCode + q;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.intSep + this.lc.positive_sign + this.currencyCode;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.currencyCode + this.intSep + q;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.lc.positive_sign + this.intSep + this.currencyCode;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.intSep + this.currencyCode + q;
+ }
+
+ // sign after symbol
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.currencyCode + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 1) {
+ return this.currencyCode + this.lc.positive_sign + q;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.intSep + this.currencyCode + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 1) {
+ return this.currencyCode + this.lc.positive_sign + this.intSep + q;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.currencyCode + this.intSep + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 1) {
+ return this.currencyCode + this.intSep + this.lc.positive_sign + q;
+ }
+
+ }
+ else if (sign == "-") {
+
+ // parentheses enclose q + sym
+ if (this.lc.int_n_sign_posn === 0 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 0) {
+ return "(" + q + this.currencyCode + ")";
+ }
+ else if (this.lc.int_n_sign_posn === 0 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 1) {
+ return "(" + this.currencyCode + q + ")";
+ }
+ else if (this.lc.int_n_sign_posn === 0 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 0) {
+ return "(" + q + this.intSep + this.currencyCode + ")";
+ }
+ else if (this.lc.int_n_sign_posn === 0 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 1) {
+ return "(" + this.currencyCode + this.intSep + q + ")";
+ }
+
+ // sign before q + sym
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 0) {
+ return this.lc.negative_sign + q + this.currencyCode;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.currencyCode + q;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 0) {
+ return this.lc.negative_sign + q + this.intSep + this.currencyCode;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.currencyCode + this.intSep + q;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 0) {
+ return this.lc.negative_sign + this.intSep + q + this.currencyCode;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.intSep + this.currencyCode + q;
+ }
+
+ // sign after q + sym
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.currencyCode + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 1) {
+ return this.currencyCode + q + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.intSep + this.currencyCode + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 1) {
+ return this.currencyCode + this.intSep + q + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.currencyCode + this.intSep + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 1) {
+ return this.currencyCode + q + this.intSep + this.lc.negative_sign;
+ }
+
+ // sign before sym
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.lc.negative_sign + this.currencyCode;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.currencyCode + q;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.intSep + this.lc.negative_sign + this.currencyCode;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.currencyCode + this.intSep + q;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.lc.negative_sign + this.intSep + this.currencyCode;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.intSep + this.currencyCode + q;
+ }
+
+ // sign after symbol
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.currencyCode + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 1) {
+ return this.currencyCode + this.lc.negative_sign + q;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.intSep + this.currencyCode + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 1) {
+ return this.currencyCode + this.lc.negative_sign + this.intSep + q;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.currencyCode + this.intSep + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 1) {
+ return this.currencyCode + this.intSep + this.lc.negative_sign + q;
+ }
+ }
+
+ // throw error if we fall through
+ throw "Error: Invalid POSIX LC MONETARY definition";
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Assembles the final string with sign and separator, but suppress the
+ * local currency symbol.
+ *
+ * @param {String} sign The amount sign: "+" or "-".
+ * @param {String} q The formatted quantity (unsigned).
+ *
+ * @returns {String} The final formatted string
+ */
+ this._formatAsLocalCurrencyWithNoSym = function (sign, q) {
+
+ // assemble the final formatted amount by going over all possible value combinations of:
+ // sign {+,-} , sign position {0,1,2,3,4} , separator {0,1,2} , symbol position {0,1}
+
+ if (sign == "+") {
+
+ // parentheses
+ if (this.lc.p_sign_posn === 0) {
+ return "(" + q + ")";
+ }
+
+ // sign before q + sym
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 0) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 0) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 0) {
+ return this.lc.positive_sign + " " + q;
+ }
+ else if (this.lc.p_sign_posn === 1 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + " " + q;
+ }
+
+ // sign after q + sym
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 0) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 1) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 0) {
+ return q + " " + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 1) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 0) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 2 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 1) {
+ return q + " " + this.lc.positive_sign;
+ }
+
+ // sign before sym
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 0) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 0) {
+ return q + " " + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + " " + q;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 0) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 3 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + " " + q;
+ }
+
+ // sign after symbol
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 0) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 0 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 0) {
+ return q + " " + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 1 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + " " + q;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 0) {
+ return q + " " + this.lc.positive_sign;
+ }
+ else if (this.lc.p_sign_posn === 4 && this.lc.p_sep_by_space === 2 && this.lc.p_cs_precedes === 1) {
+ return this.lc.positive_sign + q;
+ }
+
+ }
+ else if (sign == "-") {
+
+ // parentheses enclose q + sym
+ if (this.lc.n_sign_posn === 0) {
+ return "(" + q + ")";
+ }
+
+ // sign before q + sym
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 0) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 0) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + " " + q;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 0) {
+ return this.lc.negative_sign + " " + q;
+ }
+ else if (this.lc.n_sign_posn === 1 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + " " + q;
+ }
+
+ // sign after q + sym
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 0) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 1) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 0) {
+ return q + " " + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 1) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 0) {
+ return q + " " + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 2 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 1) {
+ return q + " " + this.lc.negative_sign;
+ }
+
+ // sign before sym
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 0) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 0) {
+ return q + " " + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + " " + q;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 0) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 3 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + " " + q;
+ }
+
+ // sign after symbol
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 0) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 0 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 0) {
+ return q + " " + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 1 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + " " + q;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 0) {
+ return q + " " + this.lc.negative_sign;
+ }
+ else if (this.lc.n_sign_posn === 4 && this.lc.n_sep_by_space === 2 && this.lc.n_cs_precedes === 1) {
+ return this.lc.negative_sign + q;
+ }
+ }
+
+ // throw error if we fall through
+ throw "Error: Invalid POSIX LC MONETARY definition";
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Assembles the final string with sign and separator, but suppress
+ * the ISO-4217 currency code.
+ *
+ * @param {String} sign The amount sign: "+" or "-".
+ * @param {String} q The formatted quantity (unsigned).
+ *
+ * @returns {String} The final formatted string.
+ */
+ this._formatAsInternationalCurrencyWithNoSym = function (sign, q) {
+
+ // assemble the final formatted amount by going over all possible value combinations of:
+ // sign {+,-} , sign position {0,1,2,3,4} , separator {0,1,2} , symbol position {0,1}
+
+ if (sign == "+") {
+
+ // parentheses
+ if (this.lc.int_p_sign_posn === 0) {
+ return "(" + q + ")";
+ }
+
+ // sign before q + sym
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 0) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 0) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.intSep + q;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 0) {
+ return this.lc.positive_sign + this.intSep + q;
+ }
+ else if (this.lc.int_p_sign_posn === 1 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.intSep + q;
+ }
+
+ // sign after q + sym
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 1) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.intSep + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 1) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.intSep + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 2 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 1) {
+ return q + this.intSep + this.lc.positive_sign;
+ }
+
+ // sign before sym
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.intSep + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.intSep + q;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 3 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.intSep + q;
+ }
+
+ // sign after symbol
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 0 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + q;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.intSep + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 1 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + this.intSep + q;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 0) {
+ return q + this.intSep + this.lc.positive_sign;
+ }
+ else if (this.lc.int_p_sign_posn === 4 && this.lc.int_p_sep_by_space === 2 && this.lc.int_p_cs_precedes === 1) {
+ return this.lc.positive_sign + q;
+ }
+
+ }
+ else if (sign == "-") {
+
+ // parentheses enclose q + sym
+ if (this.lc.int_n_sign_posn === 0) {
+ return "(" + q + ")";
+ }
+
+ // sign before q + sym
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 0) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 0) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.intSep + q;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 0) {
+ return this.lc.negative_sign + this.intSep + q;
+ }
+ else if (this.lc.int_n_sign_posn === 1 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.intSep + q;
+ }
+
+ // sign after q + sym
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 1) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.intSep + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 1) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.intSep + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 2 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 1) {
+ return q + this.intSep + this.lc.negative_sign;
+ }
+
+ // sign before sym
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.intSep + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.intSep + q;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 3 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.intSep + q;
+ }
+
+ // sign after symbol
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 0 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + q;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.intSep + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 1 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + this.intSep + q;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 0) {
+ return q + this.intSep + this.lc.negative_sign;
+ }
+ else if (this.lc.int_n_sign_posn === 4 && this.lc.int_n_sep_by_space === 2 && this.lc.int_n_cs_precedes === 1) {
+ return this.lc.negative_sign + q;
+ }
+ }
+
+ // throw error if we fall through
+ throw "Error: Invalid POSIX LC_MONETARY definition";
+ };
+};
+
+
+/**
+ * @class
+ * Class for parsing localised number strings.
+ *
+ * @public
+ * @constructor
+ * @description Creates a new numeric parser for the specified locale.
+ *
+ * @param {jsworld.Locale} locale A locale object specifying the required
+ * POSIX LC_NUMERIC formatting properties.
+ *
+ * @throws Error on constructor failure.
+ */
+jsworld.NumericParser = function(locale) {
+
+ if (typeof locale != "object" || locale._className != "jsworld.Locale")
+ throw "Constructor error: You must provide a valid jsworld.Locale instance";
+
+ this.lc = locale;
+
+
+ /**
+ * @public
+ *
+ * @description Parses a numeric string formatted according to the
+ * preset locale. Leading and trailing whitespace is ignored; the number
+ * may also be formatted without thousands separators.
+ *
+ * @param {String} formattedNumber The formatted number.
+ *
+ * @returns {Number} The parsed number.
+ *
+ * @throws Error on a parse exception.
+ */
+ this.parse = function(formattedNumber) {
+
+ if (typeof formattedNumber != "string")
+ throw "Parse error: Argument must be a string";
+
+ // trim whitespace
+ var s = jsworld._trim(formattedNumber);
+
+ // remove any thousand separator symbols
+ s = jsworld._stringReplaceAll(formattedNumber, this.lc.thousands_sep, "");
+
+ // replace any local decimal point symbols with the symbol used
+ // in JavaScript "."
+ s = jsworld._stringReplaceAll(s, this.lc.decimal_point, ".");
+
+ // test if the string represents a number
+ if (jsworld._isNumber(s))
+ return parseFloat(s, 10);
+ else
+ throw "Parse error: Invalid number string";
+ };
+};
+
+
+/**
+ * @class
+ * Class for parsing localised date and time strings.
+ *
+ * @public
+ * @constructor
+ * @description Creates a new date/time parser for the specified locale.
+ *
+ * @param {jsworld.Locale} locale A locale object specifying the required
+ * POSIX LC_TIME formatting properties.
+ *
+ * @throws Error on constructor failure.
+ */
+jsworld.DateTimeParser = function(locale) {
+
+ if (typeof locale != "object" || locale._className != "jsworld.Locale")
+ throw "Constructor error: You must provide a valid jsworld.Locale instance.";
+
+ this.lc = locale;
+
+
+ /**
+ * @public
+ *
+ * @description Parses a time string formatted according to the
+ * POSIX LC_TIME t_fmt property of the preset locale.
+ *
+ * @param {String} formattedTime The formatted time.
+ *
+ * @returns {String} The parsed time in ISO-8601 format (HH:MM:SS), e.g.
+ * "23:59:59".
+ *
+ * @throws Error on a parse exception.
+ */
+ this.parseTime = function(formattedTime) {
+
+ if (typeof formattedTime != "string")
+ throw "Parse error: Argument must be a string";
+
+ var dt = this._extractTokens(this.lc.t_fmt, formattedTime);
+
+ var timeDefined = false;
+
+ if (dt.hour !== null && dt.minute !== null && dt.second !== null) {
+ timeDefined = true;
+ }
+ else if (dt.hourAmPm !== null && dt.am !== null && dt.minute !== null && dt.second !== null) {
+ if (dt.am) {
+ // AM [12(midnight), 1 .. 11]
+ if (dt.hourAmPm == 12)
+ dt.hour = 0;
+ else
+ dt.hour = parseInt(dt.hourAmPm, 10);
+ }
+ else {
+ // PM [12(noon), 1 .. 11]
+ if (dt.hourAmPm == 12)
+ dt.hour = 12;
+ else
+ dt.hour = parseInt(dt.hourAmPm, 10) + 12;
+ }
+ timeDefined = true;
+ }
+
+ if (timeDefined)
+ return jsworld._zeroPad(dt.hour, 2) +
+ ":" +
+ jsworld._zeroPad(dt.minute, 2) +
+ ":" +
+ jsworld._zeroPad(dt.second, 2);
+ else
+ throw "Parse error: Invalid/ambiguous time string";
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Parses a date string formatted according to the
+ * POSIX LC_TIME d_fmt property of the preset locale.
+ *
+ * @param {String} formattedDate The formatted date, must be valid.
+ *
+ * @returns {String} The parsed date in ISO-8601 format (YYYY-MM-DD),
+ * e.g. "2010-03-31".
+ *
+ * @throws Error on a parse exception.
+ */
+ this.parseDate = function(formattedDate) {
+
+ if (typeof formattedDate != "string")
+ throw "Parse error: Argument must be a string";
+
+ var dt = this._extractTokens(this.lc.d_fmt, formattedDate);
+
+ var dateDefined = false;
+
+ if (dt.year !== null && dt.month !== null && dt.day !== null) {
+ dateDefined = true;
+ }
+
+ if (dateDefined)
+ return jsworld._zeroPad(dt.year, 4) +
+ "-" +
+ jsworld._zeroPad(dt.month, 2) +
+ "-" +
+ jsworld._zeroPad(dt.day, 2);
+ else
+ throw "Parse error: Invalid date string";
+ };
+
+
+ /**
+ * @public
+ *
+ * @description Parses a date/time string formatted according to the
+ * POSIX LC_TIME d_t_fmt property of the preset locale.
+ *
+ * @param {String} formattedDateTime The formatted date/time, must be
+ * valid.
+ *
+ * @returns {String} The parsed date/time in ISO-8601 format
+ * (YYYY-MM-DD HH:MM:SS), e.g. "2010-03-31 23:59:59".
+ *
+ * @throws Error on a parse exception.
+ */
+ this.parseDateTime = function(formattedDateTime) {
+
+ if (typeof formattedDateTime != "string")
+ throw "Parse error: Argument must be a string";
+
+ var dt = this._extractTokens(this.lc.d_t_fmt, formattedDateTime);
+
+ var timeDefined = false;
+ var dateDefined = false;
+
+ if (dt.hour !== null && dt.minute !== null && dt.second !== null) {
+ timeDefined = true;
+ }
+ else if (dt.hourAmPm !== null && dt.am !== null && dt.minute !== null && dt.second !== null) {
+ if (dt.am) {
+ // AM [12(midnight), 1 .. 11]
+ if (dt.hourAmPm == 12)
+ dt.hour = 0;
+ else
+ dt.hour = parseInt(dt.hourAmPm, 10);
+ }
+ else {
+ // PM [12(noon), 1 .. 11]
+ if (dt.hourAmPm == 12)
+ dt.hour = 12;
+ else
+ dt.hour = parseInt(dt.hourAmPm, 10) + 12;
+ }
+ timeDefined = true;
+ }
+
+ if (dt.year !== null && dt.month !== null && dt.day !== null) {
+ dateDefined = true;
+ }
+
+ if (dateDefined && timeDefined)
+ return jsworld._zeroPad(dt.year, 4) +
+ "-" +
+ jsworld._zeroPad(dt.month, 2) +
+ "-" +
+ jsworld._zeroPad(dt.day, 2) +
+ " " +
+ jsworld._zeroPad(dt.hour, 2) +
+ ":" +
+ jsworld._zeroPad(dt.minute, 2) +
+ ":" +
+ jsworld._zeroPad(dt.second, 2);
+ else
+ throw "Parse error: Invalid/ambiguous date/time string";
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Parses a string according to the specified format
+ * specification.
+ *
+ * @param {String} fmtSpec The format specification, e.g. "%I:%M:%S %p".
+ * @param {String} s The string to parse.
+ *
+ * @returns {object} An object with set properties year, month, day,
+ * hour, minute and second if the corresponding values are
+ * found in the parsed string.
+ *
+ * @throws Error on a parse exception.
+ */
+ this._extractTokens = function(fmtSpec, s) {
+
+ // the return object containing the parsed date/time properties
+ var dt = {
+ // for date and date/time strings
+ "year" : null,
+ "month" : null,
+ "day" : null,
+
+ // for time and date/time strings
+ "hour" : null,
+ "hourAmPm" : null,
+ "am" : null,
+ "minute" : null,
+ "second" : null,
+
+ // used internally only
+ "weekday" : null
+ };
+
+
+ // extract and process each token in the date/time spec
+ while (fmtSpec.length > 0) {
+
+ // Do we have a valid "%\w" placeholder in stream?
+ if (fmtSpec.charAt(0) == "%" && fmtSpec.charAt(1) != "") {
+
+ // get placeholder
+ var placeholder = fmtSpec.substring(0,2);
+
+ if (placeholder == "%%") {
+ // escaped '%''
+ s = s.substring(1);
+ }
+ else if (placeholder == "%a") {
+ // abbreviated weekday name
+ for (var i = 0; i < this.lc.abday.length; i++) {
+
+ if (jsworld._stringStartsWith(s, this.lc.abday[i])) {
+ dt.weekday = i;
+ s = s.substring(this.lc.abday[i].length);
+ break;
+ }
+ }
+
+ if (dt.weekday === null)
+ throw "Parse error: Unrecognised abbreviated weekday name (%a)";
+ }
+ else if (placeholder == "%A") {
+ // weekday name
+ for (var i = 0; i < this.lc.day.length; i++) {
+
+ if (jsworld._stringStartsWith(s, this.lc.day[i])) {
+ dt.weekday = i;
+ s = s.substring(this.lc.day[i].length);
+ break;
+ }
+ }
+
+ if (dt.weekday === null)
+ throw "Parse error: Unrecognised weekday name (%A)";
+ }
+ else if (placeholder == "%b" || placeholder == "%h") {
+ // abbreviated month name
+ for (var i = 0; i < this.lc.abmon.length; i++) {
+
+ if (jsworld._stringStartsWith(s, this.lc.abmon[i])) {
+ dt.month = i + 1;
+ s = s.substring(this.lc.abmon[i].length);
+ break;
+ }
+ }
+
+ if (dt.month === null)
+ throw "Parse error: Unrecognised abbreviated month name (%b)";
+ }
+ else if (placeholder == "%B") {
+ // month name
+ for (var i = 0; i < this.lc.mon.length; i++) {
+
+ if (jsworld._stringStartsWith(s, this.lc.mon[i])) {
+ dt.month = i + 1;
+ s = s.substring(this.lc.mon[i].length);
+ break;
+ }
+ }
+
+ if (dt.month === null)
+ throw "Parse error: Unrecognised month name (%B)";
+ }
+ else if (placeholder == "%d") {
+ // day of the month [01..31]
+ if (/^0[1-9]|[1-2][0-9]|3[0-1]/.test(s)) {
+ dt.day = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised day of the month (%d)";
+ }
+ else if (placeholder == "%e") {
+ // day of the month [1..31]
+
+ // Note: if %e is leading in fmt string -> space padded!
+
+ var day = s.match(/^\s?(\d{1,2})/);
+ dt.day = parseInt(day, 10);
+
+ if (isNaN(dt.day) || dt.day < 1 || dt.day > 31)
+ throw "Parse error: Unrecognised day of the month (%e)";
+
+ s = s.substring(day.length);
+ }
+ else if (placeholder == "%F") {
+ // equivalent to %Y-%m-%d (ISO-8601 date format)
+
+ // year [nnnn]
+ if (/^\d\d\d\d/.test(s)) {
+ dt.year = parseInt(s.substring(0,4), 10);
+ s = s.substring(4);
+ }
+ else {
+ throw "Parse error: Unrecognised date (%F)";
+ }
+
+ // -
+ if (jsworld._stringStartsWith(s, "-"))
+ s = s.substring(1);
+ else
+ throw "Parse error: Unrecognised date (%F)";
+
+ // month [01..12]
+ if (/^0[1-9]|1[0-2]/.test(s)) {
+ dt.month = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised date (%F)";
+
+ // -
+ if (jsworld._stringStartsWith(s, "-"))
+ s = s.substring(1);
+ else
+ throw "Parse error: Unrecognised date (%F)";
+
+ // day of the month [01..31]
+ if (/^0[1-9]|[1-2][0-9]|3[0-1]/.test(s)) {
+ dt.day = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised date (%F)";
+ }
+ else if (placeholder == "%H") {
+ // hour [00..23]
+ if (/^[0-1][0-9]|2[0-3]/.test(s)) {
+ dt.hour = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised hour (%H)";
+ }
+ else if (placeholder == "%I") {
+ // hour [01..12]
+ if (/^0[1-9]|1[0-2]/.test(s)) {
+ dt.hourAmPm = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised hour (%I)";
+ }
+ else if (placeholder == "%k") {
+ // hour [0..23]
+ var h = s.match(/^(\d{1,2})/);
+ dt.hour = parseInt(h, 10);
+
+ if (isNaN(dt.hour) || dt.hour < 0 || dt.hour > 23)
+ throw "Parse error: Unrecognised hour (%k)";
+
+ s = s.substring(h.length);
+ }
+ else if (placeholder == "%l") {
+ // hour AM/PM [1..12]
+ var h = s.match(/^(\d{1,2})/);
+ dt.hourAmPm = parseInt(h, 10);
+
+ if (isNaN(dt.hourAmPm) || dt.hourAmPm < 1 || dt.hourAmPm > 12)
+ throw "Parse error: Unrecognised hour (%l)";
+
+ s = s.substring(h.length);
+ }
+ else if (placeholder == "%m") {
+ // month [01..12]
+ if (/^0[1-9]|1[0-2]/.test(s)) {
+ dt.month = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised month (%m)";
+ }
+ else if (placeholder == "%M") {
+ // minute [00..59]
+ if (/^[0-5][0-9]/.test(s)) {
+ dt.minute = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised minute (%M)";
+ }
+ else if (placeholder == "%n") {
+ // new line
+
+ if (s.charAt(0) == "\n")
+ s = s.substring(1);
+ else
+ throw "Parse error: Unrecognised new line (%n)";
+ }
+ else if (placeholder == "%p") {
+ // locale's equivalent of AM/PM
+ if (jsworld._stringStartsWith(s, this.lc.am)) {
+ dt.am = true;
+ s = s.substring(this.lc.am.length);
+ }
+ else if (jsworld._stringStartsWith(s, this.lc.pm)) {
+ dt.am = false;
+ s = s.substring(this.lc.pm.length);
+ }
+ else
+ throw "Parse error: Unrecognised AM/PM value (%p)";
+ }
+ else if (placeholder == "%P") {
+ // same as %p but forced lower case
+ if (jsworld._stringStartsWith(s, this.lc.am.toLowerCase())) {
+ dt.am = true;
+ s = s.substring(this.lc.am.length);
+ }
+ else if (jsworld._stringStartsWith(s, this.lc.pm.toLowerCase())) {
+ dt.am = false;
+ s = s.substring(this.lc.pm.length);
+ }
+ else
+ throw "Parse error: Unrecognised AM/PM value (%P)";
+ }
+ else if (placeholder == "%R") {
+ // same as %H:%M
+
+ // hour [00..23]
+ if (/^[0-1][0-9]|2[0-3]/.test(s)) {
+ dt.hour = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised time (%R)";
+
+ // :
+ if (jsworld._stringStartsWith(s, ":"))
+ s = s.substring(1);
+ else
+ throw "Parse error: Unrecognised time (%R)";
+
+ // minute [00..59]
+ if (/^[0-5][0-9]/.test(s)) {
+ dt.minute = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised time (%R)";
+
+ }
+ else if (placeholder == "%S") {
+ // second [00..59]
+ if (/^[0-5][0-9]/.test(s)) {
+ dt.second = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised second (%S)";
+ }
+ else if (placeholder == "%T") {
+ // same as %H:%M:%S
+
+ // hour [00..23]
+ if (/^[0-1][0-9]|2[0-3]/.test(s)) {
+ dt.hour = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised time (%T)";
+
+ // :
+ if (jsworld._stringStartsWith(s, ":"))
+ s = s.substring(1);
+ else
+ throw "Parse error: Unrecognised time (%T)";
+
+ // minute [00..59]
+ if (/^[0-5][0-9]/.test(s)) {
+ dt.minute = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised time (%T)";
+
+ // :
+ if (jsworld._stringStartsWith(s, ":"))
+ s = s.substring(1);
+ else
+ throw "Parse error: Unrecognised time (%T)";
+
+ // second [00..59]
+ if (/^[0-5][0-9]/.test(s)) {
+ dt.second = parseInt(s.substring(0,2), 10);
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised time (%T)";
+ }
+ else if (placeholder == "%w") {
+ // weekday [0..6]
+ if (/^\d/.test(s)) {
+ dt.weekday = parseInt(s.substring(0,1), 10);
+ s = s.substring(1);
+ }
+ else
+ throw "Parse error: Unrecognised weekday number (%w)";
+ }
+ else if (placeholder == "%y") {
+ // year [00..99]
+ if (/^\d\d/.test(s)) {
+ var year2digits = parseInt(s.substring(0,2), 10);
+
+ // this conversion to year[nnnn] is arbitrary!!!
+ if (year2digits > 50)
+ dt.year = 1900 + year2digits;
+ else
+ dt.year = 2000 + year2digits;
+
+ s = s.substring(2);
+ }
+ else
+ throw "Parse error: Unrecognised year (%y)";
+ }
+ else if (placeholder == "%Y") {
+ // year [nnnn]
+ if (/^\d\d\d\d/.test(s)) {
+ dt.year = parseInt(s.substring(0,4), 10);
+ s = s.substring(4);
+ }
+ else
+ throw "Parse error: Unrecognised year (%Y)";
+ }
+
+ else if (placeholder == "%Z") {
+ // time-zone place holder is not supported
+
+ if (fmtSpec.length === 0)
+ break; // ignore rest of fmt spec
+ }
+
+ // remove the spec placeholder that was just parsed
+ fmtSpec = fmtSpec.substring(2);
+ }
+ else {
+ // If we don't have a placeholder, the chars
+ // at pos. 0 of format spec and parsed string must match
+
+ // Note: Space chars treated 1:1 !
+
+ if (fmtSpec.charAt(0) != s.charAt(0))
+ throw "Parse error: Unexpected symbol \"" + s.charAt(0) + "\" in date/time string";
+
+ fmtSpec = fmtSpec.substring(1);
+ s = s.substring(1);
+ }
+ }
+
+ // parsing finished, return composite date/time object
+ return dt;
+ };
+};
+
+
+/**
+ * @class
+ * Class for parsing localised currency amount strings.
+ *
+ * @public
+ * @constructor
+ * @description Creates a new monetary parser for the specified locale.
+ *
+ * @param {jsworld.Locale} locale A locale object specifying the required
+ * POSIX LC_MONETARY formatting properties.
+ *
+ * @throws Error on constructor failure.
+ */
+jsworld.MonetaryParser = function(locale) {
+
+ if (typeof locale != "object" || locale._className != "jsworld.Locale")
+ throw "Constructor error: You must provide a valid jsworld.Locale instance";
+
+
+ this.lc = locale;
+
+
+ /**
+ * @public
+ *
+ * @description Parses a currency amount string formatted according to
+ * the preset locale. Leading and trailing whitespace is ignored; the
+ * amount may also be formatted without thousands separators. Both
+ * the local (shorthand) symbol and the ISO 4217 code are accepted to
+ * designate the currency in the formatted amount.
+ *
+ * @param {String} formattedCurrency The formatted currency amount.
+ *
+ * @returns {Number} The parsed amount.
+ *
+ * @throws Error on a parse exception.
+ */
+ this.parse = function(formattedCurrency) {
+
+ if (typeof formattedCurrency != "string")
+ throw "Parse error: Argument must be a string";
+
+ // Detect the format type and remove the currency symbol
+ var symbolType = this._detectCurrencySymbolType(formattedCurrency);
+
+ var formatType, s;
+
+ if (symbolType == "local") {
+ formatType = "local";
+ s = formattedCurrency.replace(this.lc.getCurrencySymbol(), "");
+ }
+ else if (symbolType == "int") {
+ formatType = "int";
+ s = formattedCurrency.replace(this.lc.getIntCurrencySymbol(), "");
+ }
+ else if (symbolType == "none") {
+ formatType = "local"; // assume local
+ s = formattedCurrency;
+ }
+ else
+ throw "Parse error: Internal assert failure";
+
+ // Remove any thousands separators
+ s = jsworld._stringReplaceAll(s, this.lc.mon_thousands_sep, "");
+
+ // Replace any local radix char with JavaScript's "."
+ s = s.replace(this.lc.mon_decimal_point, ".");
+
+ // Remove all whitespaces
+ s = s.replace(/\s*/g, "");
+
+ // Remove any local non-negative sign
+ s = this._removeLocalNonNegativeSign(s, formatType);
+
+ // Replace any local minus sign with JavaScript's "-" and put
+ // it in front of the amount if necessary
+ // (special parentheses rule checked too)
+ s = this._normaliseNegativeSign(s, formatType);
+
+ // Finally, we should be left with a bare parsable decimal number
+ if (jsworld._isNumber(s))
+ return parseFloat(s, 10);
+ else
+ throw "Parse error: Invalid currency amount string";
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Tries to detect the symbol type used in the specified
+ * formatted currency string: local(shorthand),
+ * international (ISO-4217 code) or none.
+ *
+ * @param {String} formattedCurrency The the formatted currency string.
+ *
+ * @return {String} With possible values "local", "int" or "none".
+ */
+ this._detectCurrencySymbolType = function(formattedCurrency) {
+
+ // Check for whichever sign (int/local) is longer first
+ // to cover cases such as MOP/MOP$ and ZAR/R
+
+ if (this.lc.getCurrencySymbol().length > this.lc.getIntCurrencySymbol().length) {
+
+ if (formattedCurrency.indexOf(this.lc.getCurrencySymbol()) != -1)
+ return "local";
+ else if (formattedCurrency.indexOf(this.lc.getIntCurrencySymbol()) != -1)
+ return "int";
+ else
+ return "none";
+ }
+ else {
+ if (formattedCurrency.indexOf(this.lc.getIntCurrencySymbol()) != -1)
+ return "int";
+ else if (formattedCurrency.indexOf(this.lc.getCurrencySymbol()) != -1)
+ return "local";
+ else
+ return "none";
+ }
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Removes a local non-negative sign in a formatted
+ * currency string if it is found. This is done according to the
+ * locale properties p_sign_posn and int_p_sign_posn.
+ *
+ * @param {String} s The input string.
+ * @param {String} formatType With possible values "local" or "int".
+ *
+ * @returns {String} The processed string.
+ */
+ this._removeLocalNonNegativeSign = function(s, formatType) {
+
+ s = s.replace(this.lc.positive_sign, "");
+
+ // check for enclosing parentheses rule
+ if (((formatType == "local" && this.lc.p_sign_posn === 0) ||
+ (formatType == "int" && this.lc.int_p_sign_posn === 0) ) &&
+ /\(\d+\.?\d*\)/.test(s)) {
+ s = s.replace("(", "");
+ s = s.replace(")", "");
+ }
+
+ return s;
+ };
+
+
+ /**
+ * @private
+ *
+ * @description Replaces a local negative sign with the standard
+ * JavaScript minus ("-") sign placed in the correct position
+ * (preceding the amount). This is done according to the locale
+ * properties for negative sign symbol and relative position.
+ *
+ * @param {String} s The input string.
+ * @param {String} formatType With possible values "local" or "int".
+ *
+ * @returns {String} The processed string.
+ */
+ this._normaliseNegativeSign = function(s, formatType) {
+
+ // replace local negative symbol with JavaScript's "-"
+ s = s.replace(this.lc.negative_sign, "-");
+
+ // check for enclosing parentheses rule and replace them
+ // with negative sign before the amount
+ if ((formatType == "local" && this.lc.n_sign_posn === 0) ||
+ (formatType == "int" && this.lc.int_n_sign_posn === 0) ) {
+
+ if (/^\(\d+\.?\d*\)$/.test(s)) {
+
+ s = s.replace("(", "");
+ s = s.replace(")", "");
+ return "-" + s;
+ }
+ }
+
+ // check for rule negative sign succeeding the amount
+ if (formatType == "local" && this.lc.n_sign_posn == 2 ||
+ formatType == "int" && this.lc.int_n_sign_posn == 2 ) {
+
+ if (/^\d+\.?\d*-$/.test(s)) {
+ s = s.replace("-", "");
+ return "-" + s;
+ }
+ }
+
+ // check for rule cur. sym. succeeds and sign adjacent
+ if (formatType == "local" && this.lc.n_cs_precedes === 0 && this.lc.n_sign_posn == 3 ||
+ formatType == "local" && this.lc.n_cs_precedes === 0 && this.lc.n_sign_posn == 4 ||
+ formatType == "int" && this.lc.int_n_cs_precedes === 0 && this.lc.int_n_sign_posn == 3 ||
+ formatType == "int" && this.lc.int_n_cs_precedes === 0 && this.lc.int_n_sign_posn == 4 ) {
+
+ if (/^\d+\.?\d*-$/.test(s)) {
+ s = s.replace("-", "");
+ return "-" + s;
+ }
+ }
+
+ return s;
+ };
+};
+
+// end-of-file
diff --git a/node_modules/handlebars/node_modules/uglify-js/tmp/uglify-hangs2.js b/node_modules/handlebars/node_modules/uglify-js/tmp/uglify-hangs2.js
new file mode 100644
index 0000000000..4e9f96721d
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/tmp/uglify-hangs2.js
@@ -0,0 +1,166 @@
+jsworld.Locale = function(properties) {
+
+ // LC_NUMERIC
+
+
+ this.frac_digits = properties.frac_digits;
+
+
+ // may be empty string/null for currencies with no fractional part
+ if (properties.mon_decimal_point === null || properties.mon_decimal_point == "") {
+
+ if (this.frac_digits > 0)
+ throw "Error: Undefined mon_decimal_point property";
+ else
+ properties.mon_decimal_point = "";
+ }
+
+ if (typeof properties.mon_decimal_point != "string")
+ throw "Error: Invalid/missing mon_decimal_point property";
+
+ this.mon_decimal_point = properties.mon_decimal_point;
+
+
+ if (typeof properties.mon_thousands_sep != "string")
+ throw "Error: Invalid/missing mon_thousands_sep property";
+
+ this.mon_thousands_sep = properties.mon_thousands_sep;
+
+
+ if (typeof properties.mon_grouping != "string")
+ throw "Error: Invalid/missing mon_grouping property";
+
+ this.mon_grouping = properties.mon_grouping;
+
+
+ if (typeof properties.positive_sign != "string")
+ throw "Error: Invalid/missing positive_sign property";
+
+ this.positive_sign = properties.positive_sign;
+
+
+ if (typeof properties.negative_sign != "string")
+ throw "Error: Invalid/missing negative_sign property";
+
+ this.negative_sign = properties.negative_sign;
+
+
+ if (properties.p_cs_precedes !== 0 && properties.p_cs_precedes !== 1)
+ throw "Error: Invalid/missing p_cs_precedes property, must be 0 or 1";
+
+ this.p_cs_precedes = properties.p_cs_precedes;
+
+
+ if (properties.n_cs_precedes !== 0 && properties.n_cs_precedes !== 1)
+ throw "Error: Invalid/missing n_cs_precedes, must be 0 or 1";
+
+ this.n_cs_precedes = properties.n_cs_precedes;
+
+
+ if (properties.p_sep_by_space !== 0 &&
+ properties.p_sep_by_space !== 1 &&
+ properties.p_sep_by_space !== 2)
+ throw "Error: Invalid/missing p_sep_by_space property, must be 0, 1 or 2";
+
+ this.p_sep_by_space = properties.p_sep_by_space;
+
+
+ if (properties.n_sep_by_space !== 0 &&
+ properties.n_sep_by_space !== 1 &&
+ properties.n_sep_by_space !== 2)
+ throw "Error: Invalid/missing n_sep_by_space property, must be 0, 1, or 2";
+
+ this.n_sep_by_space = properties.n_sep_by_space;
+
+
+ if (properties.p_sign_posn !== 0 &&
+ properties.p_sign_posn !== 1 &&
+ properties.p_sign_posn !== 2 &&
+ properties.p_sign_posn !== 3 &&
+ properties.p_sign_posn !== 4)
+ throw "Error: Invalid/missing p_sign_posn property, must be 0, 1, 2, 3 or 4";
+
+ this.p_sign_posn = properties.p_sign_posn;
+
+
+ if (properties.n_sign_posn !== 0 &&
+ properties.n_sign_posn !== 1 &&
+ properties.n_sign_posn !== 2 &&
+ properties.n_sign_posn !== 3 &&
+ properties.n_sign_posn !== 4)
+ throw "Error: Invalid/missing n_sign_posn property, must be 0, 1, 2, 3 or 4";
+
+ this.n_sign_posn = properties.n_sign_posn;
+
+
+ if (typeof properties.int_frac_digits != "number" && properties.int_frac_digits < 0)
+ throw "Error: Invalid/missing int_frac_digits property";
+
+ this.int_frac_digits = properties.int_frac_digits;
+
+
+ if (properties.int_p_cs_precedes !== 0 && properties.int_p_cs_precedes !== 1)
+ throw "Error: Invalid/missing int_p_cs_precedes property, must be 0 or 1";
+
+ this.int_p_cs_precedes = properties.int_p_cs_precedes;
+
+
+ if (properties.int_n_cs_precedes !== 0 && properties.int_n_cs_precedes !== 1)
+ throw "Error: Invalid/missing int_n_cs_precedes property, must be 0 or 1";
+
+ this.int_n_cs_precedes = properties.int_n_cs_precedes;
+
+
+ if (properties.int_p_sep_by_space !== 0 &&
+ properties.int_p_sep_by_space !== 1 &&
+ properties.int_p_sep_by_space !== 2)
+ throw "Error: Invalid/missing int_p_sep_by_spacev, must be 0, 1 or 2";
+
+ this.int_p_sep_by_space = properties.int_p_sep_by_space;
+
+
+ if (properties.int_n_sep_by_space !== 0 &&
+ properties.int_n_sep_by_space !== 1 &&
+ properties.int_n_sep_by_space !== 2)
+ throw "Error: Invalid/missing int_n_sep_by_space property, must be 0, 1, or 2";
+
+ this.int_n_sep_by_space = properties.int_n_sep_by_space;
+
+
+ if (properties.int_p_sign_posn !== 0 &&
+ properties.int_p_sign_posn !== 1 &&
+ properties.int_p_sign_posn !== 2 &&
+ properties.int_p_sign_posn !== 3 &&
+ properties.int_p_sign_posn !== 4)
+ throw "Error: Invalid/missing int_p_sign_posn property, must be 0, 1, 2, 3 or 4";
+
+ this.int_p_sign_posn = properties.int_p_sign_posn;
+
+
+ if (properties.int_n_sign_posn !== 0 &&
+ properties.int_n_sign_posn !== 1 &&
+ properties.int_n_sign_posn !== 2 &&
+ properties.int_n_sign_posn !== 3 &&
+ properties.int_n_sign_posn !== 4)
+ throw "Error: Invalid/missing int_n_sign_posn property, must be 0, 1, 2, 3 or 4";
+
+ this.int_n_sign_posn = properties.int_n_sign_posn;
+
+
+ // LC_TIME
+
+ if (properties == null || typeof properties != "object")
+ throw "Error: Invalid/missing time locale properties";
+
+
+ // parse the supported POSIX LC_TIME properties
+
+ // abday
+ try {
+ this.abday = this._parseList(properties.abday, 7);
+ }
+ catch (error) {
+ throw "Error: Invalid abday property: " + error;
+ }
+
+}
diff --git a/node_modules/handlebars/node_modules/uglify-js/uglify-js.js b/node_modules/handlebars/node_modules/uglify-js/uglify-js.js
new file mode 100644
index 0000000000..6e14a637e8
--- /dev/null
+++ b/node_modules/handlebars/node_modules/uglify-js/uglify-js.js
@@ -0,0 +1,18 @@
+//convienence function(src, [options]);
+function uglify(orig_code, options){
+ options || (options = {});
+ var jsp = uglify.parser;
+ var pro = uglify.uglify;
+
+ var ast = jsp.parse(orig_code, options.strict_semicolons); // parse code and get the initial AST
+ ast = pro.ast_mangle(ast, options.mangle_options); // get a new AST with mangled names
+ ast = pro.ast_squeeze(ast, options.squeeze_options); // get an AST with compression optimizations
+ var final_code = pro.gen_code(ast, options.gen_options); // compressed code here
+ return final_code;
+};
+
+uglify.parser = require("./lib/parse-js");
+uglify.uglify = require("./lib/process");
+uglify.consolidator = require("./lib/consolidator");
+
+module.exports = uglify
diff --git a/node_modules/handlebars/package.json b/node_modules/handlebars/package.json
new file mode 100644
index 0000000000..56518d1b7a
--- /dev/null
+++ b/node_modules/handlebars/package.json
@@ -0,0 +1,41 @@
+{
+ "name": "handlebars",
+ "description": "Extension of the Mustache logicless template language",
+ "version": "1.0.9",
+ "homepage": "http://www.handlebarsjs.com/",
+ "keywords": [
+ "handlebars mustache template html"
+ ],
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/wycats/handlebars.js.git"
+ },
+ "engines": {
+ "node": ">=0.4.7"
+ },
+ "dependencies": {
+ "optimist": "~0.3",
+ "uglify-js": "~1.2"
+ },
+ "devDependencies": {
+ "benchmark": "~1.0",
+ "dust": "~0.3",
+ "jison": "~0.3",
+ "mocha": "*",
+ "mustache": "~0.7.2"
+ },
+ "main": "lib/handlebars.js",
+ "bin": {
+ "handlebars": "bin/handlebars"
+ },
+ "scripts": {
+ "test": "node_modules/.bin/mocha -u qunit spec/qunit_spec.js"
+ },
+ "optionalDependencies": {},
+ "_id": "handlebars@1.0.9",
+ "_engineSupported": true,
+ "_npmVersion": "1.1.4",
+ "_nodeVersion": "v0.6.19",
+ "_defaultsLoaded": true,
+ "_from": "handlebars"
+}